Geeks With Blogs
Gaurav Taneja Great dreams... never even get out of the box. It takes an uncommon amount of guts to put your dreams on the line, to hold them up and say, "How good or how bad am I?" That's where courage comes in.

 

When was .NET announced?
Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET.

 

When was the first version of .NET released?
The final version of the 1.0 SDK and runtime was made publicly available around 6pm PST on 15-Jan-2002. At the same time, the final version of Visual Studio.NET was made available to MSDN subscribers.

 

What platforms does the .NET Framework run on?
The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported. Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on Windows XP and Windows 2000. Windows 98/ME cannot be used for development.
IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the ASP.NET Web Matrix

web server does run on XP Home.
The Mono project is attempting to implement the .NET framework on Linux.

 

What is the CLR?
CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can take advantage of, regardless of programming language. Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article:
Object-oriented programming model (inheritance, polymorphism, exception handling, garbage collection)
 Security model
 Type system
 All .NET base classes
 Many .NET framework classes
 Development, debugging, and profiling tools
 Execution and code management
 IL-to-native translators and optimizers

What this means is that in the .NET world, different programming languages will be more equal in capability than they have ever been before, although clearly not all languages will support all CLR services.

 

What is the CTS?
CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that .NET applications can use. However note that not all .NET languages will support all the types in the CTS. The CTS is a superset of the CLS.

 

What is the CLS?
CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language.
In theory this allows very tight interop between different .NET languages - for example allowing a C# class to inherit from a VB class.

 

What is IL?
IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code (of any language) is compiled to IL. The IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

 

What does 'managed' mean in the .NET context?
The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly different things.Managed code: The .NET framework provides several core run-time services to the programs that run within it - for example

exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime.

Such code is called managed code. All C# and Visual Basic.NET code is managed by default. VS7 C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/com+).
Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+ switch, but it can be marked as managed using the __gc keyword.Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can only inherit from one base class.

 

What is reflection?
All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.
Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember ) ,  or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

 

What is the difference between Finalize and Dispose (Garbage collection) ?

Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object. In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object.

Dispose can be called even if other references to the object are alive. Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from

permanently leaking if the programmer fails to call Dispose.

 

What is Partial Assembly References?

Full Assembly reference: A full assembly reference includes the assembly's text name, version, culture, and public key token (if the assembly has a strong name). A full assembly reference is required if you reference any assembly that is part of the common

language runtime or any assembly located in the global assembly cache.

 

Partial Assembly reference: We can dynamically reference an assembly by providing only partial information, such as specifying only the assembly name. When you specify a partial assembly reference, the runtime looks for the assembly only in the application

directory.
We can make partial references to an assembly in your code one of the following ways:
-> Use a method such as System.Reflection.Assembly.Load and specify only a partial reference. The runtime checks for the assembly in the application directory.
-> Use the System.Reflection.Assembly.LoadWithPartialName method and specify only a partial reference. The runtime checks for the assembly in the application directory and in the global assembly cache

 

Changes to which portion of version number indicates an incompatible change?
Major or minor. Changes to the major or minor portion of the version number indicate an incompatible change. Under this convention then, version 2.0.0.0 would be considered incompatible with version 1.0.0.0. Examples of an incompatible change would be a change to the types of some method parameters or the removal of a type or method altogether. Build. The Build number is typically used to distinguish between daily builds or smaller compatible releases. Revision. Changes to the revision number are typically reserved for an incremental build needed to fix a particular bug. You'll sometimes hear this referred to as the "emergency bug fix" number in that the revision is what is often changed when a fix to a specific bug is

 

What is side-by-side execution? Can two application one using private assembly and other using Shared assembly be stated as a side-by-side executables?
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. Since versioning is only applied to shared assemblies, and not to private assemblies, two application one using private assembly and one using shared assembly cannot be stated as side-by-side

executables.

 

Why string are called Immutable data Type ?
The memory representation of string is an Array of Characters, So on re-assigning the new array of Char is formed & the start address is changed . Thus keeping the Old string in Memory for Garbage Collector to be disposed.

 

What does assert() method do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

 

What's the difference between the Debug class and Trace class?
Documentation looks the same.  Use Debug class for debug builds, use Trace class for both debug and release builds.

 

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.

 

Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.

 

How do assemblies find each other?
By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache.

 

How does assembly versioning work?
Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly.The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file.

 

What is an Application Domain?
An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate an application from other applications. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory.

 

What is garbage collection?
Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.

 

Why doesn't the .NET runtime offer deterministic destruction?
Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next sweep of the heap.
Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep.

 

Is the lack of deterministic destruction in .NET a problem?
It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way for the client to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some form of reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this.

 

What is serialization?
Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization / Deserialization is mostly used to transport objects (e.g. during remoting), or to persist

objects (e.g. to a file or database).

 

Does the .NET Framework have in-built support for serialization?
There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

 

Can I customise the serialization process?
Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement]

attribute, which can be used to specify the XML element name to be used for a particular property or field.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized.

 

Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

 

Why do I get errors when I try to serialize a Hashtable?
XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

 

What are attributes?
There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection.
The other type of attribute is a context attribute. Context attributes use a similar syntax to metadata attributes but they are fundamentally different. Context attributes provide an interception mechanism whereby instance activation and method calls can be

pre- and/or post-processed.

 

How does CAS work?
The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set.
For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.)

 

Who defines the CAS code groups?
Microsoft defines some default ones, but you can modify these and even create your own. To see the code groups defined on your system, run 'caspol -lg' from the command-line. On my system it looks like this:
Level = Machine

Code Groups:

1.  All code: Nothing
   1.1.  Zone - MyComputer: FullTrust
      1.1.1.  Honor SkipVerification requests: SkipVerification
   1.2.  Zone - Intranet: LocalIntranet
   1.3.  Zone - Internet: Internet
   1.4.  Zone - Untrusted: Nothing
   1.5.  Zone - Trusted: Internet
   1.6.  StrongName - 0024000004800000940000000602000000240000525341310004000003
000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD06
F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E08
07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5C
AC1DF1734633C602F8F2D5: 

Note the hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then sub-divided into several

groups, each of which in turn can be sub-divided. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission set than its parent.

 

How do I define my own code group?
Use caspol. For example, suppose you trust code from www.mydomain.com and you want it have full access to your system, but you want to keep the default restrictions for all other internet sites. To achieve this, you would add a new code group as a sub-group of the 

'Zone - Internet' group, like this:
caspol -ag 1.3 -site www.mydomain.com FullTrust
Now if you run caspol -lg you will see that the new group has been added as group 1.3.1:

 

   1.3.  Zone - Internet: Internet
      1.3.1.  Site - www.mydomain.com: FullTrust

 

Note that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to manipulate from the command-line. The underlying runtime never sees it.

 

How do I change the permission set for a code group?
Use caspol. If you are the machine administrator, you can operate at the 'machine' level - which means not only that the changes you make become the default for the machine, but also that users cannot change the permissions to be more permissive. If you are a normal (non-admin) user you can still modify the permissions, but only to make them more restrictive. For example, to allow intranet code to do what it likes you might do this:
caspol -cg 1.2 FullTrust
Note that because this is more permissive than the default policy (on a standard system), you should only do this at the machine level - doing it at the user level will have no effect.

 

I can't be bothered with all this CAS stuff. Can I turn it off?
Yes, as long as you are an administrator. Just run: caspol -s off

 

Can I look at the IL for an assembly?
Yes. MS supply a tool called Ildasm which can be used to view the metadata and IL for an assembly.

 

Can source code be reverse-engineered from IL?
Yes, it is often relatively straightforward to regenerate high-level source (e.g. C#) from IL.

 

How can I stop my code being reverse-engineered from IL?
There is currently no simple way to stop code being reverse-engineered from IL. In future it is likely that IL obfuscation tools will become available, either from MS or from third parties. These tools work by 'optimising' the IL in such a way that reverse-engineering becomes much more difficult.
Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL.

 

Is there built-in support for tracing/logging?
Yes, in the System.Diagnostics namespace. There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.

 

Can I redirect tracing to a file?
Yes. The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an

instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose.

 

What are the contents of assembly?
In general, a static assembly can consist of four elements:
 The assembly manifest, which contains assembly metadata.
 Type metadata.
 Microsoft intermediate language (MSIL) code that implements the types.
 A set of resources.

 

What is GC (Garbage Collection) and how it works
One of the good features of the CLR is Garbage Collection, which runs in the background collecting unused object references, freeing us from having to ensure we always destroy them. In reality the time difference between you releasing the object instance and it being garbage collected is likely to be very small, since the GC is always running.

[The process of transitively tracing through all pointers to actively used objects in order to locate all objects that can be referenced, and then arranging to reuse any heap memory that was not found during this trace. The common language runtime garbage collector also compacts the memory that is in use to reduce the working space needed for the heap.]

 

Heap:

A portion of memory reserved for a program to use for the temporary storage of data structures whose existence or size cannot be determined until the program is running.

 

Differnce between Managed code and unmanaged code ?

Managed Code:

Code that runs under a "contract of cooperation" with the common language runtime. Managed code must supply the metadata necessary for the runtime to provide services such as memory management, cross-language integration, code access security, and

automatic lifetime control of objects. All code based on Microsoft intermediate language (MSIL) executes as managed code.

 

Un-Managed Code:

Code that is created without regard for the conventions and requirements of the common language runtime. Unmanaged code executes in the common language runtime environment with minimal services (for example, no garbage collection, limited debugging, and so on).

 

What is MSIL, IL, CTS and, CLR ?

 

MSIL: (Microsoft intermediate language)
When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Before code can be executed, MSIL must be converted to CPU-specific code, usually by a just-in-time (JIT) compiler. Because the common language runtime supplies one or more JIT compilers for each computer architecture it supports, the same set of MSIL can be JIT-compiled and executed on any supported architecture.
When a compiler produces MSIL, it also produces metadata. Metadata describes the types in your code, including the definition of

each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at

execution time. The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published

Microsoft PE and Common Object File Format (COFF) used historically for executable content. This file format, which accommodates

 

MSIL or native code as well as metadata, enables the operating system to recognize common language runtime images. The

presence of metadata in the file along with the MSIL enables your code to describe itself, which means that there is no need for type libraries or Interface Definition Language (IDL). The runtime locates and extracts the metadata from the file as needed during

execution.


IL: (Intermediate Language)
A language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. The common language

runtime includes a JIT compiler for converting MSIL to native code.

 

CTS: (Common Type System)
The specification that determines how the common language runtime defines, uses, and manages types

 

CLR: (Common Language Runtime)
The engine at the core of managed code execution. The runtime supplies managed code with services such as cross-language

integration, code access security, object lifetime management, and debugging and profiling support.

 

What is Reference type and value type ?
Reference Type:
Reference types are allocated on the managed CLR heap, just like object types.
A data type that is stored as a reference to the value's location. The value of a reference type is the location of the sequence of bits

that represent the type's data. Reference types can be self-describing types, pointer types, or interface types

 

Value Type:
Value types are allocated on the stack just like primitive types in VBScript, VB6 and C/C++. Value types are not instantiated using new go out of scope when the function they are defined within returns.
Value types in the CLR are defined as types that derive from system.valueType.

 

A data type that fully describes a value by specifying the sequence of bits that constitutes the value's representation. Type information for a value type instance is not stored with the instance at run time, but it is available in metadata. Value type instances can be treated as objects using boxing.

 

What is Boxing and unboxing ?
Boxing:
The conversion of a value type instance to an object, which implies that the instance will carry full type information at run time and will be allocated in the heap. The Microsoft intermediate language (MSIL) instruction set's box instruction converts a value type to an object by making a copy of the value type and embedding it in a newly allocated object.

 

Un-Boxing:
The conversion of an object instance to a value type.

 

What is JIT and how is works ?
An acronym for "just-in-time," a phrase that describes an action that is taken only when it becomes necessary, such as just-in-time compilation or just-in-time object activation

 

What is portable executable (PE) ?
The file format used for executable programs and for files to be linked together to form executable programs

 

What is strong name?
A name that consists of an assembly's identity—its simple text name, version number, and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly. Because the assembly manifest

contains file hashes for all the files that constitute the assembly implementation, it is sufficient to generate the digital signature over just the one file in the assembly that contains the assembly manifest. Assemblies with the same strong name are expected to be identical

 

What is global assembly cache?
A machine-wide code cache that stores assemblies specifically installed to be shared by many applications on the computer. Applications deployed in the global assembly cache must have a strong name.

 

What is difference between constants, readonly and, static ?
Constants: The value can’t be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.

 

What is difference between shared and public?
An assembly that can be referenced by more than one application. An assembly must be explicitly built to be shared by giving it a cryptographically strong name.

 

What is namespace used for loading assemblies at run time and name the methods?
System.Reflection

 

What are the types of authentication in .net?
We have three types of  authentication:
1. Form authentication
2.  Windows authentication
3.  Passport
This has to be declared in web.config file.

 

What is the difference between a Struct and a Class in C# ?
The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects,
you will allocate additional memory for referencing each object. In this case, the struct is less expensive.
When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized. It is an error to declare a default (parameterless) constructor for a struct. A default constructor is always provided to initialize the struct members to their default values.
It is an error to initialize an instance field in a struct.
There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do.
A struct is a value type, while a class is a reference type.

How big is the datatype int in .NET?
32 bits.

 

How big is the char?
16 bits (Unicode).

 

How do you initiate a string without escaping each backslash?
Put an @ sign in front of the double-quoted string.

 

What's the access level of the visibility type internal?
Current application.

 

Explain encapsulation ?
The implementation is hidden, the interface is exposed.

 

What data type should you use if you want an 8-bit value that's signed?
sbyte.

 

Speaking of Boolean data types, what's different between C# and C/C++?
There's no conversion between 0 and false, as well as any other number and true, like in C/C++.

 

Where are the value-type variables allocated in the computer RAM?
Stack.

 

Where do the reference-type variables go in the RAM?
The references go on the stack, while the objects themselves go on the heap.

 

What is the difference between the value-type variables and reference-type variables in terms of garbage collection?
The value-type variables are not garbage-collected, they just fall off the stack when they fall out of scope, the reference-type objects

are picked up by GC when their references go null.

 

How do you convert a string into an integer in .NET?
Int32.Parse(string)

 

How do you box a primitive data type variable?
Assign it to the object, pass an object.

 

Why do you need to box a primitive variable?
To pass it by reference.

 

What's the difference between Java and .NET garbage collectors?
Sun left the implementation of a specific garbage collector up to the JRE developer, so their performance varies widely, depending on whose JRE you're using. Microsoft standardized on their garbage collection.

 

How do you enforce garbage collection in .NET?
System.GC.Collect();

 

Can you declare a C++ type destructor in C# like ~MyClass()?
Yes, but what's the point, since it will call Finalize(), and Finalize() has no guarantees when the memory will be cleaned up,  plus, it introduces additional load on the garbage collector.

 

What's different about namespace declaration when comparing that to package declaration in Java?
No semicolon.

 

What's the difference between const and readonly?
You can initialize readonly variables to some runtime values. Let's say your program uses current date and time as one of the values that won't change. This way you declare public readonly string DateT = new DateTime().ToString().

 

What does \a character do?
On most systems, produces a rather annoying beep.

 

Can you create enumerated data types in C#?
Yes.

 

What's different about switch statements in C#?
No fall-throughs allowed.

 

What happens when you encounter a continue statement inside the for loop?
The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop.

 

What's the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it's being operated on, a new instance is created.

 

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.

 

How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

 

What's the .NET datatype that allows the retrieval of data by a unique key?
HashTable.

 

What's class SortedList underneath?
A sorted HashTable.

 

Will finally block get executed if the exception had not occurred?
Yes.

 

What's the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

 

Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

 

Why is it a bad idea to throw your own exceptions?
Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

 

What's a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

 

What's a multicast delegate?
It's a delegate that points to and eventually fires off several methods.

 

How's the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32),  but also the version of the assembly.

 

What are the ways to deploy an assembly?
 An MSI installer, a CAB archive, and XCOPY command.

 

What's a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

 

What namespaces are necessary to create a localized application?
System.Globalization, System.Resources.

 

What's the difference between // comments, /* */ comments and /// comments?
Single-line, multi-line and XML documentation comments.

 

How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with a /doc switch.

 

What does assert() do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is  false. The program proceeds without any interruption if the condition is true.

 

What's the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

 

Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.

 

Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.

 

How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.

 

What are three test cases you should go through in unit testing?
Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception  test

cases (exceptions are thrown and caught properly).

 

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's the implicit name of the parameter that gets passed into the class' set method?
Value, and it's datatype depends on whatever variable we're changing.

 

How do you inherit from a class in C#?
Place a colon and then the name of the base class. Notice that it's double colon in C++.

 

Does C# support multiple inheritance?
No, use interfaces instead.

 

When you inherit a protected class-level variable, who is it available to?
Classes in the same namespace.

 

What's the top .NET class that everything is derived from?
System.Object.

 

How's method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the  same name within the class.

 

What does the keyword virtual mean in the method definition?
The method can be over-ridden.

 

Can you declare the override method static while the original method is non-static?
No, you can't, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword  override.

 

Can you override private virtual methods?
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

 

Can you prevent your class from being inherited and becoming a base class for some other classes?
Yes, that's what keyword sealed in the class definition is for. The developer trying to derive from your class will get a  message: cannot inherit from Sealed class WhateverBaseClassName. It's the same concept as final class in Java.

 

Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, just leave the class public and make the method sealed.

 

Why can't you specify the accessibility modifier for methods inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it's public by default.

 

Can you inherit multiple interfaces?
Yes, why not.

 

And if they have conflicting method names?
It's up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you're

okay.

 

What's the difference between an interface and abstract class?
In the interface all methods must be abstract, in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

 

How can you overload a method?
Different parameter data types, different number of parameters, different order of parameters.

 

If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary 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 the difference between System.String and System.StringBuilder classes?
System.String is immutable, System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

 

Does C# support multiple-inheritance?
No, use interfaces instead.

 

When you inherit a protected class-level variable, who is it available to?
Classes in the same namespace.

 

Are private class-level variables inherited?
Yes, but they are not accessible.  Although they are not visible or accessible via the class interface, they are inherited.

 

Describe the accessibility modifier "protected internal".
It is available to derived classes and classes within the same Assembly (and naturally from the base class it's declared in).

 

What's the top .NET class that everything is derived from?
System.Object.

 

What's the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation.  Strings are immutable, so each time it's being operated on, a new instance is created.

 

Can you store multiple data types in System.Array?
No.

 

What's the .NET class that allows the retrieval of a data element using a unique key?
HashTable.

 

Will the finally block get executed if an exception has not occurred?
Yes.

 

What's an abstract class?
A class that cannot be instantiated.  An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.


When do you absolutely have to declare a class as abstract?
 1.       When at least one of the methods in the class is abstract.
 2.       When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.

 

What's an interface?
It's an abstract class with public abstract methods all of which must be implemented in the inherited classes.

 

Why can't you specify the accessibility modifier for methods inside the interface?
They all must be public.  Therefore, to prevent you from getting the false impression that you have any freedom of choice,   

you are not allowed to specify any accessibility, it's public by default.

 

What's the difference between an interface and abstract class?
In an interface class, all methods must be abstract.  In an abstract class some methods can be concrete.  In an interface class, no accessibility modifiers are allowed, which is ok in an abstract class.

 

How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply  involves

having another method with the same name within the class.

 

Can you declare an override method to be static if the original method is non-static?
No. The signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

 

Can you override private virtual methods?
No.  Private methods are not accessible outside the class.

 

What's a delegate?
A delegate object encapsulates a reference to a method.

 

What's a multicast delegate?
It's a delegate that points to and eventually fires off several methods

 

 

 

Forms:

 

Can you write a class without specifying namespace? Which namespace does it belong to by default??
Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally, you  wouldn't want global namespace.

 

You are designing a GUI application with a windows and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What's the problem? 
One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at  the same location when resized.

 

How can you save the desired properties of Windows Forms application? 
.config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.

 

So how do you retrieve the customized properties of a .NET application from XML .config file? 
Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.

 

Can you automate this process? 
In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.

 

My progress bar freezes up and dialog window shows blank, when an intensive background process takes over. 
Yes, you should've multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.

 

What's the safest way to deploy a Windows Forms app?
Web deployment: the user always downloads the latest version of the code, the program runs within security sandbox, properly written app will not require additional security privileges.

 

Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio? 
The designer will likely through it away, most of the code inside InitializeComponent is auto-generated.

 

What's the difference between WindowsDefaultLocation and WindowsDefaultBounds?
WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.

 

What's the difference between Move and LocationChanged? Resize and SizeChanged? 
Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.

 

How would you create a non-rectangular window, let's say an ellipse? 
Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.

 

How do you create a separator in the Menu Designer? 
A hyphen '-' would do it. Also, an ampersand '&\' would underline the next letter.

 

How's anchoring different from docking? 
Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking  treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.

 

How do you trigger the Paint event in System.Drawing?
Invalidate the current form, the OS will take care of repainting. The Update method forces the repaint.

 

With these events, why wouldn't Microsoft combine Invalidate and Paint, so that you wouldn't have to tell it to repaint, and then to force it to repaint?
Painting is the slowest thing the OS does, so usually telling it to repaint, but not forcing it allows for the process to take place in the background.

 

How can you assign an RGB color to a System.Drawing.Color object?
Call the static method FromArgb of this class and pass it the RGB values.

 

What class does Icon derive from? 
Isn't it just a Bitmap with a wrapper name around it? No, Icon lives in System.Drawing namespace. It's not a Bitmap by default, and is treated separately by .NET. However, you can use ToBitmap method to get a valid Bitmap object from a valid Icon object.

 

Before in my VB app I would just load the icons from DLL. How can I load the icons provided by .NET dynamically? 
By using System.Drawing.SystemIcons class, for example System.Drawing.SystemIcons.Warning produces an Icon with a  warning sign in it.

 

When displaying fonts, what's the difference between pixels, points and ems? 
A pixel is the lowest-resolution dot the computer monitor supports. Its size depends on user's settings and monitor size. A point is always 1/72 of an inch. An em is the number of pixels that it takes to display the letter M.

 

 

 

ASP.net

 

 

What is view state and use of it?
The current property settings of an ASP.NET page and those of any ASP.NET server controls contained within the page. ASP.NET can detect when a form is requested for the first time versus when the form is posted (sent to the server), which  allows you to program accordingly.

What are user controls and custom controls?
Custom controls:

 A control authored by a user or a third-party software vendor that does not belong to   the .NET Framework class library. This is a generic term that includes user controls. A  custom server control is used in Web Forms (ASP.NET pages). A custom client control is used  in Windows Forms applications.

User Controls:
In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used   as a server control. An ASP.NET user control is authored declaratively  and persisted as a  text file with an .ascx extension. The ASP.NET page framework compiles a user control on  the fly to a class that derives from the        System.Web.UI.UserControl class.

What are the validation controls?
A set of server controls included with ASP.NET that test user input in HTML and Web server  controls for programmer-defined requirements. Validation controls perform input checking in server code. If the user is working with a browser that supports DHTML, the validation  controls can also perform validation using client script.

What's the difference between Response.Write() andResponse.Output.Write()?
The latter one allows you to write formattedoutput.

What methods are fired during the page load? Init()
 When the page is instantiated, Load() - when the page is loaded into server  memory,PreRender () - the brief moment before the page is displayed to the user  as HTML, Unload() - when page finishes loading.

Where does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page

Where do you store the information about the user's locale?
System.Web.UI.Page.Culture

What's the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"?
CodeBehind is relevant to Visual Studio.NET only.

What's a bubbled event?
When you have a complex control, likeDataGrid, writing an event processing routine for each object (cell, button,row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.
Suppose you want a certain ASP.NET function executed on MouseOver over a certain button.

Where do you add an event handler?
It's the Attributesproperty, the Add function inside that property.            
e.g. btnSubmit.Attributes.Add("onMouseOver","someClientCode();")

What data type does the RangeValidator control support?
Integer,String and Date.

What are the different types of caching?
Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In context of web application, caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them.ASP.NET has 3 kinds of caching strategiesOutput CachingFragment CachingData    

CachingOutput Caching: Caches the dynamic output generated by a request. Some times it is useful to cache  the output of a website even for a minute, which will result in a better  performance. For caching the whole page the page should have OutputCache directive.<%@ OutputCache Duration="60" VaryByParam="state" %>

Fragment Caching: Caches the portion of the  page generated by the request. Some times it is not practical to cache the entire page, in such cases we can cache a portion of page<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>

Data Caching: Caches the objects programmatically. For     data caching asp.net provides a cache object for eg: cache["States"] = dsStates;

What do you mean by authentication and authorization?
Authentication is the process of validating a user on the credentials (username and     password) and authorization performs after authentication. After Authentication a user will     be verified for performing the various tasks, It access is limited it is known as       authorization.

What are different types of directives in .NET?
@Page
: Defines page-specific attributes used by the ASP.NET page parser and compiler. Can       be included only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>  
@Control:Defines control-specific attributes used by the ASP.NET page parser and        compiler. Can be included only in .ascx files. <%@ Control Language="VB" EnableViewState="false" %>
@Import: Explicitly imports a namespace into a page or user control. The Import         directive cannot have more than one namespace attribute. To import multiple     namespaces,     use multiple @Import directives. <% @ Import Namespace="System.web" %>
@Implements: Indicates that the current page or user control implements the specified .NET      framework interface.<%@ Implements Interface="System.Web.UI.IPostBackEventHandler" %>
@Register: Associates aliases with namespaces and class names for concise notation in   custom server control syntax.<%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="AdRotator.ascx" %>
@Assembly: Links an assembly to the current page during compilation, making all         the     assembly's classes and interfaces available for use on the      page. <%@ Assembly Name="MyAssembly" %><%@ Assembly Src="MySource.vb" %>
@OutputCache: Declaratively controls the output caching policies of an ASP.NET page or a        user control contained in a page<%@ OutputCache Duration="#ofseconds" Location="Any | Client | Downstream | Server | None" Shared="True | False" VaryByControl="controlname" VaryByCustom="browser | customstring" VaryByHeader="headers" VaryByParam="parametername" %>
@Reference: Declaratively indicates that another user control or page source file               should be dynamically compiled and linked against the page in which this directive is   declared.

How do I debug an ASP.NET application that wasn't written with Visual Studio.NET and that doesn't use code-behind?
Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing      the code you want to debug, and set your breakpoints. Start the ASP.NET application. Go back to DbgClr, choose Debug Processes from the Tools menu, and select  aspnet_wp.exe from  the list of processes. (If aspnet_wp.exe doesn't appear in the list,check the "Show system      processes" box.) Click the Attach button to attach to aspnet_wp.exe and begin debugging.
Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can   enable tell ASP.NET to build debug executables by placing a
<%@ Page Debug="true" %>   statement at the top of an ASPX file or a   <COMPILATION debug="true" />statement in a Web.config file.
 
Can a user browsing my Web site read my Web.config or Global.asax files?
No. The <HTTPHANDLERS>section of Machine.config, which holds the master configuration  settings for ASP.NET, contains entries that map ASAX files, CONFIG files, and selected  other file types to an HTTP handler named HttpForbiddenHandler, which fails attempts to retrieve the associated file. You can modify it by editing  Machine.config or including an section in a local Web.config file.

What's the difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript?
RegisterClientScriptBlock is for returning blocks of client-side script containing functions. RegisterStartupScript is for returning blocks of client-script not   packaged in functions-in other words, code that's to execute when the page is loaded. The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs.<%@ Reference Control="MyControl.ascx" %>

Is it necessary to lock application state before accessing it?
Only if you're performing a multistep update and want the update to be treated as an atomic     operation. Here's an example:
                Application.Lock ();
                Application["ItemsSold"] = (int) Application["ItemsSold"] + 1;
                Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1;
                Application.UnLock ();  
By locking application state before updating it and unlocking it afterwards, you ensure  that another request being processed on another thread doesn't read application state   at exactly the wrong time and see an inconsistent view of it. If I update session state, should I lock it, too? Are concurrent accesses by multiple requests executing on multiple threads a concern with session state?
Concurrent accesses aren't an issue with session state, for two reasons. One, it's unlikely that two requests from the same user will overlap. Two, if they do overlap, ASP.NET locks down session state during request processing so that two threads can't touch it at once. Session state is locked down when the HttpApplication instance that's processing the request fires an AcquireRequestState event and unlocked when it fires a ReleaseRequestState event.

Do ASP.NET forms authentication cookies provide any protection against replay attacks? Do they, for example, include the client's IP  address or anything else that would distinguish the real client from an attacker?
No. If an authentication cookie is stolen, it can be used by an attacker. It's up to you to     prevent this from happening by using an encrypted communications channel (HTTPS). Authentication cookies issued as session cookies, do, however,include a time-out valid that     limits their lifetime. So a stolen session cookie can only be used in replay attacks as long as the ticket inside the cookie is valid. The default time-out interval is 30 minutes.You can change that by modifying the timeout attribute accompanying the <forms> element in Machine.config or a local Web.config file. Persistent authentication cookies do not  time-out and therefore are a more serious security threat if stolen.

How do I send e-mail from an ASP.NET application?
  
        MailMessage message = new MailMessage ();
        message.From = <email>;
        message.To = <email>;
        message.Subject = "Scheduled Power Outage";
        message.Body = "Our servers will be down tonight.";
        SmtpMail.SmtpServer = "localhost";
        SmtpMail.Send (message);

 MailMessage and SmtpMail are classes defined in the .NET Framework Class Library's  System.Web.Mail namespace. Due to a security change made to ASP.NET just before it shipped,  you need to set SmtpMail's SmtpServer property to "localhost" even though "localhost" is  the default. In addition, you must use the IIS configuration applet to enable localhost  (127.0.0.1) to relay messages through the local SMTP service.

What are VSDISCO files?

VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following VSDISCO file in a directory on your Web server, for example, it returns   references to all ASMX and DISCO files in the host directory and any subdirectories not         noted in <exclude> elements:
             <?xml version="1.0" ?>
                <dynamicDiscovery
                  xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
                  <exclude path="_vti_cnf" />
                  <exclude path="_vti_pvt" />
                  <exclude path="_vti_log" />
                  <exclude path="_vti_script" />
                  <exclude path="_vti_txt" />
                </dynamicDiscovery>   

How does dynamic discovery work?
ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the host  directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client who requests a VSDISCO file gets back what appears to be a static DISCO document.
Note that VSDISCO files are disabled in the release version of ASP.NET. You can reenable them by uncommenting the line   in the <httpHandlers> section of Machine.config that maps *.vsdisco to System.Web.Services.Discovery.DiscoveryRequestHandler and granting the ASPNET  user account permission to read the IIS metabase. However, Microsoft is actively discouraging the use of VSDISCO files because they could represent a threat to Web server security.
 
Is it possible to prevent a browser from caching an ASPX page?
Just call SetNoStore on the HttpCachePolicy object exposed through the Response object's Cache property, as demonstrated here:
 
        <%@ Page Language="C#" %>
        <html>
          <body>
            <%
              Response.Cache.SetNoStore ();
              Response.Write (DateTime.Now.ToLongTimeString ());
            %>
          </body>
        </html>  

SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP response. In this example, it prevents caching of a Web page that shows the current time.

What does AspCompat="true" mean and when should I use it?
AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but should be set to true in any ASPX file that creates apartment-threaded COM objects--that is, COM objects registered ThreadingModel=Apartment. That includes all COM objects written with  Visual Basic 6.0. AspCompat should also be set to true (regardless of threading  model)  if the page creates COM objects that access intrinsic ASP objects such as Request and Response. The following directive sets AspCompat to true:

         <%@ Page AspCompat="true" %>  

Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available      to the COM components by placing unmanaged wrappers around the equivalent ASP.NET objects. Second, it improves the performance of calls that the page places to apartment- threaded COM objects by ensuring that the page (actually, the thread that processes the  request for the page) and the COM objects it creates share an apartment. AspCompat="true" forces ASP.NET request threads into single-threaded apartments (STAs). If those threads create COM objects marked ThreadingModel=Apartment, then the objects are created in the same STAs as the threads that created them. Without AspCompat="true," request threads run in a multithreaded apartment (MTA) and each call to an STA-based COM object incurs a performance hit when it's  marshaled across apartment boundaries.

Do not set AspCompat to true if your page uses no COM objects or if it uses COM objects that don't access ASP intrinsic objects and that are registered ThreadingModel=Free or  ThreadingModel=Both.

Explain the differences between Server-side and Client-side code?
 Server side scripting means that all the script will be executed by the server and  interpreted as needed. ASP doesn't have some of the functionality like sockets, uploading,  etc. For these you have to make a custom components usually in VB or VC++. Client side  scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in  VBScript or JavaScript. Download time, browser compatibility, and visible code - since  JavaScript and VBScript code is included in the HTML page, then anyone can see the code by viewing the page source. Also a possible security hazards for the client computer.

What type of code (server or client) is found in a Code-Behind class?
C#

Should validation (did the user enter a real date) occur server-side or client-side? Why?
Client-side validation because there is no need to request a server side date when you  could obtain a date from the client machine.

What are ASP.NET Web Forms? How is this technology different than what is available though ASP?
Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto  them. However, these UI elements render themselves in the appropriate markup language   required by the request, e.g. HTML. If you use Microsoft Visual Studio .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.

What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional   integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request  object. Sure, there are workarounds, but they're difficult. Finally, Response.Redirect  necessitates a round trip to the client, which, on high-volume sites, causes scalability problems.
As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.

How can you provide an alternating color scheme in a Repeater control?
AlternatingItemTemplate Like the ItemTemplate element, but rendered for every other row (alternating items) in the Repeater control. You can specify a different appearance for the AlternatingItemTemplate element by setting its style properties.

Which template must you provide, in order to display data in a Repeater control?
ItemTemplate

What event handlers can I include in Global.asax?
Application_Start,Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed,  Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute, 
Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache, Session_Start,Session_End
You can optionally include "On" in any of method names. For example, you can name a BeginRequest event handler.Application_BeginRequest or Application_OnBeginRequest.You can also include event handlers in Global.asax for events fired by custom HTTP modules.Note that not all of the event handlers make sense for Web Services (they're designed for ASP.NET applications in general, whereas .NET XML Web Services are specialized instances of an ASP.NET app). For example, the Application_AuthenticateRequest and Application_AuthorizeRequest events are designed to be used with ASP.NET Forms authentication. 

 

WebServices

 

What platforms do .NET XML Web Services run on? 
Currently, they're supported on Windows 2000 and Windows XP. ASP.NET integrates with Internet Information Server (IIS) and thus requires that IIS be installed. It runs on server and non-server editions of Windows 2000 and XP as long as IIS is  

installed.  


Can two different programming languages be mixed in a single ASMX file? 
No.  


What is code-behind? 
Code-behind allows you to associate Web Service source code written in a CLR compliant language (such as C# or VB.NET) as compiled in a separate file (typically *.asmx.cs or *.asmx.vb). You would otherwise typically find the executable  code directly inserted into the .asmx file.  


What namespaces are imported by default in ASMX files? 
The following namespaces are imported by default. Other namespaces must be imported manually.· System, System.Collections,System.ComponentModel,System.Data, System.Diagnostics,System.Web,System.Web.Services  


How do I provide information to the Web Service when the information is required as a SOAP Header? 
The key here is the Web Service proxy you created using wsdl.exe or through Visual Studio .NET's Add Web Reference menu option. If you happen to download a WSDL file for a Web Service that requires a SOAP header, .NET will create a SoapHeader class in the proxy source file. Using the previous example:     
      public class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol

        {   

            public AuthToken AuthTokenValue;       

       

        [System.Xml.Serialization.XmlRootAttribute(Namespace="http://tempuri.org/", IsNullable=false)]       

            public class AuthToken : SoapHeader {        public string Token;    }}   
     
In this case, when you create an instance of the proxy in your main application file, you'll also create an instance of the AuthToken class and assign the string:     

     Service1 objSvc = new Service1();

     processingobjSvc.AuthTokenValue = new AuthToken();

     objSvc.AuthTokenValue.Token = <actual token value>;

     Web Servicestring strResult = objSvc.MyBillableWebMethod();   
    
What is WSDL?
WSDL is the Web Service Description Language, and it is implemented as a specific XML vocabulary. While it's very much more complex than what can be described here, there are two important aspects to WSDL with which you should be aware. First, WSDL provides instructions to consumers of Web Services to describe the layout and contents of the SOAP packets  the Web Service intends to issue. It's an interface description document, of sorts. And second, it isn't intended that you  read and interpret the WSDL. Rather, WSDL should be processed by machine, typically to generate proxy source code (.NET) or create dynamic proxies on the fly (the SOAP Toolkit or Web Service Behavior).  

 

 

Remoting FAQ's

 


 

What 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.


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.


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.   

 

 

 

 

 

 

 

 

 

 

ADO.Net:

 

Explain what a diffgram is and its usage ?
A DiffGram is an XML format that is used to identify current and original versions of data elements. The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order.

When sending and retrieving a DataSet from an XML Web service, the DiffGram format is implicitly used. Additionally, when loading the contents of a DataSet from XML using the ReadXml method, or when writing the contents of a DataSet in XML using the WriteXml method, you can select that the contents be read or written as a DiffGram.

The DiffGram format is divided into three sections: the current data, the original (or "before") data, and an errors section, as shown in the following example.

<?xml version="1.0"?>
<diffgr:diffgram
         xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
         xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"
         xmlns:xsd="
http://www.w3.org/2001/XMLSchema">

   <DataInstance>
   </DataInstance>

  <diffgr:before>
  </diffgr:before>

  <diffgr:errors>
  </diffgr:errors>
</diffgr:diffgram>

The DiffGram format consists of the following blocks of data:

<DataInstance>
The name of this element, DataInstance, is used for explanation purposes in this documentation. A DataInstance element represents a DataSet or a row of a DataTable. Instead of DataInstance, the element would contain the name of the DataSet or DataTable. This block of the DiffGram format contains the current data, whether it has been modified or not. An element, or row, that has been modified is identified with the diffgr:hasChanges annotation.
<diffgr:before>
This block of the DiffGram format contains the original version of a row. Elements in this block are matched to elements in the DataInstance block using the diffgr:id annotation.
<diffgr:errors>
This block of the DiffGram format contains error information for a particular row in the DataInstance block. Elements in this block are matched to elements in the DataInstance block using the diffgr:id annotation.

Which method do you invoke on the DataAdapter control to load your generated dataset with data?
You have to use the Fill method of the DataAdapter control and pass the dataset object as an argument to load the generated data.

Can you edit data in the Repeater control?
NO.

Which are the different IsolationLevels ?
Following are the various IsolationLevels:

  • Serialized   Data read by a current transaction cannot be changed by another transaction until the current transaction finishes. No new data can be inserted that would affect the current transaction. This is the safest isolation level and is the default. 
  • Repeatable Read   Data read by a current transaction cannot be changed by another transaction until the current transaction finishes. Any type of new data can be inserted during a transaction. 
  • Read Committed   A transaction cannot read data that is being modified by another transaction that has not committed. This is the default isolation level in Microsoft® SQL Server. 
  • Read Uncommitted   A transaction can read any data, even if it is being modified by another transaction. This is the least safe isolation level but allows the highest concurrency. 
  • Any   Any isolation level is supported. This setting is most commonly used by downstream components to avoid conflicts. This setting is useful because any downstream component must be configured with an isolation level that is equal to or less than the isolation level of its immediate upstream component. Therefore, a downstream component that has its isolation level configured as Any always uses the same isolation level that its immediate upstream component uses. If the root object in a transaction has its isolation level configured to Any, its isolation level becomes Serialized.

How xml files and be read and write using dataset?.
DataSet exposes method like ReadXml and WriteXml to read and write xml

What are the different rowversions available?
There are four types of Rowversions.
Current:
The current values for the row. This row version does not exist for rows with a RowState of Deleted.

Default :
The row the default version for the current DataRowState. For a DataRowState value of Added, Modified or Current, the default version is Current. For a DataRowState of Deleted, the version is Original. For a DataRowState value of Detached, the version is Proposed.

Original:
The row contains its original values.

Proposed:
The proposed values for the row. This row version exists during an edit operation on a row, or for a row that is not part of a DataRowCollection

Explain acid properties?.
The term ACID conveys the role transactions play in mission-critical applications. Coined by transaction processing pioneers, ACID stands for atomicity, consistency, isolation, and durability.

These properties ensure predictable behavior, reinforcing the role of transactions as all-or-none propositions designed to reduce the management load when there are many variables.

Atomicity
A transaction is a unit of work in which a series of operations occur between the BEGIN TRANSACTION and END TRANSACTION statements of an application. A transaction executes exactly once and is atomic — all the work is done or none of it is.

Operations associated with a transaction usually share a common intent and are interdependent. By performing only a subset of these operations, the system could compromise the overall intent of the transaction. Atomicity eliminates the chance of processing a subset of operations.

Consistency
A transaction is a unit of integrity because it preserves the consistency of data, transforming one consistent state of data into another consistent state of data.

Consistency requires that data bound by a transaction be semantically preserved. Some of the responsibility for maintaining consistency falls to the application developer who must make sure that all known integrity constraints are enforced by the application. For example, in developing an application that transfers money, you should avoid arbitrarily moving decimal points during the transfer.

Isolation
A transaction is a unit of isolation — allowing concurrent transactions to behave as though each were the only transaction running in the system.

Isolation requires that each transaction appear to be the only transaction manipulating the data store, even though other transactions may be running at the same time. A transaction should never see the intermediate stages of another transaction.

Transactions attain the highest level of isolation when they are serializable. At this level, the results obtained from a set of concurrent transactions are identical to the results obtained by running each transaction serially. Because a high degree of isolation can limit the number of concurrent transactions, some applications reduce the isolation level in exchange for better throughput.

Durability
A transaction is also a unit of recovery. If a transaction succeeds, the system guarantees that its updates will persist, even if the computer crashes immediately after the commit. Specialized logging allows the system's restart procedure to complete unfinished operations, making the transaction durable.


Whate are different types of Commands available with DataAdapter ?
The SqlDataAdapter has SelectCommand, InsertCommand, DeleteCommand and UpdateCommand

What is a Dataset?
Datasets are the result of bringing together ADO and XML. A dataset contains one or more data of tabular XML, known as DataTables, these data can be treated separately, or can have relationships defined between them. Indeed these relationships give you ADO data SHAPING without needing to master the SHAPE language, which many people are not comfortable with.

The dataset is a disconnected in-memory cache database. The dataset object model looks like this:

Dataset
  DataTableCollection
  DataTable
   DataView
   DataRowCollection
    DataRow
   DataColumnCollection
    DataColumn
   ChildRelations
   ParentRelations
   Constraints
   PrimaryKey
DataRelationCollection

Let’s take a look at each of these:

DataTableCollection: As we say that a DataSet is an in-memory database. So it has this collection, which holds data from multiple tables in a single DataSet object.

DataTable: In the DataTableCollection, we have DataTable objects, which represents the individual tables of the dataset.

DataView: The way we have views in database, same way we can have DataViews. We can use these DataViews to do Sort, filter data.

DataRowCollection: Similar to DataTableCollection, to represent each row in each Table we have DataRowCollection.

DataRow:  To represent each and every row of the DataRowCollection, we have DataRows.

DataColumnCollection: Similar to DataTableCollection, to represent each column in each Table we have DataColumnCollection.

DataColumn: To represent each and every Column of the DataColumnCollection, we have DataColumn.

PrimaryKey: Dataset defines Primary key for the table and the primary key validation will take place without going to the database.

Constraints: We can define various constraints on the Tables, and can use Dataset.Tables(0).enforceConstraints. This will execute all the constraints, whenever we enter data in DataTable.

DataRelationCollection: as we know that we can have more than 1 table in the dataset, we can also define relationship between these tables using this collection and maintain a parent-child relationship.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Explain the ADO . Net Architecture ( .Net Data Provider)
ADO.Net is the data access model for .Net –based applications. It can be used to access relational database systems such as SQL SERVER 2000, Oracle, and many other data sources for which there is an OLD DB or ODBC provider. To a certain extent, ADO.NET represents the latest evolution of ADO technology. However, ADO.NET introduces some major changes and innovations that are aimed at the loosely coupled and inherently disconnected – nature of web applications.

A .Net Framework data provider is used to connecting to a database, executing commands, and retrieving results. Those results are either processed directly, or placed in an ADO.NET DataSet in order to be exposed to the user in an ad-hoc manner, combined with data from multiple sources, or remoted between tiers. The .NET Framework data provider is designed to be lightweight, creating a minimal layer between the data source and your code, increasing performance without sacrificing functionality.

Following are the 4 core objects of .Net Framework Data provider:

  • Connection: Establishes a connection to a specific data source
  • Command: Executes a command against a data source. Exposes Parameters and can execute within the scope of a Transaction from a Connection.
  • DataReader: Reads a forward-only, read-only stream of data from a data source.
  • DataAdapter: Populates a DataSet and resolves updates with the data source.

The .NET Framework includes the .NET Framework Data Provider for SQL Server (for Microsoft SQL Server version 7.0 or later), the .NET Framework Data Provider for OLE DB, and the .NET Framework Data Provider for ODBC.

 

The .NET Framework Data Provider for SQL Server:  The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. It is lightweight and performs well because it is optimized to access a SQL Server directly without adding an OLE DB or Open Database Connectivity (ODBC) layer. The following illustration contrasts the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB communicates to an OLE DB data source through both the OLE DB Service component, which provides connection pooling and transaction services, and the OLE DB Provider for the data source

 

The .NET Framework Data Provider for OLE DB: The .NET Framework Data Provider for OLE DB uses native OLE DB through COM interoperability to enable data access. The .NET Framework Data Provider for OLE DB supports both local and distributed transactions. For distributed transactions, the .NET Framework Data Provider for OLE DB, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services.

 

The .NET Framework Data Provider for ODBC: The .NET Framework Data Provider for ODBC uses native ODBC Driver Manager (DM) through COM interoperability to enable data access. The ODBC data provider supports both local and distributed transactions. For distributed transactions, the ODBC data provider, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services.

 

The .NET Framework Data Provider for Oracle: The .NET Framework Data Provider for Oracle enables data access to Oracle data sources through Oracle client connectivity software. The data provider supports Oracle client software version 8.1.7 and later. The data provider supports both local and distributed transactions (the data provider automatically enlists in existing distributed transactions, but does not currently support the EnlistDistributedTransaction method).

 

The .NET Framework Data Provider for Oracle requires that Oracle client software (version 8.1.7 or later) be installed on the system before you can use it to connect to an Oracle data source.
.NET Framework Data Provider for Oracle classes are located in the System.Data.OracleClient namespace and are contained in the System.Data.OracleClient.dll assembly. You will need to reference both the System.Data.dll and the System.Data.OracleClient.dll when compiling an application that uses the data provider.
Choosing a .NET Framework Data Provider

 

.NET Framework Data Provider for SQL Server: Recommended for middle-tier applications using Microsoft SQL Server 7.0 or later. Recommended for single-tier applications using Microsoft Data Engine (MSDE) or Microsoft SQL Server 7.0 or later.
Recommended over use of the OLE DB Provider for SQL Server (SQLOLEDB) with the .NET Framework Data Provider for OLE DB. For Microsoft SQL Server version 6.5 and earlier, you must use the OLE DB Provider for SQL Server with the .NET Framework Data Provider for OLE DB.

 

.NET Framework Data Provider for OLE DB: Recommended for middle-tier applications using Microsoft SQL Server 6.5 or earlier, or any OLE DB provider. For Microsoft SQL Server 7.0 or later, the .NET Framework Data Provider for SQL Server is recommended. Recommended for single-tier applications using Microsoft Access databases. Use of a Microsoft Access database for a middle-tier application is not recommended.

 

.NET Framework Data Provider for ODBC: Recommended for middle-tier applications using ODBC data sources. Recommended for single-tier applications using ODBC data sources.

.NET Framework Data Provider for Oracle: Recommended for middle-tier applications using Oracle data sources. Recommended for single-tier applications using Oracle data sources. Supports Oracle client software version 8.1.7 and later. The .NET Framework Data Provider for Oracle classes are located in the System.Data.OracleClient namespace and are contained in the System.Data.OracleClient.dll assembly. You need to reference both the System.Data.dll and the System.Data.OracleClient.dll when compiling an application that uses the data provider.

Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
Let’s take a look at the differences between ADO Recordset and ADO.Net DataSet:

1. Table Collection: ADO Recordset provides the ability to navigate through a single table of information. That table would have been formed with a join of multiple tables and returning columns from multiple tables. ADO.NET DataSet is capable of holding instances of multiple tables. It has got a Table Collection, which holds multiple tables in it. If the tables are having a relation, then it can be manipulated on a Parent-Child relationship. It has the ability to support multiple tables with keys, constraints and interconnected relationships. With this ability the DataSet can be considered as a small, in-memory relational database cache.

2. Navigation: Navigation in ADO Recordset is based on the cursor mode. Even though it is specified to be a client-side Recordset, still the navigation pointer will move from one location to another on cursor model only. ADO.NET DataSet is an entirely offline, in-memory, and cache of data. All of its data is available all the time. At any time, we can retrieve any row or column, constraints or relation simply by accessing it either ordinarily or by retrieving it from a name-based collection.

3. Connectivity Model: The ADO Recordset was originally designed without the ability to operate in a disconnected environment. ADO.NET DataSet is specifically designed to be a disconnected in-memory database. ADO.NET DataSet follows a pure disconnected connectivity model and this gives it much more scalability and versatility in the amount of things it can do and how easily it can do that.

4. Marshalling and Serialization: In COM, through Marshalling, we can pass data from 1 COM component to another component at any time. Marshalling involves copying and processing data so that a complex type can appear to the receiving component the same as it appeared to the sending component. Marshalling is an expensive operation. ADO.NET Dataset and DataTable components support Remoting in the form of XML serialization. Rather than doing expensive Marshalling, it uses XML and sent data across boundaries.

5. Firewalls and DCOM and Remoting: Those who have worked with DCOM know that how difficult it is to marshal a DCOM component across a router. People generally came up with workarounds to solve this issue. ADO.NET DataSet uses Remoting, through which a DataSet / DataTable component can be serialized into XML, sent across the wire to a new AppDomain, and then Desterilized back to a fully functional DataSet. As the DataSet is completely disconnected, and it has no dependency, we lose absolutely nothing by serializing and transferring it through Remoting.


How do you handle data concurrency in .NET ?

One of the key features of the ADO.NET DataSet is that it can be a self-contained and disconnected data store. It can contain the schema and data from several rowsets in DataTable objects as well as information about how to relate the DataTable objects-all in memory. The DataSet neither knows nor cares where the data came from, nor does it need a link to an underlying data source. Because it is data source agnostic you can pass the DataSet around networks or even serialize it to XML and pass it across the Internet without losing any of its features. However, in a disconnected model, concurrency obviously becomes a much bigger problem than it is in a connected model.

In this column, I'll explore how ADO.NET is equipped to detect and handle concurrency violations. I'll begin by discussing scenarios in which concurrency violations can occur using the ADO.NET disconnected model. Then I will walk through an ASP.NET application that handles concurrency violations by giving the user the choice to overwrite the changes or to refresh the out-of-sync data and begin editing again. Because part of managing an optimistic concurrency model can involve keeping a timestamp (rowversion) or another type of flag that indicates when a row was last updated, I will show how to implement this type of flag and how to maintain its value after each database update.


Is Your Glass Half Full?

There are three common techniques for managing what happens when users try to modify the same data at the same time: pessimistic, optimistic, and last-in wins. They each handle concurrency issues differently.

The pessimistic approach says: "Nobody can cause a concurrency violation with my data if I do not let them get at the data while I have it." This tactic prevents concurrency in the first place but it limits scalability because it prevents all concurrent access. Pessimistic concurrency generally locks a row from the time it is retrieved until the time updates are flushed to the database. Since this requires a connection to remain open during the entire process, pessimistic concurrency cannot successfully be implemented in a disconnected model like the ADO.NET DataSet, which opens a connection only long enough to populate the DataSet then releases and closes, so a database lock cannot be held.

Another technique for dealing with concurrency is the last-in wins approach. This model is pretty straightforward and easy to implement-whatever data modification was made last is what gets written to the database. To implement this technique you only need to put the primary key fields of the row in the UPDATE statement's WHERE clause. No matter what is changed, the UPDATE statement will overwrite the changes with its own changes since all it is looking for is the row that matches the primary key values. Unlike the pessimistic model, the last-in wins approach allows users to read the data while it is being edited on screen. However, problems can occur when users try to modify the same data at the same time because users can overwrite each other's changes without being notified of the collision. The last-in wins approach does not detect or notify the user of violations because it does not care. However the optimistic technique does detect violations.

 

 

<<Prev Next>>

In optimistic concurrency models, a row is only locked during the update to the database. Therefore the data can be retrieved and updated by other users at any time other than during the actual row update operation. Optimistic concurrency allows the data to be read simultaneously by multiple users and blocks other users less often than its pessimistic counterpart, making it a good choice for ADO.NET. In optimistic models, it is important to implement some type of concurrency violation detection that will catch any additional attempt to modify records that have already been modified but not committed. You can write your code to handle the violation by always rejecting and canceling the change request or by overwriting the request based on some business rules. Another way to handle the concurrency violation is to let the user decide what to do. The sample application that is shown in Figure 1 illustrates some of the options that can be presented to the user in the event of a concurrency violation.

Where Did My Changes Go?

When users are likely to overwrite each other's changes, control mechanisms should be put in place. Otherwise, changes could be lost. If the technique you're using is the last-in wins approach, then these types of overwrites are entirely possible.For example, imagine Julie wants to edit an employee's last name to correct the spelling. She navigates to a screen which loads the employee's information into a DataSet and has it presented to her in a Web page. Meanwhile, Scott is notified that the same employee's phone extension has changed. While Julie is correcting the employee's last name, Scott begins to correct his extension. Julie saves her changes first and then Scott saves his.Assuming that the application uses the last-in wins approach and updates the row using a SQL WHERE clause containing only the primary key's value, and assuming a change to one column requires the entire row to be updated, neither Julie nor Scott may immediatelyrealize the concurrency issue that just occurred. In this particular situation, Julie's changes were overwritten by Scott's changes because he saved last, and the last name reverted to the misspelled version.

So as you can see, even though the users changed different fields, their changes collided and caused Julie's changes to be lost. Without some sort of concurrency detection and handling, these types of overwrites can occur and even go unnoticed.When you run the sample application included in this column's download, you should open two separate instances of Microsoft® Internet Explorer. When I generated the conflict, I opened two instances to simulate two users with two separate sessions so that a concurrency violation would occur in the sample application. When you do this, be careful not to use Ctrl+N because if you open one instance and then use the Ctrl+N technique to open another instance, both windows will share the same session.

Detecting Violations

The concurrency violation reported to the user in Figure 1 demonstrates what can happen when multiple users edit the same data at the same time. In Figure 1, the user attempted to modify the first name to "Joe" but since someone else had already modified the last name to "Fuller III," a concurrency violation was detected and reported. ADO.NET detects a concurrency violation when a DataSet containing changed values is passed to a SqlDataAdapter's Update method and no rows are actually modified. Simply using the primary key (in this case the EmployeeID) in the UPDATE statement's WHERE clause will not cause a violation to be detected because it still updates the row (in fact, this technique has the same outcome as the last-in wins technique). Instead, more conditions must be specified in the WHERE clause in order for ADO.NET to detect the violation.

The key here is to make the WHERE clause explicit enough so that it not only checks the primary key but that it also checks for another appropriate condition. One way to accomplish this is to pass in all modifiable fields to the WHERE clause in addition to the primary key. For example, the application shown in Figure 1 could have its UPDATE statement look like the stored procedure that's shown in Figure 2.

Notice that in the code in Figure 2 nullable columns are also checked to see if the value passed in is NULL. This technique is not only messy but it can be difficult to maintain by hand and it requires you to test for a significant number of WHERE conditions just to update a row. This yields the desired result of only updating rows where none of the values have changed since the last time the user got the data, but there are other techniques that do not require such a huge WHERE clause.

Another way to make sure that the row is only updated if it has not been modified by another user since you got the data is to add a timestamp column to the table. The SQL Server(tm) TIMESTAMP datatype automatically updates itself with a new value every time a value in its row is modified. This makes it a very simple and convenient tool to help detect concurrency violations.

A third technique is to use a DATETIME column in which to track changes to its row. In my sample application I added a column called LastUpdateDateTime to the Employees table.

ALTER TABLE Employees ADD LastUpdateDateTime DATETIME

There I update the value of the LastUpdateDateTime field automatically in the UPDATE stored procedure using the built-in SQL Server GETDATE function.

The binary TIMESTAMP column is simple to create and use since it automatically regenerates its value each time its row is modified, but since the DATETIME column technique is easier to display on screen and demonstrate when the change was made, I chose it for my sample application. Both of these are solid choices, but I prefer the TIMESTAMP technique since it does not involve any additional code to update its value.

Retrieving Row Flags

One of the keys to implementing concurrency controls is to update the timestamp or datetime field's value back into the DataSet. If the same user wants to make more modifications, this updated value is reflected in the DataSet so it can be used again. There are a few different ways to do this. The fastest is using output parameters within the stored procedure. (This should only return if @@ROWCOUNT equals 1.) The next fastest involves selecting the row again after the UPDATE within the stored procedure. The slowest involves selecting the row from another SQL statement or stored procedure from the SqlDataAdapter's RowUpdated event.

I prefer to use the output parameter technique since it is the fastest and incurs the least overhead. Using the RowUpdated event works well, but it requires me to make a second call from the application to the database. The following code snippet adds an output parameter to the SqlCommand object that is used to update the Employee information:

oUpdCmd.Parameters.Add(new SqlParameter("@NewLastUpdateDateTime",

  SqlDbType.DateTime, 8, ParameterDirection.Output,

  false, 0, 0, "LastUpdateDateTime", DataRowVersion.Current, null));

oUpdCmd.UpdatedRowSource = UpdateRowSource.OutputParameters;

The output parameter has its sourcecolumn and sourceversion arguments set to point the output parameter's return value back to the current value of the LastUpdateDateTime column of the DataSet. This way the updated DATETIME value is retrieved and can be returned to the user's .aspx page. Contd....

Saving Changes

Now that the Employees table has the tracking field (LastUpdateDateTime) and the stored procedure has been created to use both the primary key and the tracking field in the WHERE clause of the UPDATE statement, let's take a look at the role of ADO.NET. In order to trap the event when the user changes the values in the textboxes, I created an event handler for the TextChanged event for each TextBox control:

private void txtLastName_TextChanged(object sender, System.EventArgs e)

{

    // Get the employee DataRow (there is only 1 row, otherwise I could

    // do a Find)

    dsEmployee.EmployeeRow oEmpRow =

           (dsEmployee.EmployeeRow)oDsEmployee.Employee.Rows[0];

    oEmpRow.LastName = txtLastName.Text;

    // Save changes back to Session

    Session["oDsEmployee"] = oDsEmployee;

}

This event retrieves the row and sets the appropriate field's value from the TextBox. (Another way of getting the changed values is to grab them when the user clicks the Save button.) Each TextChanged event executes after the Page_Load event fires on a postback, so assuming the user changed the first and last names, when the user clicks the Save button, the events could fire in this order: Page_Load, txtFirstName_TextChanged, txtLastName_TextChanged, and btnSave_Click.

The Page_Load event grabs the row from the DataSet in the Session object; the TextChanged events update the DataRow with the new values; and the btnSave_Click event attempts to save the record to the database. The btnSave_Click event calls the SaveEmployee method (shown in Figure 3) and passes it a bLastInWins value of false since we want to attempt a standard save first. If the SaveEmployee method detects that changes were made to the row (using the HasChanges method on the DataSet, or alternatively using the RowState property on the row), it creates an instance of the Employee class and passes the DataSet to its SaveEmployee method. The Employee class could live in a logical or physical middle tier. (I wanted to make this a separate class so it would be easy to pull the code out and separate it from the presentation logic.)

Notice that I did not use the GetChanges method to pull out only the modified rows and pass them to the Employee object's Save method. I skipped this step here since there is only one row. However, if there were multiple rows in the DataSet's DataTable, it would be better to use the GetChanges method to create a DataSet that contains only the modified rows.

If the save succeeds, the Employee.SaveEmployee method returns a DataSet containing the modified row and its newly updated row version flag (in this case, the LastUpdateDateTime field's value). This DataSet is then merged into the original DataSet so that the LastUpdateDateTime field's value can be updated in the original DataSet. This must be done because if the user wants to make more changes she will need the current values from the database merged back into the local DataSet and shown on screen. This includes the LastUpdateDateTime value which is used in the WHERE clause. Without this field's current value, a false concurrency violation would occur.

Reporting Violations

If a concurrency violation occurs, it will bubble up and be caught by the exception handler shown in Figure 3 in the catch block for DBConcurrencyException. This block calls the FillConcurrencyValues method, which displays both the original values in the DataSet that were attempted to be saved to the database and the values currently in the database. This method is used merely to show the user why the violation occurred. Notice that the exDBC variable is passed to the FillConcurrencyValues method. This instance of the special database concurrency exception class (DBConcurrencyException) contains the row where the violation occurred. When a concurrency violation occurs, the screen is updated to look like Figure 1.

The DataSet not only stores the schema and the current data, it also tracks changes that have been made to its data. It knows which rows and columns have been modified and it keeps track of the before and after versions of these values. When accessing a column's value via the DataRow's indexer, in addition to the column index you can also specify a value using the DataRowVersion enumerator. For example, after a user changes the value of the last name of an employee, the following lines of C# code will retrieve the original and current values stored in the LastName column:

string sLastName_Before = oEmpRow["LastName", DataRowVersion.Original];

string sLastName_After = oEmpRow["LastName", DataRowVersion.Current];

The FillConcurrencyValues method uses the row from the DBConcurrencyException and gets a fresh copy of the same row from the database. It then displays the values using the DataRowVersion enumerators to show the original value of the row before the update and the value in the database alongside the current values in the textboxes.

User's Choice

Once the user has been notified of the concurrency issue, you could leave it up to her to decide how to handle it. Another alternative is to code a specific way to deal with concurrency, such as always handling the exception to let the user know (but refreshing the data from the database). In this sample application I let the user decide what to do next. She can either cancel changes, cancel and reload from the database, save changes, or save anyway.

The option to cancel changes simply calls the RejectChanges method of the DataSet and rebinds the DataSet to the controls in the ASP.NET page. The RejectChanges method reverts the changes that the user made back to its original state by setting all of the current field values to the original field values. The option to cancel changes and reload the data from the database also rejects the changes but additionally goes back to the database via the Employee class in order to get a fresh copy of the data before rebinding to the control on the ASP.NET page.

The option to save changes attempts to save the changes but will fail if a concurrency violation is encountered. Finally, I included a "save anyway" option. This option takes the values the user attempted to save and uses the last-in wins technique, overwriting whatever is in the database. It does this by calling a different command object associated with a stored procedure that only uses the primary key field (EmployeeID) in the WHERE clause of the UPDATE statement. This technique should be used with caution as it will overwrite the record.

If you want a more automatic way of dealing with the changes, you could get a fresh copy from the database. Then overwrite just the fields that the current user modified, such as the Extension field. That way, in the example I used the proper LastName would not be overwritten. Use this with caution as well, however, because if the same field was modified by both users, you may want to just back out or ask the user what to do next. What is obvious here is that there are several ways to deal with concurrency violations, each of which must be carefully weighed before you decide on the one you will use in your application.

Wrapping It Up

Setting the SqlDataAdapter's ContinueUpdateOnError property tells the SqlDataAdapter to either throw an exception when a concurrency violation occurs or to skip the row that caused the violation and to continue with the remaining updates. By setting this property to false (its default value), it will throw an exception when it encounters a concurrency violation. This technique is ideal when only saving a single row or when you are attempting to save multiple rows and want them all to commit or all to fail.

I have split the topic of concurrency violation management into two parts. Next time I will focus on what to do when multiple rows could cause concurrency violations. I will also discuss how the DataViewRowState enumerators can be used to show what changes have been made to a DataSet.

How you will set the datarelation between two columns?
ADO.NET provides DataRelation object to set relation between two columns.It helps to enforce the following  constraints,a unique constraint, which guarantees that a column in the table  contains no duplicates and a foreign-key constraint,which can be used to maintain referential  integrity.A unique constraint is implemented either by simply setting the Unique property of a data  column to true, or by adding an instance of the UniqueConstraint class to the DataRelation object's ParentKeyConstraint. As part of the foreign-key constraint, you can specify referential integrity  rules that are applied at three points,when a parent record is updated,when a parent record is deleted and when a change is accepted or rejected.


 

Posted on Wednesday, April 2, 2008 10:43 PM Study | Back to top


Comments on this post: Simple Questions on .NET

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Gaurav Taneja | Powered by: GeeksWithBlogs.net