dot-net-faqs - WordPress.com

advertisement

Chapter 1: Basic .NET Framework

1. What is an IL?

A. MSIL stands for Microsoft Intermediate Language in short MSIL or IL(Intermediate

Language). When you compile a program the CLR will compile the code into MSIL code.

Which will then be included in the assembly[exe/dll]. When you run the program in client place. The clr will manage to convert the MSIL into machine language by a process called

Jitting.

When we compile our .Net Program using any .Net compliant language like (C#, VB.NET,

C++.NET) it does not get converted into the executable binary code but to an intermediate code, called MSIL or IL in short, understandable by CLR. MSIL is an OS and H/w independent code. When the program needs to be executed, this MSIL or intermediate code is converted to binary executable code, called native code. The presence of IL makes it possible the Cross Language Relationship as all the .Net compliant languages produce the similar standard IL code.

2. What is a CLR?

A. CLR Stands For common language runtime. It is the implementation for CLI Common language implementation. The core run time engine in the Microsoft .Net framework for executing .net applications. The CLR Supplies Managed code with services such as cross language integration, code access security object life time management, resource management, type safety, pre-emptive threading, metadata services(type reflections) and debugging and profiling support.

The most important part of the .NET Framework is the .Net Common Language Runtime

(CLR) also called .Net Runtime in short. It is a framework layer that resides above the

Operating System and handles/manages the execution of the .NET applications. Our .Net programs don't directly communicate with the Operating System but through CLR.

3. What is CTS?

A. CTS stand for Common Type System.

The CTS makes available a common set of data types so that compiled code of one language could easily interoperate with compiled code of another language by understanding each others‘ data types.

A fundamental part of the .NET Framework's Common Language Runtime (CLR), the CTS specifies no particular syntax or keywords, but instead defines a common set of types that can be used with many different language syntaxes.

4. What is a CLS (Common Language Specification)?

A. Common Language Specification (CLS):The Common Language Specification (CLS) describes a set of features that different languages have in common.

The CLS includes a subset of the Common Type System (CTS).

5. What is a Managed Code?

A. By managed code, it means that the complete life cycle and execution is managed by the

.NET Common Language Runtime (CLR). The .NET CLR manages the memory on behalf of the managed code, performs garbage collection on the managed heap, perform assembly validation and assembly (component) resolution on behalf of the program. The CLR also maintains the security constraints applied to the managed code

Managed code is code that is written to target the services of the Common Language

Runtime. In order to target these services, the code must provide a minimum level of

information (metadata) to the runtime. All C#, Visual Basic .NET, and JScript .NET code is managed by default. Visual Studio .NET C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/CLR).

6. What is a Assembly?

A. The .NET assembly is the standard for components developed with the Microsoft.NET. Dot

NET assemblies may or may not be executable, i.e., they might exist as the executable

(.exe) file or dynamic link library (DLL) file. All the .NET assemblies contain the definition of types, versioning information for the type, meta-data, and manifest. The designers of .NET have worked a lot on the component (assembly) resolution.

7. What are the different types of Assembly?

There are three kinds of assemblies in .NET;

Private Assemblies.

Shared Assemblies.

Satellite Assemblies.

Private assemblies are simple and copied with each calling assemblies in the calling assemblies folder.

Shared assemblies (also called strong named assemblies) are copied to a single location

(usually the Global assembly cache). For all calling assemblies within the same application, the same copy of the shared assembly is used from its original location. Hence, shared assemblies are not copied in the private folders of each calling assembly. Each shared assembly has a four part name including its face name, version, public key token and culture information. The public key token and version information makes it almost impossible for two different assemblies with the same name or for two similar assemblies with different version to mix with each other.

An assembly can be a single file or it may consist of the multiple files. In case of multi-file, there is one master module containing the manifest while other assemblies exist as nonmanifest modules. A module in .NET is a sub part of a multi-file .NET assembly. Assembly is one of the most interesting and extremely useful areas of .NET architecture along with reflections and attributes, but unfortunately very few people take interest in learning such theoretical looking topics.

Satellite Assembly Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated witha given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. For example,

English and Japanese editions of the .NET Framework version 1.1 share the same core files.

The Japanese .NET Framework version 1.1 adds satellite assemblies withlocalized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files

A8. What is NameSpace?

A. A namespace is a logical naming scheme for types in which a simple type name, such as

MyType, is preceded with a dot-separated hierarchical name. Such a naming scheme is completely under control of the developer. For example, types MyCompany.FileAccess.A and

MyCompany.FileAccess.B might be logically expected to have functionally related to file access. The .

NET Framework uses a hierarchical naming scheme for grouping types into logical categories of related functionality, such as the ASP.NET application framework , or remoting functionality. Design tools can make use of namespaces to make it easier for

developers to browse and reference types in their code.

9. What is Difference between NameSpace and Assembly?

A. A namespace is a logical naming scheme for types in which a simple type name, such as

MyType, is preceded with a dot-separated hierarchical name. Such a naming scheme is completely under control of the developer. For example, types MyCompany.FileAccess.A and

MyCompany.FileAccess.B might be logically expected to have functionally related to file access. The .

NET Framework uses a hierarchical naming scheme for grouping types into logical categories of related functionality, such as the ASP.NET application framework , or remoting functionality. Design tools can make use of namespaces to make it easier for developers to browse and reference types in their code.

The concept of a namespace is not related to that of an assembly. A single assembly may contain types whose hierarchical names have different namespace roots, and a logical namespace root may span multiple assemblies. In the .NET Framework, a namespace is a logical design-time naming convenience, whereas an assembly establishes the name scope for types at run time.

10. If you want to view an Assembly how do you go about it?

A. There Is No other tool to view or to get about assembly other than ILDASM.

11. What is Manifest?

A. Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information.

12. Where is version information stored of an assembly?

A. Assembly version information is stored in Manifest.

13. Is versioning applicable to private assemblies?

A. No.

14. What is GAC?

A. The Global Assembly Cache or the popular acronym GAC refers to the machine-wide code cache in any of the computers that have been installed with common language runtime. The

GAC or the Global Assembly Cache in .NET Framework acts as the central place for registering assemblies.

15. what is the concept of strong names?

A. Strong name is basically linked with shared Assemblies. When you publish your assembly in Globle Assembly Cache at that time you need to give strong name to that assembly. To give strong name you can use sn.exe from .net command prompt.

A strong name consists of the assembly's identity — its simple text name, version number, and culture information (if provided) — plus a public key and a digital signature. It is generated from an assembly file using the corresponding private key. (The assembly file contains the assembly manifest, which contains the names and hashes of all the files that

make up the assembly.)

Remember that once you give an assembly a strong name, all assemblies that reference that assembly also have to have strong names, so that the security of the strongly named assembly is not compromised.

Note Once an assembly is created, you cannot sign it with a strong name. You can sign an assembly with a strong name only when you create it.

16. How to add and remove an assembly from GAC?

A. Each computer that .NET is installed on has a Global Assembly Cache (GAC) located in the Assembly folder in the Windows directory (usually: C:\WinNT\Assembly). The GAC contains information about shared assemblies which are components that can be shared among several applications (Ex. a DLL). Shared assemblies must have globally unique names derived from their strong names (public keys generated to distinguish assemblies from other assemblies that may have the same names) which is Microsoft's solution to DLL hell. The GAC, not the registry, is the store for this information. When an application loads the GAC is examined by the Common Language Runtime to determine if the version of a shared component exists that is compatible with the one referenced by the application.

The gacutil.exe

that ships with .NET can be used to add or remove a shared assembly from the GAC.

To add a shared assembly, from the command line enter:

gacutil.exe /i myassembly.dll

To remove a shared assembly, from the command line enter:

gacutil.exe /u myassembly.dll

When viewing the GAC in Windows Explorer shfusion.dll

is used to provide the user interface. You can locate and rename this DLL to view the GAC like any other folder.

17. What is Delay signing?

A. Delay signing allows to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed.

This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.

18. What is garbage collection?

A. The garbage collector in .Net takes care of bulk of the memory management responsibility, freeing up the developer to focus on core issues. The garbage collector is optimized to perform the memory free-up at the best time based upon the allocations being made. Java developers have enjoyed the benefits of Garbage collection. VB developers are also used to a certain amount of flexibility in these terms and .Net provides full-fledged memory management capabilities for managed resources.

19. Can we force garbage collector to run?

A. Yes we can force garbage collection by invoking the (GC.Collect) method from the program. This is not advisable and should be used only in extreme cases.

20. What is reflection?

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

Reflection is the ability to read metadata at runtime. Using reflection, it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically.

Reflection also allows us to create new types at runtime, but in the upcoming example we will be reading and invoking only.

21. What are different types of JIT?

Pre-JIT (Compiles entire code into native code at one stretch)

Ecno-JIT (Compiles code part by part freeing when required)

Normal JIT (Compiles only that part of code when called and places in cache)

22. What are Value types and Reference types?

Value types inherit from the System.ValueType

class, which in turn, inherits from System.

Object . However, you can not inherit directly from the System.ValueType

class.

If you try to inherit explicitly from System.Value

, you'll get the C3838 compiler error. Value types have several special properties:

Value types are stored on the stack. (We'll discover that shortly.)

Value type objects have two representations: an unboxed form and a boxed form.

Value types are accessed directly which means you don't need to use the new operator.

Value types are managed types, they are initialised to 0 when they are created.

Value type instances are not under the control of the Garbage Collector.

Value types are implicitly sealed , which means that no class can derive from them.

In C#, struct s are always value types and allocated on the stack.

Reference types inherit directly from System.

Object , they offer many advantages over Value types:

Reference types are stored on the managed heap, thus they are under the control of

Garbage Collector.

Two or more reference type variables can refer to a single object in the heap, allowing operations on one variable to affect the object referenced by the other variable.

The variable representing the instance contains a pointer to the instance of the class, it is dereferenced first if you want to access any of its members. In C#, Class es are always reference types and created on the managed heap.

23.What is concept of Boxing and Unboxing ?

Boxing and unboxing is a essential concept in C#‘s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. Converting a value type to reference type is called Boxing. Unboxing is an explicit operation.

24.What is the difference between VB.NET and C#?

Difference between VB.NET and C#.

VB.NET :

1)no unsigned int

2)Loosely typed language

3)no operator overloading

4)no pointers

5)no auto XML documentation

C#.net :

1) supports unsigned int

2)strongly typed language

3)supports operator overloading

4)supports pointers

5)supports auto XML documentation

25.what is the difference between System exceptions and Application exceptions?

26.What is CODE Access security?

CAS is a security model that lets you grant or deny execution permissions to an assembly according to its "properties," called evidence, such as its strong name or publisher. CAS is completely orthogonal to classic security models that lie on the authentication-permissions mechanism based on the identity of the caller. This article is a concise introduction to this compelling and fascinating topic.

27.What is a satellite assembly?

Satellite Assembly Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated witha given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. For example,

English and Japanese editions of the .NET Framework version 1.1 share the same core files.

The Japanese .NET Framework version 1.1 adds satellite assemblies withlocalized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files

28.How to prevent my .NET DLL to be decompiled?

By design .NET embeds rich Meta data inside the executable code using MSIL. Any one can easily decompile your DLL back using tools like ILDASM (owned by Microsoft) or Reflector for.NET which is a third party. Secondly there are many third party tools which make this decompiling process a click away. So any one can easily look in to your assemblies and reverse engineer them back in to actual source code and understand some real good logic which can make it easy to crack your application .The process by which you can stop this reverse engineering is using ―obfuscation‖. It‘s a technique which will foil the decompilers.

There are many third parties (XenoCode, Demeanor for .NET) which provide .NET obfuscation solution. Microsoft includes one that is Dotfuscator Community Edition with

Visual Studio.NET.

29.what is the difference between Convert.toString and .toString () method?

A. Convert.ToString wont allow null values. Cannot convert null to String

Whereas .ToString accepts null values

30.What is Native Image Generator (Ngen.exe)?

The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer. The runtime can use native images from the cache instead using the just-in-time

(JIT) compiler to compile the original assembly.

31. If we have two version of same assembly in GAC how do we make a choice?

32. What is CodeDom?

The CodeDOM provides types that represent many common types of source code elements.

You can design a program that builds a source code model using CodeDOM elements to assemble an object graph. This object graph can be rendered as source code using a

CodeDOM code generator for a supported programming language. The CodeDOM can also be used to compile source code into a binary assembly.

Some common uses for the CodeDOM include:

Templated code generation: generating code for ASP.NET, XML Web services client proxies, code wizards, designers, or other code-emitting mechanisms.

Dynamic compilation: supporting code compilation in single or multiple languages.

Chapter 2: NET Interoperability

1.

How can we use COM Components in .NET?

.NET components communicate with COM using RCW (Runtime Callable Wrapper).

Following are the ways with which you can generate RCW :

 Adding reference in Visual Studio.net. Wrapper class is generated and placed in the "BIN" directory.

Using Type library import tool. Tlbimp.exe yourname.dll.

Using Interopservices.System.Runtime.InteropServices namespace contains class TypeLib Converter which provides methods to convert COM classes and interface in to assembly metadata.

Make your custom wrappers.If your COM component does not have type library then the only way to communicate is writing custom wrappers. That means communicating directly with COM components.

2.

Once I have developed the COM wrapper do I have to still register the COM in registry?

Yes

3.

How can we use .NET components in COM?

.NET components can not be used in straight forward way with COM. You will need to create CCW (COM Callable Wrapper) in order that COM components communicate with

.NET assemblies. Following are the different approaches to implement it:

 Explicitly declare interfaces.

Public Interface ICustomer

Property CustomerName() As String

Property CustomerCode() As String

Sub AddCustomer()

End Interface

Public Class Customer Implements ICustomer

Private PstrCustomerName As String

Private PstrCustomerCode As String

Public Sub AddCustomer() Implements ICustomer.AddCustomer

Try

‗ addin of database code can go here

Catch ex As Exception

Throw ex

End Try

End Sub

Public Property CustomerCode() As String Implements

ICustomer.CustomerCode

Get

Return PstrCustomerCode

End Get

Set(ByVal value As String)

PstrCustomerCode = value

End Set

End Property

Public Property CustomerName() As String Implements

ICustomer.CustomerName

Get

Return PstrCustomerName

4.

End Get

Set(ByVal value As String)

PstrCustomerName = value

End Set

End Property

Public Sub New()

End Sub

End Class

The above customer class is going to be used by COM components so all the properties and methods are declared in interface and implemented in the customer class. Customer Name.Customer Code and AddCustomer are first declared in ICustomer and then implemented in Customer Class. Also note that the class must have a default constructor.

To create CCW is by using InteropServices attributes. Here interfaces are created automatically

Following are different type of class attributes :

None: No class interface is generated for the class. This is default setting when you do not specify anything.

AutoDispatch: Interface that supports IDispatch is created for the class.

However, no type information is produced.

AutoDual : A dual interface is created for the class. Type information is produced and made available in the type library.

Below is an example of code that uses third attribute:

Imports System.Runtime.InteropServices _

<ClassInterfaceAttribute(ClassInterfaceType.AutoDual)> _

Public Class ClsCompliant

End Class

Other than class attributes defined up there are other attributes with which you can govern other part of assembly. Example "GuidAttribute" allows you to specify the GUID, "ComVisibleAttribute" can be used to hide .NET types from

COM etc.

Once .NET assembly is created using either interface or using interopservices method we need to create a COM type library using Type library export tool. Tlbexp (AssemblyName)

The final thing is registering the CCW in registry using regasm tool. regasm

AssemblyName [Options]

Finally refer the TLB in your COM IDE. DLL and TLB should be in same directory where the application is executed.

How can we make Windows API calls in .NET?

Windows API call are not COM based and they are invoked through Platform Invoke

Services.

Declare StringConversionType (Function | Sub) MethodName Lib "DllName" ([Args])

As Type where

StringConversionType is for what type of conversion should take place. Either we can specify Unicode to convert all strings to Unicode values, or Auto to convert strings according to the .NET runtime rules.

MethodName is the name of the API to call.

DllName is the name of the DLL

Args are any arguments to the API call.

Type is the return type of the API call.

Below is a sample code for VB.NET which uses Sleep windows API for delaying.

Public Class Form1

Declare Auto Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds

As Long)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles MyBase.Load

MessageBox.Show(" start sleeping for 5000 Milliseconds.....")

Sleep(5000)

MessageBox.Show(" end of sleeping.....")

End Sub

End Class

And also example in C#:

#region Using directives using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices;

#endregion namespace CSharpCode

{ partial class Form1 : Form

{

[DllImport("Kernel32.dll")] static extern int Sleep(long dwMilliseconds); public Form1()

{

InitializeComponent();

} private void Form1_Load(object sender, EventArgs e)

{

MessageBox.Show("Starting of 5000 ms...");

Sleep(5000);

MessageBox.Show("End of 5000 ms...");

}

}

}

5.

When we use Windows API in .NET is it managed or unmanaged code?

Windows API in .NET is unmanaged code.

6.

What is COM?

Microsoft‘s COM is a technology for component software development. It is a binary standard which is language independent. DCOM is a distributed extension of COM.

7.

What is Reference counting in COM?

Reference counting is a memory management technique used to count how many times an object has a pointer referring to it. The first time it is created, the reference count is set to one. When the last reference to the object is nulled, the reference count is set to zero and the object is deleted. Care must be exercised to prevent a context switch from changing the reference count at the time of deletion.

8.

Can you describe IUnknown interface in short?

Every COM object supports at least one interface, the IUnknown interface. All interfaces are classes derived from the base class IUnknown. Each interface supports methods access data and perform operations transparently to the programmer. For example, IUnknown supports three methods, AddRef, Release(), and

QueryInterface(). Suppose that pinterf is a pointer to an IUnknown.pinterf->AddRef() increments the reference count.pinterf->Release() decrements the reference count, deleting the object when the reference count reaches zero. pinterf->QueryInterface(

IDesired, pDesired) checks to see if the current interface (IUnknown) supports another interface, IDesired, creates an instance (via a call to CoCreateInstance()) of the object if the reference count is zero (the object does not yet exist), and then calls pDesired->AddRef() to increment the reference count (where pDesired is a pointer to

IDesired) and returns the pointer to the caller.

9.

What is DCOM?

DCOM differs from COM in that it allows for creating objects distributed across a network, a protocol for invoking that object‘s methods, and secures access to the object. DCOM provides a wrapper around COM, hence it is a backwards compatible extension. DCOM uses Remote Procedural Calls (RPC) using Open Software

Foundation‘s Distributed Computing Environment.

These RPC are implemented over TCP/IP and named pipes. The protocol which is actually being used is registered just prior to use, as opposed to being registered at initialization time. The reason for this is that if a protocol is not being used, it will not be loaded.

In order to inform an object that the client is still alive, periodic pinging is used.

Hence, when the client has died and no ping has been received (to refresh it) before the expiration time, the server object will perform some clean up tasks (including decrementing its reference count).

Since RPC across a network are typically slow (compared to processes residing on the same machine), DCOM sends multiple requests in the same call. For example, in COM, the program performs a QueryInterface, one interface at a time. In DCOM, multiple

QueryInterfaces are all clustered into one call.

This clustering optimization trick is also used when creating an instance of the object and serializing it with data. Since these two operations usually occur together, DCOM allows one method which will perform both operations in one call without waiting for an acknowledgment from the first task before performing the second one.

Similarly, when a client pings its server object, he can do it in one call. Moreover, if there are multiple clients sending pings to multiple servers, an optimization is made where the multiple pings going to the same object are consolidated into just one ping.

This is to cut down on the use of precious bandwidth used only for pinging.

The client has the control to set the computer which will be responsible for the lifetime of the object. That is to say, these objects are not created just somewhere where the system resources and access privileges allow for it.

Call security is implemented in all four ways: authentication (to prevent false clients from impersonating the true client), authorization (to insure that a client only does what it is authorized to do), data integrity (to insure that data was not tampered with during transit) and data privacy (to insure that only designated sources can read it).

The security issues are handled as they are on operating systems. The client gives the server various access privileges to access memory or disk space.

10.

How do we create DCOM object in VB6?

Using the CreateObject method you can create a DCOM object. You have to put the server name in the registry.

11.

How to implement DTC (Distributed Transactions Coordinator) in .NET ?

DTC is implemented using COM+.

Following are the steps to implement COM + in .NET :

 "EnterpriseService" namespace has all the classes by which we can implement

DTC in .NET. You have to add reference to "EnterpriseService" namespace.

You class must derive from "ServicedComponent" object.

Then you have to define your class with the transaction attribute [

Transaction(TransactionOption.RequiresNew) ]

After the class level transaction type is defined. Its time to define at the method level the AutoComplete attribute. Autocomplete attribute says that if no exception is thrown then mark its part of the transaction as being okay. This helps cut down on the amount of code required. If the implementation sets

AutoComplete to false, or omits it all together, then we would need to manage the transaction manually. To manually control the transaction you will need to use the ContextUtil class and its static members. Following is small snippet of

ContextUtil: public void SampleFunction()

{ try

{

// Do something to a database

12.

// ...

// Everything okay so far Commit the transaction

ContextUtil.SetComplete();

} catch(Exception)

{

// Something went wrong Abort and Rollback the Transaction.

ContextUtil.SetAbort();

}

}

Component derived from "ServicedComponent" should be strong named as they run under COM+.

Once the classes are compiled using the string name.Register the Component in COM+ services using regsvcs c:\DllPath\TransactionComponent.dll

You can see that the component is registered using the COM+ Explorer.

How many types of Transactions are there in COM + .NET?

There are 5 transactions types that can be used with COM+. Whenever an object is registered with COM+ it has to abide either to these 5 transaction types.

Disabled: There is no transaction. COM+ does not provide transaction support for this component.

Not Supported: Component does not support transactions. Hence even if the calling component in the hierarchy is transaction enabled this component will not participate in the transaction.

Supported: Components with transaction type support will be a part of the transaction. This will be only if the calling component has an active transaction. If the calling component is not transaction enabled this component will not start a new transaction.

Required: Components with this attribute require a transaction i.e. either the calling should have a transaction in place else this component will start a new transaction.

Required New: Components enabled with this transaction type always require a new transaction. Components with required new transaction type instantiate a new

13.

transaction for themselves every time.

How do you do object pooling in .NET?

COM+ reduces overhead by creating object from scratch. So in COM+ when object is activated its activated from pool and when its deactivated it‘s pushed back to the pool. Object pooling is configures by using the "ObjectPoolingAttribute" to the class.

When a class is marked with objectpooling attribute it can not be inherited.

<ObjectPooling(MinPoolSize := 2, MaxPoolSize := 5, CreationTimeout := 20000)> _

Public Class TestingClass Inherits ServicedComponent

Public Sub DoWork()

' Method contents go here.

End Sub

End Class

Below is a sample code which uses the class.

Public Class App

Overloads Public Shared Sub Main(args() As String)

Dim xyz As New TestObjectPooling() xyz.doWork()

ServicedComponent.DisposeObject (xyz)

End Sub

End Class

Note the DisposeObject() This ensures its safe return to the object pool.

14.

What are types of compatibility in VB6?

There are three possible project compatibility settings:

No Compatibility With this setting, new class ID‘s, new interface ID‘s and a new type library ID will be generated by VB each time the ActiveX component project is compiled. This will cause any compiled client components to fail (with error 429!) and report a missing reference to the ‗VB ActiveX Test Component‘ when a client project is loaded in the VB IDE. Use this setting to compile the initial release of a component to other developers.

Project Compatibility With this setting, VB will generate new interface ID‘s for classes whose interfaces have changed, but will not change the class ID‘s or

 the type library ID. This will still cause any compiled client components to fail

(with error 429!) but will not report a missing reference to the ‗VB ActiveX Test

Component‘ when a client project is loaded in the VB IDE. Recompilation of client components will restore them to working order again. Use this setting during the initial development and testing of a component within the IDE and before the component is released to other developers.

Binary Compatibility VB makes it possible to extend an existing class or interface by adding new methods and properties etc. and yet still retain binary compatibility. It can do this, because it silently creates a new interface ID for the extended interface and adds registration code to register the original interface ID but with a new Forward key containing the value of this new interface ID. COM will then substitute calls having the old ID with the new ID and hence applications built against the old interface will continue to work

(assuming the inner workings of the component remain backward compatible!).

With this setting, VB will not change any of the existing class, interface or type library ID‘s, however in order that it can do so, VB requires the project to specify an existing compiled version that it can compare against to ensure that existing interfaces have not been broken.

15.

What is equivalent for regsvr32 exe in .NET ?

Regasm.exe - The Assembly Registration tool reads the metadata within an assembly and adds the necessary entries to the registry, which allows COM clients to create

.NET Framework classes transparently.

Chapter 3: Threading

1.

What is multi-tasking?

It is a feature of modern operating systems with which we can run multiple programs at same time

2.

What is multi-threading?

Multi-threading forms subset of multi-tasking. Instead of having to switch between programs this feature switches between different parts of the same program. Example you are writing in word and at the same time word is doing a spell check in background.

3.

What is a Thread?

4.

A thread is the basic unit to which the operating system allocates processor time.

Did VB6 support multi-threading?

While VB6 supports multiple single-threaded apartments, it does not support a freethreading model, which allows multiple threads to run against the same set of data.

5.

Can we have multiple threads in one AppDomain ?

One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process. Each AppDomain is started with a single thread, but can create additional threads from any of its threads. All threading classes are defined in System.Threading namespace.

6.

Which namespace contains threading - related classes ?

Systems.Threading has all the classes related to implement threading. Any .NET application who wants to implement threading has to import this namespace. .NET program always has at least two threads running one is the main program and second is the garbage collector.

7.

How can we implement threading ?

Below is an example in VB.Net:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles MyBase.Load

Dim pthread1 As New Thread(AddressOf Thread1)

Dim pthread2 As New Thread(AddressOf Thread2) pthread1.Start() pthread2.Start()

End Sub

Public Sub Thread1()

Dim pintcount As Integer

Dim pstr As String pstr = "This is first thread"

Do Until pintcount > 5 lstThreadDisplay.Items.Add(pstr) pintcount = pintcount + 1

Loop

End Sub

Public Sub Thread2()

Dim pintcount As Integer

Dim pstr As String pstr = "This is second thread"

Do Until pintcount > 5 lstThreadDisplay.Items.Add(pstr) pintcount = pintcount + 1

Loop

End Sub

How can we change priority and what the levels of priority are provided by 8.

.NET ?

Thread Priority can be changed by using Threadname.Priority =

ThreadPriority.Highest. In the sample provided look out for code where the second thread is ran with a high priority.

Following are different levels of Priority provided by .NET :

 ThreadPriority.Highest

 ThreadPriority.AboveNormal

ThreadPriority.Normal

ThreadPriority.BelowNormal

ThreadPriority.Lowest

9.

What does AddressOf operator do in background?

The AddressOf operator creates a delegate object to the BackgroundProcess method.

A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the

Start() method of the thread.

10.

How can you reference current thread of the method?

"Thread.CurrentThread" refers to the current thread running in the method."CurrentThread" is a public static property.

11.

What does Thread.Sleep() do in threading?

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

12.

takes an integer value in milliseconds that determines how long the thread should sleep. Example: Thread.CurrentThread.Sleep(2000).

How can we make a thread sleep for infinite period?

You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite). To interrupt this sleep you can call the Thread.Interrupt() method.

13.

What are Suspend() and Resume() methods in threading?

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

14.

How to stop a long running thread ?

Thread.Abort() stops the thread execution at that moment itself.

15.

How to debug threads ?

"Debug\Windows\Treads" in Visual Studio gives an access to the threads debug window.This window is only seen when the program is running in debug mode.

16.

What is Thread.Join() in threading?

There are two versions of Thread.Join():

 Thread.Join().

 Thread.Join(Integer) this returns a Boolean value.

The Thread.Join() method is useful for determining if a thread has completed before starting another task. The Join() method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join() returns true; otherwise it returns False. Once you call Join(), the calling procedure stops and waits for the thread to signal that it is done.

Example you have "Thread1" and "Thread2" and while executing "Thread1" you call

"Thread2.Join()".So "Thread1" will wait until "Thread2" has completed its execution and the again invoke "Thread1".

Thread.Join(Integer) ensures that threads do not wait for a long time. If it exceeds a specific time which is provided in integer the waiting thread will start.

17.

What are daemon threads and how can a thread be created as daemon?

Daemon thread‘s run in background and stop automatically when nothing is running program. Example of a daemon thread is "Garbage collector". Garbage collector runs until some .NET code is running or else its idle. You can make a thread a daemon by assigning Thread.IsBackground=true

18.

When working with shared data in threading how do you implement synchronization ?

There are certain situtations that you need to be careful with when using threads. If two threads (e.g. the main and any worker threads) try to access the same variable at the same time, you‘ll have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock a variable before accessing it. However, if the two threads lock the same variable at the same time, you‘ll have a deadlock problem.

SyncLock x

'Do something with x

End SyncLock

19.

Can we use events with threading?

Yes, we can use events with thread; this is one of the techniques to synchronize one

20.

thread with other.

How can we know a state of a thread?

"ThreadState" property can be used to get detail of a thread. Thread can have one or a combination of Status.System.Threading. Threadstate enumeration has all the values to detect a state of thread. Some sample states are IsRunning, IsAlive,

Suspended etc.

21.

What is Interlocked class?

Interlocked class provides methods by which you can achieve following functionalities in a synchronization mode:

Increment Values.

Decrement values.

Exchange values between variables.

Compare values from any thread.

Example : System.Threading.Interlocked.Increment(intVal)

22.

What is a Monitor object?

Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished.

SyncLock and End SyncLock statements are provided in order to simplify access to monitor object.

23.

What are Wait handles and a Mutex object?

Wait handles sends signals of a thread status from one thread to other thread. There are three kind of wait modes : WaitOne, WaitAny, WaitAll.

When a thread wants to release a Wait handle it can call Set method. You can use

Mutex (mutually exclusive) objects to avail for the following modes. Mutex objects are synchronization objects that can only be owned by a single thread at a time. Threads request ownership of the mutex object when they require exclusive access to a resource. Because only one thread can own a mutex object at any time, other threads must wait for ownership of a Mutex object before using the resource.

The WaitOne method causes a calling thread to wait for ownership of a mutex object.

If a thread terminates normally while owning a mutex object, the state of the mutex

24.

object is set to be signaled and the next waiting thread gets ownership.

What are ManualResetEvent and AutoResetEvent?

Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to no signaled using the Reset method or when control returns to a waiting

WaitOne call. Instances of the AutoResetEvent class can also be set to signaled using

Set, but they automatically return to nonsignaled as soon as a waiting thread is notified that the event became signaled.

25.

What is ReaderWriter Lock?

You may want to lock a resource only when data is being written and permit multiple clients to simultaneously read data when data is not being updated. The

ReaderWriterLock class enforces exclusive access to a resource while a thread is modifying the resource, but it allows nonexclusive access when reading the resource.

ReaderWriter locks are a useful alternative to exclusive locks that cause other threads to wait, even when those threads do not need to update data.

26.

How can you avoid deadlock in threading?

A good and careful planning can avoid deadlocks.There are so many ways Microsoft has provided by which you can reduce deadlocks example Monitor, Interlocked classes, Wait handles, Event raising from one thread to other thread, ThreadState property which you can poll and act accordingly etc.

27.

What is the difference between thread and process?

A thread is a path of execution that run on CPU, a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context.

1.

Chapter 4: Remoting and Webservices

What is an application domain?

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

2.

What is .NET Remoting?

.NET remoting is replacement of DCOM. Using .NET remoting you can make remote object calls which lie in different Application Domains. As the remote objects run in different process client calling the remote object can not call it directly. So the client uses a proxy which looks like a real object.

When client wants to make method call on the remote object it uses proxy for it.

These method calls are called as "Messages". Messages are serialized using

"formatter" class and sent to client "channel". Client Channel communicates with

Server Channel. Server Channel uses as formatter to deserialize the message and sends to the remote object.

Which class does the remote object has to inherit?

3.

All remote objects should inherit from System.MarshalbyRefObject.

4.

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

There are two different ways in which object can be created using Remoting:

 SAO (Server Activated Objects) also called as Well-Known call mode.

 CAO (Client Activated Objects).

5.

SAO has two modes "Single Call" and "Singleton". With Single Call object the object is created with every method call thus making the object stateless. With Singleton the object is created only once and the object is shared with all clients.

CAO are stateful as compared to SAO. In CAO the creation request is sent from client side. Client holds a proxy to the server object created on server.

Describe in detail Basic of SAO architecture of Remoting?

Remoting has at least three sections :

Common Interface which will be shared between them.

Server.

Client.

Here is an explanation of the process:

First important section is the common interface between Server and Client.

For sample project interface is very simple with only two methods : SetValue and GetValue.

Public Interface InterFaceRemoting

Sub SetValue(ByVal value As String)

Function GetValue() As String

End Interface

Second important section is the server. In this sample server is using HTTP channel and the server object is singleton.

Imports System

Imports System.Runtime.Remoting

Imports System.Runtime.Remoting.Channels.Http

Imports System.Runtime.Remoting.Channels

Imports InterFaceRemoting

Public Class RemotingServer Inherits MarshalByRefObject

Implements InterFaceRemoting.InterFaceRemoting

Private strData As String

Public Function GetValue() As String Implements

InterFaceRemoting.InterFaceRemoting.GetValue

Return strData

End Function

Sub New() strData = "testing.."

End Sub

Public Sub SetValue(ByVal value As String) Implements

InterFaceRemoting.InterFaceRemoting.SetValue strData = value

End Sub

6.

End Class

Module ModuleRemotingStartUp

Sub Main()

Dim objHttpChannel As HttpChannel

Console.WriteLine("Server Started...") objHttpChannel = New HttpChannel(1234)

ChannelServices.RegisterChannel(objHttpChannel)

RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServe r),

"RemoteObject", WellKnownObjectMode.Singleton)

Console.WriteLine("Server registered and listening waiting for clients...")

Console.ReadLine()

End Sub

End Module

In the code above, Channel object is created and registered. Server then hosts the object so that client can connect to it. This is the time when we specify what mode the server object will be created i.e. Singleton or SingleCall. This is done by the following below given code. Note in sample we are hosting the server object in singleton mode that means that the same object will be shared between all clients. Also note the server object is implementing

"InterFaceRemoting" and inheriting from "MarshalByRefObject".

RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServe r),

"RemoteObject", WellKnownObjectMode.Singleton)

In the last section the client will connect to this hosted remoting object.

Imports System

Imports System.Runtime.Remoting

Imports System.Runtime.Remoting.Channels.Http

Imports System.Runtime.Remoting.Channels

Imports InterFaceRemoting

Module ModuleStartClient

Sub Main()

Dim objHttpChannel As New HttpChannel

Dim objRemoting As InterFaceRemoting.InterFaceRemoting

ChannelServices.RegisterChannel(objHttpChannel) objRemoting =

CType(Activator.GetObject(GetType(InterFaceRemoting.InterFaceRemoting),

"http://localhost:1234/RemoteObject"),

InterFaceRemoting.InterFaceRemoting)

Console.WriteLine("Referenced the main object.... Now displaying Data")

Console.WriteLine("Value on server :- " & objRemoting.GetValue.ToString())

Console.WriteLine("Press enter to Terminate")

Console.ReadLine()

End Sub

End Module

Finally you need to run server and then client.

What are the situations you will use singleton architecture in remoting ?

If all remoting clients have to share the same data singleton architecture will be used.

7.

What is fundamental of published or precreated objects in Remoting?

In scenarios of singleton or single call the objects are created dynamically. But in situations where you want to precreate object and publish it you will use published object scenarios.

Dim obj as new objRemote obj.Initvalue = 100

RemotingServices.Marshal(obj,"RemoteObject")

As shown in above sample following changes will be needed on server side.

RemotingConfiguration.RegisterWellKnownServiceType is replaced by

RemotingServices.Marshal(obj,"RemoteObject") where "obj" is the precreated objected on the server whose value is initialized to 100.

8.

What are the ways in which client can create object on server in CAO model?

There are two ways by which you can create Client objects on remoting server :

Activator.CreateInstance()

By Keyword "New".

9.

Are CAO stateful in nature?

Yes. In CAO remoting model client creates a instance on server and instance variable

10.

set by client on server can be retrieved again with correct value.

In CAO model for client objects to be created by "New" keyword what should we do?

Remoting Clients and Remoting Server can communicate because they share a common contract by implementing Shared Interface or Base Class (As seen in previous examples). But according to OOP‘s concept we can not create a object of interface or Base Classes (Abstract Class). Shipping the server object to client is not a good design practice. In CAO model we can use SOAPSUDS utility to generate

Metadata DLL from server which can be shipped to client, clients can then use this

DLL for creating object on server. Run the SOAPSUDS utility from visual studio command prompt for syntax see below : soapsuds -ia:RemotingServer -nowp -oa:ClientMetaData.dll

Where RemotingServer is your server class name.

ClientMetaData.dll is the DLL name by which you will want to create the metadll.

Server code will change as follows:

ChannelServices.RegisterChannel(objHttpChannel)

RemotingConfiguration.ApplicationName = "RemoteObject"

RemotingConfiguration.RegisterActivatedServiceType(GetType(InterFaceRemoting.Int

erFaceRemoting))

So we have to provide ApplicationName and register the object as

ActivatedServiceType.

On client side we have to reference the generated ClientMetaData.dll from SOAPSUDS utility. Below are changes which are needed to be incorporated at the Remoting

Client:

RemotingConfiguration.RegisterActivatedClientType(typeof(RemoteObject),"http:// localhost:1234/MyServer")

Dim objRemoteObject as new RemoteObject()

RemoteObject is class which is obtained from ClientMetaData.dll which we created using SOAPSUDS utility. Now you can reference the object as normal object.

11.

Is it a good design practice to distribute the implementation to Remoting

Client?

It‘s never advisable to distribute complete implementation at client, due to following reasons:

Any one can use ILDASM or similar utility and get access to your code.

It‘s a bad architecture move to have full implementation as client side as any changes in implementation on server side you have to redistribute it again.

12.

So the best way is to have a interface or SOAPSUDS generated meta-data DLL at client side rather than having full implementation.

What are LeaseTime, SponsorshipTime, RenewonCallTime and

LeaseManagerPollTime?

In normal .NET environment objects lifetime is managed by garbage collector. But in remoting environment remote clients can access objects which are out of control of garbage collector. Garbage collector boundary is limited to a single PC on which framework is running; any remote client across physical PC is out of control of GC

(Garbage Collector).

This constraint of garbage collector leads to a new way of handling lifetime for remoting objects, by using concept called as "LeaseTime". Every server side object is assigned by default a &qout;LeaseTime" of five minutes. This leasetime is decreased at certain intervals. Again for every method call a default of two minutes is assigned.

When i say method call means every call made from client. This is called as

"RenewalOnCallTime".

Let‘s put the whole thing in equation to make the concept more clear.

Total Remoting object life time = LeaseTime + (Number of method calls) X

(RenewalTime).

If we take NumberOfMethodCalls as one.

Then default Remote Object Life Time = 5 + (1) X 2 = 10 minutes (Everything is in minutes)

When total object lifetime is reduced to zero, it queries the sponsor that should the object be destroyed. Sponsor is an object which decides should object Lifetime be renewed. So it queries any registered sponsors with the object, if does not find any then the object is marked for garbage collection. After this garbage collection has whole control on the object lifetime. If we do not foresee how long a object will be needed specify the "SponsorShipTimeOut" value. SponsorShipTimeOut is time unit a call to a sponsor is timed out. "LeaseManagerPollTime" defines the time the sponsor has to return a lease time extension.

13.

Which config file has all the supported channels/protocol?

Machine.config file has all the supported channels and formatter supported by .NET remoting.Machine.config file can be found at

"C:\WINDOWS\Microsoft.NET\Framework\vXXXXX\CONFIG" path. Find

<system.runtime.remoting> element in the Machine.config file which has the channels and the formatters. Below is a figure shown which can give a clear idea of how the file looks like.

14.

How can you specify remoting parameters using Config files?

Both remoting server and remoting client parameters can be provided through config files. Below is a sample of server config file which provides all remoting parameter values which we where providing through code.

<configuration>

<system.runtime.remoting>

<application name="Server">

<service>

<wellknown mode="SingleCall" type="Server.ClsServer, Server" objectUri="RemoteObject" />

</service>

<channels>

<channel ref="tcp server" port="9000" />

</channels>

</application>

</system.runtime.remoting>

</configuration>

Later this config file can be loaded using the following code.

RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.Applic

ationBase

& "Server.config")

Same way we also have client.config file for loading the client remoting parameters.

<configuration>

<system.runtime.remoting>

<application name="Client">

<client url="tcp://localhost:9000/RemoteObject">

<wellknown type="CommonInterface.Icommon, Icommon" url = "tcp://localhost:9000/Server/RemoteObject"/>

</client>

<channels>

<channel ref="tcp client" />

</channels>

</application>

</system.runtime.remoting>

</configuration> client remoting can then load the configuration file by using :

Dim IobjCommon As CommonInterFace.Icommon

Dim StrData As String

Dim objServiceEntries As WellKnownClientTypeEntry()

RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.Applic

ationBase

& "Client.config")

objServiceEntries = RemotingConfiguration.GetRegisteredWellKnownClientTypes()

IobjCommon = Activator.GetObject(GetType(Icommon), objServiceEntries(0).ObjectUrl.ToString())

StrData = IobjCommon.GetValue()

Console.WriteLine(" Serve side Data is " & StrData)

Console.ReadLine()

15.

Can Non-Default constructors be used with Single Call SAO?

Non-Default constructors cannot be used with single call objects as object is created with every method call, there is no way to define Non-default constructors in method calls. It‘s possible to use Non-Default constructor with Client activated objects as both methods "NEW" keyword and "Activator.CreateInstance" provide a way to specify

Non-Default constructors.

16.

How can we call methods in remoting Asynchronously?

We can make Asynchronous method calls by using delegates.

17.

What is Asynchronous One-Way Calls?

One-way calls are a different from asynchronous calls from execution angle that the

.NET Framework does not guarantee their execution. In addition, the methods used in this kind of call cannot have return values or out parameters. One-way calls are defined by using [OneWay()] attribute in class.

18.

What is marshalling and what are different kinds of marshalling?

Marshaling is used when an object is converted so that it can be sent across the network or across application domains. Unmarshaling creates an object from the marshaled data. There are two ways to do marshalling:

 Marshal-by-value (MBV) : In this the object is serialized into the channel, and a copy of the object is created on the other side of the network. The object to marshal is stored into a stream, and the stream is used to build a copy of the object on the other side with the unmarshalling sequence.

 Marshaling-by-reference (MBR) : Here it creates a proxy on the client that is used to communicate with the remote object. The marshaling sequence of a remote object creates an ObjRef instance that itself can be serialized across the network.

19.

What is ObjRef object in remoting?

All Marshal() methods return ObjRef object.The ObjRef is serializable because it implements the interface ISerializable, and can be marshaled by value. The ObjRef knows about location of the remote object, host name, port number and object name.

20.

What is a Web Service?

Web Services are business logic components which provide functionality via the

Internet using standard protocols such as HTTP. Web Services uses Simple Object

Access Protocol (SOAP) in order to expose the business functionality.SOAP defines a standardized format in XML which can be exchanged between two entities over standard protocols such as HTTP. SOAP is platform independent so the consumer of a

Web Service is therefore completely shielded from any implementation details about the platform exposing the Web Service. For the consumer it is simply a black box of send and receive XML over HTTP. So any web service hosted on Windows can also be consumed by UNIX and LINUX platform.

21.

What is UDDI?

Full form of UDDI is Universal Description, Discovery and Integration. It is a directory that can be used to publish and discover public Web Services. If you want to see more details you can visit the http://www.UDDI.org .

22.

What is DISCO?

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

23.

common services together on a server and provides links to the schema documents of the services it describes may require.

What is WSDL?

Web Service Description Language (WSDL)is a W3C specification which defines XML grammar for describing Web Services.XML grammar describes details such as where we can find the Web Service (its URI), what are the methods and properties that service supports, data type support and supported protocols.

Clients can consume this WSDL and build proxy objects that clients use to communicate with the Web Services. Full WSDL specification is available at http://www.w3.org/TR/wsdl .

24.

What the different phase/steps of acquiring a proxy object in Webservice?

Following are the different steps needed to get a proxy object of a webservice at the client side :

 Client communicates to UDDI node for webservice either through browser or

UDDI‘s public web service.

UDDI node responds with a list of webservices.

Every service listed by webservice has a URI pointing to DISCO or WSDL document.

After parsing the DISCO document, we follow the URI for the WSDL document related to the webservice which we need.

 Client then parses the WSDL document and builds a proxy object which can communicate with Webservice./li>

25.

What is file extension of Webservices?

.ASMX is extension for Webservices.

26.

Which attribute is used in order that the method can be used as

WebService?

WebMethod attribute has to be specified in order that the method and property can be treated as WebService.

27.

What are the steps to create a webservice and consume it?

In Visual Studio you can create a new project using "Asp.NET Web Service" template or just create asmx-file using any text editor. After webservice is implemented, you need either add a webreference to it in Visual Studio, or to create a proxy for the client manually using wsdl.exe utility and build a client program using created proxy class, so that using it client can consume the webservice

28.

Do webservice have state?

No.

29.

How can we maintain State in Webservices ?

Webservices as such do not have any mechanism by which they can maintain state.

Webservices can access ASP.NET intrinsic objects like Session, application and so on if they inherit from "WebService" base class.

<%@ Webservice class="TestWebServiceClass" %>

Imports System.Web.Services

Public class TestWebServiceClass

Inherits WebService

<WebMethod> Public Sub SetSession(value As String) session("Val") = Value

End Sub

...

'End Class

Chapter 5: Caching Concepts

1.

What is the difference between Cache object and Application object?

The main difference between the Cache and Application objects is that the Cache object provides cache-specific features, such as dependencies and expiration policies.

2.

How to get access to Cache object ?

The Cache object is defined in the System.Web.Caching namespace. You can get a reference to the Cache object by using the Cache property of the HttpContext class in the System.Web namespace or by using the Cache property of the Page object.

3.

What are dependencies in cache and types of dependencies?

When you add an item to the cache, you can define dependency relationships that can force that item to be removed from the cache under specific activities of dependencies. Example if the cache object is dependent on file and when the file data changes you want the cache object to be update. Following are the supported

4.

dependency :

 File dependency: Allows you to invalidate a specific cache item when a disk

 based file or files change.

Time-based expiration: Allows you to invalidate a specific cache item depending on predefined time.

 Key dependency: Allows you to invalidate a specific cache item depending when another cached item changes.

Can you show a simple code showing file dependency in cache?

Partial Class Default_aspx

Public Sub displayAnnouncement()

Dim announcement As String

If Cache("announcement") Is Nothing Then

Dim file As New _

System.IO.StreamReader _

(Server.MapPath("announcement.txt")) announcement = file.ReadToEnd file.Close()

Dim depends As New _

System.Web.Caching.CacheDependency _

(Server.MapPath("announcement.txt"))

Cache.Insert("announcement", announcement, depends)

End If

Response.Write(CType(Cache("announcement"), String))

End Sub

Private Sub Page_Init(ByVal sender As Object, ByVal e As

System.EventArgs) Handles Me.Init displayAnnouncement()

End Sub

End Class

Above given method displayAnnouncement() displays banner text from

Announcement.txt file which is lying in application path of the web directory. Above method first checks whether the Cache object is nothing, if the cache object is nothing then it moves further to load the cache data from the file. Whenever the file data changes the cache object is removed and set to nothing.

5.

What is Cache Callback in Cache?

Cache object is dependent on its dependencies example file based, time based etc…Cache items remove the object when cache dependencies change.ASP.NET provides capability to execute a callback method when that item is removed from cache.

6.

What is scavenging?

When server running your ASP.NET application runs low on memory resources, items are removed from cache depending on cache item priority. Cache item priority is set when you add item to cache. By setting the cache item priority controls the items scavenging are removed first.

7.

What are different types of caching using cache object of ASP.NET?

You can use two types of output caching to cache information that is to be transmitted to and displayed in a Web browser:

 Page Output Caching Page output caching adds the response of page to cache object. Later when page is requested page is displayed from cache rather

 than creating the page object and displaying it. Page output caching is good if the site is fairly static.

Page Fragment Caching If parts of the page are changing, you can wrap the static sections as user controls and cache the user controls using page fragment caching.

8.

How can you cache different version of same page using ASP.NET Cache object ?

Output cache functionality is achieved by using "OutputCache" attribute on ASP.NET page header. Below is the syntax:

<%@ OutputCache Duration="20" Location="Server" VaryByParam="state"

VaryByCustom="minorversion" VaryByHeader="Accept-Language"%>

 VaryByParam: Caches different version depending on input parameters send

 through HTTP POST/GET.

VaryByHeader: Caches different version depending on the contents of the page header.

VaryByCustom: Lets you customize the way the cache handles page variations by declaring the attribute and overriding the GetVaryByCustomString handler.

VaryByControl: Caches different versions of a user control based on the value of properties of objects in the control.

How will implement Page Fragment Caching?

9.

Page fragment caching involves the caching of a fragment of the page, rather than the entire page. When portions of the page are need to be dynamically created for each user request this is best method as compared to page caching. You can wrap Web

Forms user control and cache the control so that these portions of the page don‘t need to be recreated each time.

10.

Can you compare ASP.NET sessions with classic ASP?

ASP.NET session caches per user session state. It basically uses "HttpSessionState" class. Following are the limitations in classic ASP sessions:

 ASP session state is dependent on IIS process very heavily. So if IIS restarts

ASP session variables are also recycled. ASP.NET session can be independent of the hosting environment thus ASP.NET session can maintained even if IIS

 reboots.

ASP session state has no inherent solution to work with Web Farms.ASP.NET session can be stored in state server and SQL SERVER which can support multiple server.

ASP session only functions when browser supports cookies. ASP.NET session can be used with browser side cookies or independent of it.

11.

Which various modes of storing ASP.NET session?

 InProc: In this mode Session state is stored in the memory space of worker process. This is the default setting. If the IIS reboots or web application restarts

 then session state is lost.

StateServer: In this mode Session state is serialized and stored in a separate process (Aspnet_state.exe); therefore, the state can be stored on a separate computer(a state server).

SQL Server: In this mode Session state is serialized and stored in a SQL

Server database.

Session state can be specified in <sessionState> element of application configuration file. Using State Server and SQL SERVER session state can be shared across web farms but note this comes at speed cost as ASP.NET needs to serialize and deserialize data over network again and again.

12.

Is Session_End event supported in all session modes?

Session_End event occurs only in "Inproc mode"."State Server" and "SQL SERVER" do not have Session_End event.

13.

What are the precautions you will take in order that StateServer Mode work properly?

 StateServer mode session data is stored in a different process so you must

 ensure that your objects are serializable.

<machineKey> elements in Web.config should be identical across all servers.So this ensures that encryption format is same across all computers.

IIS metabase (\LM\W3SVC\2) must be identical across all servers in that farm.

14.

What are the precautions you will take in order that SQL Server Mode work properly?

SQL Servermode session data is stored in a different process so you must ensure that your objects are serializable.

IIS metabase (\LM\W3SVC\2) must be identical across all servers in that farm.

By default Session objects are stored in "TempDB", you can configure it store outside "TempDB" by running Microsoft provided SQL script. "TempDB" database is re-created after SQL SERVER computer reboot. If you want to maintain session state with every reboot best is to run SQL Script and store session objects outside "TempDB" database.

15.

Where do you specify session state mode in ASP.NET?

<sessionState mode="SQLServer" stateConnectionString="tcpip=192.168.1.1:42424" sqlConnectionString="data source=192.168.1.1; Integrated

Security=SSPI" cookieless="false" timeout="20"

/>

16.

What are the other ways you can maintain state?

17.

Other than session variables you can use hidden fields, ViewState, hidden frames, cookies, query strings.

What are benefits and limitations of using Hidden fields?

Benefits of using Hidden fields: they are simple to implement, as data is cached on client side they work with Web Farms, all browsers support hidden field, no server resources are required.

Limitations: they can be tampered creating a security hole, page performance decreases if you store large data, as the data are stored in pages itself, hidden fields do not support rich structures as HTML hidden fields are only single valued. Then you have to work around with delimiters etc to handle complex structures

Below is how you will actually implement hidden field in a project

<input id="HiddenValue" type="hidden" value="Initial Value" runat="server" name="HiddenValue">

18.

What is ViewState?

Viewstate is a built-in structure for automatically retaining values amongst the multiple requests for the same page. The viewstate is internally maintained as a hidden field on the page but is hashed, providing greater security than developerimplemented hidden fields do.

19.

Does the performance for ViewState vary according to User controls?

Performance of ViewState varies depending on the type of server control to which it is applied. Label, TextBox, CheckBox, RadioButton, and HyperLink are server controls that perform well with ViewState. DropDownList, ListBox, DataGrid, and DataList suffer from poor performance because of their size and the large amounts of data making roundtrips to the server.

20.

What are benefits and limitations of using Viewstate for state management?

Benefits: no server resources are required because state is in a structure in the page code, simplicity, states are retained automatically, the values in view state are hashed, compressed, and encoded, thus representing a higher state of security than hidden fields, ViewState is good for caching data in Web frame configurations because the data is cached on the client.

Limitations: page loading and posting performance decreases when large values are stored because view state is stored in the page, although view state stores data in a hashed format, it can still be tampered because it is stored in a hidden field on the page. The information in the hidden field can also be seen if the page output source is viewed directly, creating a potential security risk.

21.

How can you use Hidden frames to cache client data?

<FRAMESET cols="100%,*,*">

<FRAMESET rows="100%">

<FRAME src="data_of_frame1.html"></FRAMESET>

<FRAME src="data_of_hidden_frame.html">

<FRAME src="data_of_hidden_frame.html" frameborder="0" noresize scrolling="yes">

</FRAMESET>

22.

What are benefits and limitations of using Hidden frames?

Benefits: you can cache more than one data field, the ability to cache and access data items stored in different hidden forms, the ability to access JScript variable values stored in different frames if they come from the same site.

Limitations: hidden frames are not supported on all browsers, hidden frames data can be tampered thus creating security hole.

23.

What are benefits and limitations of using Cookies?

Benefits: no server resources are required as they are stored in client, they are light weight and simple to use.

Limitations: most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in the new browser and client-device versions available today, some users disable their browser or client device‘s ability to receive cookies, thereby limiting the use of cookies, cookies can be tampered and thus creating a security hole, cookies can expire thus leading to inconsistency.

24.

What are benefits and limitations of using Hidden frames?

Benefits: you can cache more than one data field, the ability to cache and access data items stored in different hidden forms, the ability to access JScript variable values stored in different frames if they come from the same site.

Limitations: hidden frames are not supported on all browsers, hidden frames data can be tampered thus creating security hole.

Below is sample code of implementing cookiesRequest.Cookies.Add(New

HttpCookie("name", "user1"))

25.

What is Query String and what are benefits and limitations of using Query

Strings?

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

Benefits: no server resources are required, the query string containing in the HTTP requests for a specific URL, all browsers support query strings.

Limitations: query string data is directly visible to user thus leading to security problems, most browsers and client devices impose a 255-character limit on URL length.

Below is a sample "Login" query string passed in URL http://www.querystring.com/login.aspx?login=testing. This query string data can then be requested later by using Request.QueryString("login").

26.

What is Absolute and Sliding expiration?

Cache.Insert("announcement", announcement, depends, _

DateTime.Now.AddMinutes(1), Nothing)

Sliding Expiration specifies that the cache will expire if a request is not made within a specified duration. Sliding expiration policy is useful whenever you have a large number of items that need to be cached, because this policy enables you to keep only the most frequently accessed items in memory. For example, the following code specifies that the cache will have a sliding duration of one minute. If a request is made 59 seconds after the cache is accessed, the validity of the cache would be reset to another minute:

Cache.Insert("announcement", announcement, depends, _

27.

DateTime.MaxValue, _

TimeSpan.FromMinutes(1))

What is cross page posting?

By default, button controls in ASP.NET pages post back to the same page that contains the button, where you can write an event handler for the post. In most cases this is the desired behavior, but occasionaly you will also want to be able to post to another page in your application. The Server.Transfer method can be used to move between pages, however the URL doesn‘t change. Instead, the cross page posting feature in ASP.NET 2.0 allows you to fire a normal post back to a different page in the application. In the target page, you can then access the values of server controls in the source page that initiated the post back.

To use cross page posting, you can set the PostBackUrl property of a Button,

LinkButton or ImageButton control, which specifies the target page. In the target page, you can then access the PreviousPage property to retrieve values from the source page. By default, the PreviousPage property is of type Page, so you must access controls using the FindControl method. You can also enable strongly-typed access to the source page by setting the @PreviousPageType directive in the target page to the virtual path or Type name of the source page.

Here is a step-by-step guide for implementing the cross-page post back using controls that implement the IButtonControl interface.

 Create a Web Form and insert a Button control on it using the VS .NET

 designer.

Set the button‘s PostBackUrl property to the Web Form you want to post back. For instance in this case it is "nextpage.aspx" <asp:Button ID="Button1" runat="server" PostBackUrl="~/nextpage.aspx" Text="Post to nextpage" />

When the PostBackUrl property of the IButtonControl is set, the ASP.NET framework binds the corresponding HTML element to new JavaScript function named

WebForm_DoPostBackWithOptions. The corresponding HTML rendered by the ASP.NET

2.0 will look like this:

<input type="submit" name="Button1" value="Post to Page 2" onclick="javascript:WebForm_DoPostBackWithOptions(new

WebForm_PostBackOptions("Button1", ",false","Page2.aspx", false, false))" id="Button1" />

28.

How do we access ViewState value of this page in the next page?

View state is page specific; it contains information about controls embedded on the particular page. ASP.NET 2.0 resolves this by embedding a hidden input field name,

__POSTBACK . This field is embedded only when there is an IButtonControl on the page and its PostBackUrl property is set to a non-null value. This field contains the view state information of the poster page. To access the view state of the poster page, you can use the new PreviousPage property of the page:

Page poster = this.PreviousPage;

Then you can find any control from the previous page and read its state:

Label posterLabel = poster.findControl("myLabel"); string lbl = posterLabel.Text;

This cross-page post back feature also solves the problem of posting a Form to multiple pages, because each control, in theory, can point to different post back URL.

29.

Can we post and access ViewState in another application?

You can post back to any page and pages in another application, too. But if you are posting pages to another application, the PreviousPage property will return null. This is a significant restriction, as it means that if you want to use the ViewState, you are confined, for example, posting to pages in the same virtual directory. Even so, this is a highly acceptable addition to the functionality of ASP.NET.

30.

How do we enable SQL Cache Dependency in ASP.NET 2.0?

Below are the steps to enable a SQL Cache Dependency:

 Enable notifications for the database.

Before you can use SQL Server cache invalidation, you need to enable notifications for the database. This task is performed with the aspnet_regsql.exe command-line utility, which is located in the c:\[WinDir]\Microsoft.NET\Framework\[Version] directory. aspnet_regsql -ed -E -d Northwind , where -ed : command-line switch, -E: use trusted connection , -S: specify server name it other than the current computer you are working on, -d: database name.

So now let‘s try to understand what happens in the database because of

"aspnet_regsql.exe". After we execute the "aspnet_regsql -ed -E -d Northwind" command you will see one new table

AspNet_SqlCacheTablesForChangeNotification and four new stored procedures created. Essentially, when a change takes place, a record is written in this table.

The SQL Server polling queries this table for changes.

Here is a brief run of what the stored procedures do.

 AspNet_SqlCacheRegisterTableStoredProcedure: This stored procedure sets a table to support notifications. This process works by adding a notification trigger to the table, which will fire when any row is inserted, deleted, or updated.

AspNet_SqlCacheUnRegisterTableStoredProcedure: This stored procedure takes a registered table and removes the notification trigger so that notifications won‘t be generated.

AspNet_SqlCacheUpdateChangeIdStoredProcedure: The notification trigger calls this stored procedure to update the

AspNet_SqlCacheTablesForChangeNotification table, thereby indicating that the table has changed.

AspNet_SqlCacheQueryRegisteredTablesStoredProcedure: This extracts just the table names from the

AspNet_SqlCacheTablesForChangeNotification table. It‘s used to get a quick look at all the registered tables

AspNet_SqlCachePollingStoredProcedure: This will get the list of changes from the

AspNet_SqlCacheTablesForChangeNotification table. It is used to perform polling.

Enabling notification for individual tables Once the necessary stored procedure and tables are created then we have to notify saying which table needs to be enabled for notifications. That can be achieved by two ways:aspnet_regsql -et -E -d Northwind -t Products or exec spNet_SqlCacheRegisterTableStoredProcedure 'TableName' .

Registering tables for notification internally creates triggerfor the tables. For instance for a "products" table the following trigger is created. So any modifications done to the "Products" table will update the

&quotAspNet_SqlCacheNotification" table.

"AspNet_SqlCacheTablesForChangeNotification" contains a single record for every table you‘re monitoring. When you make a change in the table (such as inserting, deleting or updating a record), the change Id column is incremented

 by 1.ASP.NET queries this table repeatedly keeps track of the most recent changed values for every table. When this value changes in a subsequent read,

ASP.NET knows that the table has changed.

Enable ASP.NET polling using "web.config" file Now that all our database side is configured in order to get the SQL Cache working in the ASP.NET side we need to do some configuration in the web.config file.

We need to set two attributes in the "web.config" file: set "Enabled" attribute to true to set the caching on and set the poll time attribute to the number of milliseconds between each poll.

Finally use the Cache dependency object in your ASP.NET code. Now comes the final step to use our cache dependency with programmatic data caching, a data source control, and output caching. For programmatic data caching, we need to create a new

SqlCacheDependency and supply that to the Cache.Insert() method. In the

SqlCacheDependency constructor, you supply two strings. The first is the name of the database you defined in the element in the section of the web.config file e.g: Northwind. The second is the name of the linked table e.g: Products. private static void CacheProductsList(List<ClsProductItem> products)

{

SqlCacheDependency sqlDependency = new SqlCacheDependency("Northwind",

"Products");

HttpContext.Current.Cache.Insert("ProductsList", products, sqlDependency,

DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);

}

private static List<ClsProductItem> GetCachedProductList()

{ return HttpContext.Current.Cache["ProductsList"] as List<ClsProductItem>;

}

31.

What is Post Cache substitution?

Post cache substitution is used when we want to cache the whole page but also need some dynamic region inside that cached page. Some examples like

QuoteoftheDay,RandomPhotos, and AdRotator etc. are examples where we can implement Post Cache Substitution.

Post-cache substitution can be achieved by two means - call the new

Response.WriteSubstitution method, passing it a reference to the desired substitution method callback or add a <asp:Substitution> control to the page at the desired location, and set its methodName attribute to the name of the callback method.

We pass the response substitution callback to the method. So now when ASP.NET page framework retrieves the cached page, it automatically triggers your callback method to get the dynamic content. It then inserts your content into the cached HTML of the page. Even if your page hasn‘t been cached yet (for example, it‘s being rendered for the first time), ASP.NET still calls your callback in the same way to get the dynamic content. So you create a method that generates some dynamic content, and by doing so you guarantee that your method is always called, and it‘s content is never cached.

In case of using "<asp:substitution>" control we need to provide "methodname" attribute of the substitution control.

32.

Why do we need methods to be static for Post Cache substitution?

ASP.NET should be able to call this method even when there isn‘t an instance of your page class available. When your page is served from the cache, the page object isn‘t created. So ASP.NET skips the page life cycle when the page is coming from cache, which means it won‘t create any control objects or raise any control events. If your dynamic content depends on the values of other controls, you‘ll need to use a different technique, because these control objects won‘t be available to your callback.

Chapter 6: OOPS

1.

What is Object Oriented Programming?

It is a problem solving technique to develop software systems. It is a technique to think real world in terms of objects. Object maps the software model to real world

2.

concept. These objects have responsibilities and provide services to application or other objects.

What is a Class ?

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

3.

What’s an Object?

4.

It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are members of a class. Attributes and behavior of an object are defined by the class definition.

5.

What is the relation between Classes and Objects?

They look very much same but are not same. Class is a definition, while object is a instance of the class created. Class is a blue print while objects are actual objects existing in real world.

6.

What are different properties provided by Object-Oriented systems?

Following are characteristics of Object Oriented Systems:

 Abstraction It allows complex real world to be represented in simplified manner. Example color is abstracted to RGB. By just making the combination of these three colors we can

 achieve any color in world. It‘s a model of real world or concept.

Encapsulation It is a process of hiding all the internal details of an object from the outside world.

Communication using messages When application wants to achieve certain task it can only be done using combination of objects. A single object cannot do all the task. Example if we want to make order processing form. We will use Customer object, Order object, Product object and Payment object to achieve this functionality. In short these objects should communicate with each other. This is achieved when objects send messages to each other.

Object lifetime All objects have life time.Objects are created ,and initialized, necessary functionalities are done and later the object is destroyed. Every object have their own state and identity which differ from instance to instance.

Class hierarchies (Inheritance and aggregation) In object-oriented world objects have relation and hierarchies in between them. There are basically three kind of relationship in Object Oriented world : association - the simplest relationship between objects. example every customer has sales. So Customer

 object and sales object have an association relation between them; aggregation - also called as composition model. example in order to make a "Accounts"class it has use other objects example "Voucher", "Journal" and "Cash" objects. So accounts class is aggregation of these three objects.

Inheritance Hierarchy is used to define more specialized classes based on a preexisting generalized class. Example we have VEHICLE class and we can inherit this class make more specialized class like CAR, which will add new attributes and use some existing qualities of the parent class. Its shows more of a parent-child relationship. This kind of hierarchy is called inheritance.

Polymorphism When inheritance is used to extend a generalized class to a more specialized class, it includes behavior of the top class(Generalized class). The inheriting class often implement a behavior that can be somewhat different than the generalized class, but the name of the behavior can be same. It is important that a given instance of an object use the correct behavior, and the property of polymorphism allows this to happen automatically.

7.

What are abstract classes?

Following are features of a abstract class :

 You cannot create a object of abstract class.

 In VB.NET abstract classes are created using "MustInherit" keyword. In C#

 we have "abstract" keyword.

Abstract classes can have implementation or pure abstract methods which should be implemented in the child class.

8.

Abstract class is designed to act as a base class (to be inherited by other classes). Abstract class is a design concept in program development and provides a base upon which other classes are built.

Abstract classes are similar to interfaces. After declaring an abstract class, it cannot be instantiated on its own, it must be inherited.

What is a Interface?

Interface is a contract that defines the signature of the functionality. So if a class is implementing a interface it says to the outer world, that it provides specific behavior.

Example if a class is implementing IDisposable interface that means it has a functionality to release unmanaged resources. Now external objects using this class know that it has contract by which it can dispose unused unmanaged objects.

Single Class can implement multiple interfaces. If a class implements a interface then it has to provide implementation to all its methods.

9.

What is difference between abstract classes and interfaces?

Abstract classes can have concrete methods while interfaces have no methods

10.

implemented. Interfaces do not come in inheriting chain, while abstract classes come in inheritance.

What is a delegate?

Delegate is a class that can hold a reference to a method or a function. Delegate class has a signature and it can only reference those methods whose signature is compliant with the class. Delegates are type-safe functions pointers or callbacks.

Public Class FrmDelegates

Inherits System.Windows.Forms.Form

Public Delegate Sub DelegateAddString()

Private Sub FrmDelegates_Load(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles MyBase.Load

End Sub

Private Sub AddString() lstDelegates.Items.Add("Running AddString() method")

End Sub

Private Sub cmdDelegates_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles cmdDelegates. Click

Dim objDelegateAddString As DelegateAddString objDelegateAddString = AddressOf AddString objDelegateAddString.Invoke()

End Sub

End Class

11.

What are events?

As compared to delegates events works with source and listener methodology. So listeners who are interested in receiving some events they subscribe to the source.

Once this subscription is done the source raises events to its entire listener when needed. One source can have multiple listeners.

In sample given below class "ClsWithEvents" is a event source class, which has a event "EventAddString()". Now the listeners who are interested in receiving this

events they can subscribe to this event. In class "FrmWithEvents" you can see they handle clause which is associated with the "mobjClsWithEvents" objects.

Public Class ClsWithEvents

Event EventAddString(ByVal Value As String)

Public Sub AddString()

RaiseEvent EventAddString("String added by Event")

End Sub

End Class

Public Class FrmWithEvents

Inherits System.Windows.Forms.Form

Private WithEvents mobjClsWithEvents As New ClsWithEvents()

Private Sub FrmWithEvents_Load(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles MyBase.Load

End Sub

Private Sub mobjClsWithEvents_EventAddString(ByVal Value As String) Handles mobjClsWithEvents.EventAddString

LstData.Items.Add(Value)

End Sub

Private Sub CmdRunEvents_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles CmdRunEvents.Click mobjClsWithEvents.AddString()

End Sub

End Class

12.

Do events have return type?

No, events do not have return type.

13.

Can events have access modifiers?

Events are always public as they are meant to serve every one register ing to it. But you can access modifiers in events.You can have events with protected keyword which

14.

will be accessible only to inherited classes.You can have private events only for object in that class.

Can we have shared events?

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

15.

What is shadowing?

When two elements in a program have same name, one of them can hide and shadow

16.

the other one. So in such cases the element which shadowed the main element is referenced.

What is the difference between Shadowing and Overriding?

Following are the differences between shadowing and overriding:

 Overriding redefines only the implementation while shadowing redefines the

 whole element.

In overriding derived classes can refer the parent class element by using "Me"

("this" in C#) keyword, but in shadowing you can access it by "MyBase" ("base" in C#).

17.

What is the difference between delegate and events?

 Actually events use delegates in bottom. But they add an extra layer on the

 delegates, thus forming the publisher and subscriber model.

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

18.

If we inherit a class do the private variables also get inherited?

Yes, the variables are inherited but cannot be accessed directly by the class interface.

19.

What are the different accessibility levels defined in .NET?

Following are the five levels of access modifiers :

 Private: Only members of class have access.

Protected : All members in current class and in derived classes can access the variables.

Friend (internal in C#): Only members in current project have access to the

 elements.

Protected friend (protected internal in C#): All members in current project and all members in derived class can access the variables.

Public : All members have access in all classes and projects.

20.

Can you prevent a class from overriding?

If you define a class as "Sealed" in C# and "NotInheritable" in VB.NET you cannot inherit the class any further.

21.

What is the use of "MustInherit" keyword in VB.NET ?

If you want to create a abstract class in VB.NET it‘s done by using "MustInherit" keyword. You cannot create an object of a class which is marked as "MustInherit".

When you define "MustInherit" keyword for class you can only use the class by inheriting.

22.

Do interface have accessibility modifier?

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

23.

What are similarities between Class and structure?

Following are the similarities between classes and structures :

Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.

Structures and classes can implement interface.

Both of them can have constructors with and without parameter. 

 Both can have delegates and events.

24.

What are differences between Class and structure?

Following are the key differences between classes and structures :

 Structure are value types and classes are reference types. So structures use stack and classes use heap.

Structures members cannot be declared as protected, but class members can be. You cannot do inheritance in structures.

Structures do not require constructors while classes require.

 Objects created from classes are terminated using Garbage collector.

Structures are not destroyed using GC.

25.

What does virtual keyword mean?

It signifies that method and property can be overridden.

26.

What are shared (VB.NET)/static(C#) classes?

Static/Shared classes are used when a class provides functionality which is not specific to any instance. In short if you want an object to be shared between multiple instances you will use a static/Shared class. Following are features of Static/Shared classes :

 They cannot be instantiated. By default a object is created on the first method

 call to that object.

Static/Shared classes cannot be inherited.

Static/Shared classes can have only static members.

Static/Shared classes can have only static constructor.

Below is a snippet. It has a "AddCount" function which increments a static "intCount" variable. In form there are two buttons which creates a new object and displays the count of the static variable. Even though the object is created and destroyed, the variable values does not change. It retains its old value.

Public Class ClsShared

Shared intCount As Integer

Public Function AddCount() As Integer intCount = intCount + 1

Return intCount

End Function

End Class

Public Class FrmSharedClasses

Inherits System.Windows.Forms.Form

Private Sub CmdInstance1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdInstance1.Click

Dim pobjClsShared As New ClsShared()

MessageBox.Show("The count at this moment is" & pobjClsShared.AddCount.ToString())

End Sub

Private Sub CmdInstance2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdInstance2.Click

Dim pobjClsShared As New ClsShared()

MessageBox.Show("The count at this moment is" & pobjClsShared.AddCount.ToString())

End Sub

27.

End Class

What is Dispose method in .NET?

.NET provides "Finalize" method in which we can clean up our resources. But relying on this is not always good so the best is to implement "Idisposable" interface and implement the "Dispose" method where you can put your clean up routines.

28.

What is the use of "Overrides" and "Overridable" keywords ?

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

Overrides is used in the child class to indicate that you are overriding a method.

29.

Where are all .NET Collection classes located?

System.Collection namespace has all the collection classes available in .NET.

30.

What is ArrayList?

Array is whose size can increase and decrease dynamically. Array list can hold item of different types. As Array list can increase and decrease size dynamically you do not have to use the ReDim (in VB.Net) keyword. You can access any item in array using the Index value of the array position.

31.

What is a HashTable?

You can access array using index value of array, but only if you know the real value of index. Hashtable provides way of accessing the index using a user identified key

32.

value, thus removing the index problem.

What are queues and stacks?

Queue is for first-in, first-out (FIFO) structures. Stack is for last-in, first-out (LIFO) structures.

33.

What is enum?

The enum keyword is used when you require a enumeration. A enumeration is a distinct type that consists of a set of named constants called the enumetor list. Every enumeration type has an underlying type which can be all integral times except that of a char type.

34.

What is nested Classes?

Nested classes are classes within classes. In sample below "ClsNested" class has a

"ChildNested" class nested inside it.

Public Class ClsNested

Public Class ChildNested

Public Sub ShowMessage()

MessageBox.Show(―Hi this is nested class‖)

End Sub

End Class

End Class

This is the way we can instantiate the nested class and make the method call.

35.

Dim pobjChildNested As New ClsNested.ChildNested() pobjChildNested.ShowMessage()

What is Operator Overloading in .NET?

It provides a way to define and use operators such as +, -, and / or user-defined classes or structs. It allows us to define/redefine the way operators work with our classes and structs. This allows programmers to make their custom types look and feel like simple types such as int and string. VB.NET supports operator overloading since VB.Net 2005. Operator overloading is done by using the "Operator" keyword.

36.

What is the significance of Finalize method in .NET?

.NET Garbage collector does almost all clean up activity for your objects. But unmanaged resources (ex: - Windows API created objects, File, Database connection objects, COM objects etc) is outside the scope of .NET framework we have to explicitly clean our resources. For these types of objects .NET framework provides Object.

Finalize method which can be overridden and clean up code for unmanaged resources can be put in this section.

37.

Why is it preferred to not use finalize for clean up?

Problem with finalize is that garbage collection has to make two rounds in order to remove objects which have finalize methods.

Below figure will make things clear regarding the two rounds of garbage collection rounds performed for the objects having finalized methods.

Below figure will make things clear regarding the two rounds of garbage collection rounds performed for the objects having finalized methods.

In this scenario there are three objects Object1, Object2 and Object3. Object2 has the finalize method overridden and remaining objects do not have the finalize method overridden.

Now when garbage collector runs for the first time it searches for objects whose memory has to free. He can see three objects but only cleans the memory for Object1 and Object3. Object2 it pushes to the finalization queue.

Now garbage collector runs for the second time. He see‘s there are no objects to be released and then checks for the finalization queue and at this moment it clears object2 from the memory

So if you notice that object2 was released from memory in the second round and not first. That‘s why the best practice is not to write clean up Non.NET resources in

Finalize method rather use the Dispose.

38.

How can we suppress a finalize method?

GC.SuppressFinalize ()

39.

What is the use of Dispose() method?

Dispose method belongs to IDisposable interface. We had seen in the previous section how bad it can be to override the finalize method for writing the cleaning of unmanaged resources. So if any object wants to release its unmanaged code best is to implement. IDisposable and override the Dispose method of IDisposable interface.

Now once your class has exposed the Dispose method it‘s the responsibility of the client to call the Dispose method to do the cleanup.

40.

How do I force the Dispose method to be called automatically, as clients can forget to call Dispose method?

Call the Dispose method in Finalize method and in Dispose method suppress the finalize method using GC.SuppressFinalize. Below is the sample code of the pattern.

This is the best way we do clean our unallocated resources and yes not to forget we do not get the hit of running the Garbage collector twice.

Public Class ClsTesting

Implements IDisposable

Public Overloads Sub Dispose()Implements IDisposable.Dispose

' write your clean up code here

GC.SuppressFinalize(Me)

End Sub

Protected Overrides Sub Finalize()

Dispose()

End Sub

End Class

41.

In what instances you will declare a constructor to be private?

When we create a private constructor, we cannot create object of the class directly from a client. So you will use private constructors when you do not want instances of the class to be created by any external client. Example utility functions in project will have no instance and be used without creating instance, as creating instances of the class would be waste of memory.

42.

Can we have different access modifiers on get/set methods of a property?

No we cannot have different modifiers for the same property. The access modifier on a property applies to both its get and set accessors.

43.

If we write a goto or a return statement in try and catch block will the finally block execute ?

The code in then finally always run even if there are statements like goto or a return statements.

44.

What is Indexer?

45.

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

Can we have static indexer in C#?

No.

46.

Can two catch blocks be executed?

No, once the proper catch section is executed the control goes finally to block. So there will not be any scenarios in which multiple catch blocks will be executed.

47.

What is the difference between System.String and System.StringBuilder classes?

1.

System.String is immutable; System.StringBuilder can have mutable string where a variety of operations can be performed.

Chapter 7: ASP.NET

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

Following is the sequence in which the events occur (extremely simplified version, for more detailed description see another post ):

 Page_Init.

Page_Load.

Control events.

 Page_Unload event.

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

2.

In which event are the controls fully loaded ?

Page_Load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that viewstate is not fully loaded during this event

3.

How can we identify that the Page is PostBack?

Page object has a "IsPostBack" property which can be checked to know that is the page posted back.

4.

How does ASP.NET maintain state in between subsequent request?

5.

What is event bubbling?

Server controls like Datagrid, DataList, Repeater can have other child controls inside them. Example DataGrid can have combo box inside datagrid. These child controls do not raise their events by themselves, rather they pass the event to the container parent (which can be a DataGrid, DataList, Repeater), which passed to the page as

"Item Command" event. As the child control send their events to parent this is termed as event bubbling.

How do we assign page specific attributes?

6.

Page attributes are specified using the @Page directive.

7.

If we want to make sure that no one has tampered with ViewState, how do we ensure it?

Set the @Page directive EnableViewStateMac to True.

8.

What is the use of @Register directives?

@Register directive informs the compiler of any custom server control added to the page.

9.

What is SmartNavigation property?

It‘s a feature provided by ASP.NET to prevent flickering and redrawing when the page is posted back. It is supported by Internet Explorer only.

10.

What is AppSetting Section in "Web.Config" file ?

Web.config file defines configuration for a webproject. Using "AppSetting" section we can define user defined values. For Example we can define "ConnectionString" section which will be used throughout the project for database connection.

<configuration>

<appSettings>

11.

<add key="ConnectionString" value="server=xyz;pwd=www;database=testing" />

</appSettings>

Where is ViewState information stored?

In HTML Hidden Fields.

12.

What is the use of @OutputCache directive in ASP.NET?

It is basically used for caching.

13.

How can we create custom controls in ASP.NET ?

User controls in ASP.NET are created using .ASCX files. After .ASCX file is created you need to two things in order that the ASCX can be used in project:

Register the ASCX control in page using the <%@ Register directive. Example

<%@ Register tagprefix="Accounting" Tagname="footer" Src="Footer.ascx"

%>

Now to use the above accounting footer in page you can use the below directive. <Accounting:footer runat="server" />

14.

What types of validation controls are provided by ASP.NET?

There are six main types of validation controls:

 RequiredFieldValidator - It checks whether the control have any value. It‘s

 used when you want the control should not be empty.

RangeValidator - It checks if the value in validated control is in that specific

 range. Example txtCustomerCode should not be more than eight length.

CompareValidator - It checks that the value in controls should match some specific value. Example Textbox TxtPi should be equal to 3.14.

RegularExpressionValidator - When we want the control value should

 match with a specific regular expression.

CustomValidator - It is used to define user-defined validation.

 ValidationSummary - It displays summary of all current validation errors.

15.

What is "AutoPostBack" feature in ASP.NET ?

If we want the control to automatically postback in case of any event, we will need to check this attribute as true. Example on a ComboBox change we need to send the event immediately to the server side then set the "AutoPostBack " attribute to true.

16.

How can you enable automatic paging in DataGrid?

In order to enable paging in Datagrid you need to (very short version):

 Set the "AllowPaging" property to true.

 In PageIndexChanged event handler set the current PageIndex clicked.

Below is an example in C#:

//Declaring DataGrid protected System.Web.UI.WebControls.DataGrid DataGrid1;

//Binding DataGrid with a Data Source (DataSet in our Case)

DataGrid1.DataSource = dataSet1;

DataGrid1.DataBind(); this.DataGrid1.PageIndexChanged += new

System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.GridPageI

ndexChanged);

//Implement the EventHandler private void GridPageIndexChanged(object source,

System.Web.UI.WebControls.DataGridPageChangedEventArgs e)

{

}

DataGrid1.CurrentPageIndex = e.NewPageIndex;

//Bind the DataGrid again with the Data Source

DataGrid1.DataSource = dataSet1;

DataGrid1.DataBind();

17.

What is the use of "GLOBAL.ASAX" file ?

It allows to handle ASP.NET application level events and setting application-level variables.

18.

What is the difference between "Web.config" and "Machine.Config" ?

"Web.config" files apply settings to each web application, while "Machine.config" file apply settings to all ASP.NET applications.

19.

What are SESSION and APPLICATION objects?

In short, Session object stores information between HTTP requests for a particular user, while Application object is global across users.

20.

What is the difference between Server.Transfer and Response.Redirect ?

Following are the major differences between them:

 Response.Redirect sends message to the browser saying it to move to some different page, while Server.Transfer does not send any message to the browser but rather redirects the user directly from the server itself. So in Server.Transfer

21.

 there is no round trip while Response.Redirect has a round trip and hence puts a load on server.

Using Server.Transfer you cannot redirect to a different from the server itself.

This cross server redirect is possible only using Response.Redirect.

With Server.Transfer you can preserve your information. It has a parameter called as "preserveForm". So the existing query string etc. will be able in the calling page.

What is the difference between authentication and authorization?

Authentication is verifying the identity of a user and authorization is process where we check does this identity have access rights to the system. In short we can say the following authentication is the process of obtaining some sort of credentials.from the users and using those credentials to verify the user‘s identity. Authorization is the process of allowing an authenticated user access to resources. Authentication always proceed to Authorization; even if your application lets anonymous users connect and use the application, it still authenticates them as being anonymous.

22.

What is impersonation in ASP.NET?

By default, ASP.NET executes in the security context of a restricted user account on the local machine. Sometimes you need to access network resources such as a file on a shared drive, which requires additional permissions. One way to overcome this restriction is to use impersonation. With impersonation, ASP.NET can execute the request using the identity of the client who is making the request, or ASP.NET can impersonate a specific account you specify in web.config.

23.

Explain in brief how the ASP.NET authentication process works.

ASP.NET does not run by itself, it runs inside the process of IIS. So there are two authentication layers which exist in ASP.NET system. First authentication happens at the IIS level and then at the ASP.NET level depending on the WEB.CONFIG file :

 IIS first checks to make sure the incoming request comes from an IP address that is allowed access to the domain. If not it denies the request.

 Next IIS performs its own user authentication if it is configured to do so. By default IIS allows anonymous access, so requests are automatically

 authenticated, but you can change this default on a per – application basis with in IIS.

If the request is passed to ASP.Net with an authenticated user, ASP.Net checks to see whether impersonation is enabled. If impersonation is enabled,

ASP.Net acts as though it were the authenticated user. If not ASP.Net acts with its own configured account.

Finally the identity from step 3 is used to request resources from the operating system. If ASP.net authentication can obtain all the necessary resources it grants the users request otherwise it is denied. Resources can include much more than just the ASP.net page itself you can also use .Net‘s code access security features to extend this authorization step to disk files, registry keys and other resources.

24.

What are the various ways of authentication techniques in ASP.NET?

Selecting an authentication provider is as simple as making an entry in the web.config file for the application. You can use one of these entries to select the corresponding built in authentication provider:

<authentication mode="windows">

<authentication mode="passport">

<authentication mode="forms">

Custom authentication where you might install an ISAPI filter in IIS that compares incoming requests to list of source IP addresses, and considers requests to be authenticated if they come from an acceptable address. In that case, you would set the authentication mode to none to prevent any of the .Net authentication providers from being triggered.

Windows authentication and IIS

If you select windows authentication for your ASP.NET application, you also have to configure authentication within IIS. This is because IIS provides Windows authentication. IIS gives you a choice for four different authentication methods: anonymous,basic,digest and windows integrated.

If you select anonymous authentication, IIS doesn‘t perform any authentication, Any one is allowed to access the ASP.NET application.

If you select basic authentication, users must provide a windows username and password to connect. However this information is sent over the network in clear text, which makes basic authentication very much insecure over the internet.

If you select digest authentication, users must still provide a windows user name and password to connect. However the password is hashed before it is sent across the network. Digest authentication requires that all users be running Internet Explorer 5 or later and that windows accounts to stored in active directory.

If you select windows integrated authentication, passwords never cross the network.Users must still have a username and password, but the application uses either the Kerberos or challenge/response protocols authenticate the user. Windowsintegrated authentication requires that all users be running Internet Explorer 3.01 or later Kerberos is a network authentication protocol. It is designed to provide strong authentication for client/server applications by using secret-key cryptography. Kerberos is a solution to network security problems. It provides the tools of authentication and strong cryptography over the network to help to secure information in systems across entire enterprise.

Passport authentication

Passport authentication lets you to use Microsoft‘s passport service to authenticate users of your application. If your users have signed up with passport, and you configure the authentication mode of the application to the passport authentication, all authentication duties are off-loaded to the passport servers.

Passport uses an encrypted cookie mechanism to indicate authenticated users. If users have already signed into passport when they visit your site, they‘ll be considered authenticated by ASP.NET. Otherwise they‘ll be redirected to the passport servers to log in. When they are successfully log in, they‘ll be redirected back to your site

To use passport authentication you have to download the Passport Software

Development Kit (SDK) and install it on your server. The SDK can be found at

Microsoft website. It includes full details of implementing passport authentication in your own applications.

Forms authentication

Forms authentication provides you with a way to handle authentication using your own custom logic with in an ASP.NET application. The following applies if you choose forms authentication.

When a user requests a page for the application, ASP.NET checks for the presence of a special session cookie. If the cookie is present, ASP.NET assumes the user is authenticated and processes the request.

If the cookie isn‘t present, ASP.NET redirects the user to a web form you provide.

You can carry out whatever authentication, it check‘s you like it checks your form.

25.

When the user is authenticated, you indicate this to ASP.NET by setting a property, which creates the special cookie to handle subsequent requests.

How does authorization work in ASP.NET?

ASP.NET impersonation is controlled by entries in the applications web.config file. The default setting is "no impersonation". You can explicitly specify that ASP.NET shouldn‘t use impersonation by including the following code in the file

<identity impersonate="false"/>

It means that ASP.NET will not perform any authentication and runs with its own privileges. By default ASP.NET runs as an unprivileged account named ASPNET. You can change this by making a setting in the processModel section of the machine.config file. When you make this setting, it automatically applies to every site on the server.

To user a high-privileged system account instead of a low-privileged set the userName attribute of the processModel element to SYSTEM. Using this setting is a definite security risk, as it elevates the privileges of the ASP.NET process to a point where it can do bad things to the operating system.

When you disable impersonation, all the request will run in the context of the account running ASP.NET: either the ASPNET account or the system account. This is true when you are using anonymous access or authenticating users in some fashion. After the user has been authenticated, ASP.NET uses its own identity to request access to resources.

The second possible setting is to turn on impersonation. <identity impersonate="false"/>.

In this case, ASP.NET takes on the identity IIS passes to it. If you are allowing anonymous access in IIS, this means ASP.NET will impersonate the

IUSR_ComputerName account that IIS itself uses. If you aren‘t allowing anonymous

access, ASP.NET will take on the credentials of the authenticated user and make requests for resources as if it were that user. Thus by turning impersonation on and using a non-anonymous method of authentication in IIS, you can let users log on and use their identities within your ASP.NET application.

Finally, you can specify a particular identity to use for all authenticated requests

: <identity impersonate="false" username="DOMAIN\username" password="password"/>.

With this setting, all the requests are made as the specified user (Assuming the password it correct in the configuration file). So, for example you could designate a user for a single application, and use that user‘s identity every time someone authenticates to the application. The drawback to this technique is that you must embed the user‘s password in the web.config file in plain text. Although ASP.NET won‘t allow anyone to download this file, this is still a security risk if anyone can get the file by other means.

26.

What is the difference between Datagrid, Datalist and Repeater?

A Datagrid, Datalist and Repeater are all ASP.NET data Web controls. They have many things in common like DataSource Property, DataBind Method, ItemDataBound and

ItemCreated events.

When you assign the DataSource Property of a DataGrid to a DataSet then each

DataRow present in the DataRow Collection of DataTable is assigned to a corresponding DataGridItem and this is same for the rest of the two controls also. But

The HTML code generated for a DataGrid has an HTML TABLE ROW (TR) element created for the particular DataRow and its a Table form representation with Columns and Rows.

For a Datalist it‘s an Array of Rows and based on the Template Selected and the

RepeatColumn Property value We can specify how many DataSource records should appear per HTML <table> row. In short in DataGrid we have one record per row, but in DataList we can have five or six rows per row.

For a Repeater Control, the DataRecords to be displayed depends upon the Templates specified and the only HTML generated is the due to the Templates.

In addition to these, DataGrid has a pin-built support for Sort, Filter and paging the data, which is not possible when using a DataList and for a Repeater Control we would require to write an explicit code to do paging.

27.

From performance point of view how do Datagrid, Datalist and Repeater rate ?

Repeater is fastest, followed by DataList and finally DataGrid.

28.

What is the method to customize columns in DataGrid?

Use the TemplateColumn.

29.

How can we format data inside DataGrid?

Use the DataFormatString property.

30.

How to decide should you use a DataGrid, DataList or Repeater ?

DataGrid provides ability to allow the end-user to sort, page, and edit its data. But it comes at a cost of speed. Second the display format is simple that is in row and columns. Real life scenarios can be more demanding that.

With its templates, the DataList provides more control over the look and feel of the displayed data than the DataGrid. It offers better performance than DataGrid.

Repeater control allows for complete and total control. With the Repeater, the only

HTML emitted are the values of the databinding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with the DataGrid and DataList. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time.

But repeater does not provide editing features like datagrid so everything has to be coded by programmer. However, the Repeater does boast the best performance of the three data Web controls. Repeater is fastest followed by DataList and finally DataGrid.

31.

Explain main differences between ASP and ASP.NET?

ASP.NET supports new features:

Better Language Support

 New ADO.NET Concepts have been implemented.

 ASP.NET supports full language (C#, VB.NET, C++) and not simple scripting like Vbscript.

Better controls than ASP

ASP.NET covers large sets of HTML controls.

Better Display grid like Datagrid, Repeater and DataList. Many of the display grids have paging support.

Compiled Code

The first request for an ASP.NET page on the server will compile the ASP.NET code and keep a cached copy in memory. The result of this is greatly increased performance.

Better Display grid like Datagrid, Repeater and DataList. Many of the display grids have paging support.

Controls have events support

 All ASP.NET controls support events.

 Load, Click and Change events handled by code makes coding much simpler and much better organized.

Compiled Code

 The first request for an ASP.NET page on the server will compile the ASP.NET code and keep a cached copy in memory. The result of this is greatly increased performance.

Better Authentication Support

 ASP.NET supports forms-based user authentication, including cookie management and automatic redirecting of unauthorized logins. (You can still do your custom login page and custom user checking).

User Accounts and Roles

 ASP.NET allows for user accounts and roles, to give each user (with a given role) access to different server code and executables.

High Scalability

 Server to server communication has been greatly enhanced, making it possible to scale an application over several servers. One example of this is the ability to run XML parsers, XSL transformations and even resource hungry session objects on other servers.

Easy Configuration

 Configuration of ASP.NET is done with plain text files.

 Configuration files can be uploaded or changed while the application is running. No need to restart the server, deal with metabase or registry.

Easy Deployment

 No more server restart to deploy or replace compiled code. ASP.NET simply redirects all new requests to the new code.

32.

What are major events in GLOBAL.ASAX file ?

The Global.asax file, which is derived from the HttpApplication class, maintains a pool of HttpApplication objects, and assigns them to applications as needed. The

Global.asax file contains the following events

Application_Init : Fired when an application initializes or is first called. It is invoked for all HttpApplication object instances.

Application_Disposed : Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.

Application_Error : Fired when an unhandled exception is encountered within the application.

Application_Start : Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.

Application_End : Fired when the last instance of an HttpApplication class is destroyed. It is fired only once during an application‘s lifetime.

Application_BeginRequest : Fired when an application request is received. It is the first event fired for a request, which is often a page request (URL) that a user enters.

Application_EndRequest : The last event fired for an application request.

Application_PreRequestHandlerExecute : Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.

Application_PostRequestHandlerExecute : Fired when the ASP.NET page framework has finished executing an event handler.

Application_PreSendRequestHeaders : Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).

Application_PreSendContent : Fired before the ASP.NET page framework send content to a requesting client (browser).(browser).

Application_AcquireRequestState :Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.

Application_ReleaseRequestState :Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.

Application_ResolveRequestCache : Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.

Application_UpdateRequestCache :Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.

Application_AuthenticateRequest : Fired when the security module has established the current user‘s identity as valid. At this point, the user‘s credentials have been validated.

Application_AuthorizeRequest : Fired when the security module has verified that a user can access resources.

Session_Start : Fired when a new user visits the application Web site.

Session_End :Fired when a user‘s session times out, ends, or they leave the application Web site.

33.

What order they are triggered?

They‘re triggered in the following order:

 Application_BeginRequest

Application_AuthenticateRequest

Application_AuthorizeRequest

Application_ResolveRequestCache

Application_AcquireRequestState

Application_PreRequestHandlerExecute

Application_PreSendRequestHeaders

Application_PreSendRequestContent

..code is executed..

Application_PostRequestHandlerExecute

Application_ReleaseRequestState

Application_UpdateRequestCache

Application_EndRequest

1.

Can we make sessions do not use cookies?

2.

We need to enable "cookieless" property in Web.config.

<sessionState cookieless="true" timeout="20" />

How can we force all the validation control to run?

Call Page.Validate

How can we check if all the validation control are valid and proper?

3.

Using the Page.IsValid() property you can check whether all the validation are done.

4.

If client side validation is enabled in your Web page, does that mean server side code is not run?

When client side validation is enabled server emit‘s JavaScript code for the custom validators. But note that does not mean that server side checks on custom validators do not execute. It does this redundant check two times as some of the validators do not support client side scripting.

5.

Which JavaScript file is referenced for validating the validators at the client side?

WebUIValidation.js javascript file installed at "aspnet_client" root IIS directory is used to validate the validation controls at the client side. That is true for .Net 1.1. in .Net

2.0 we use axd.file for that. You‘ll have to save the AXD file, and then open it in notepad to see the actual javascript.

6.

How to disable client side script in validators?

Set EnableClientScript property to false.

7.

You find that one of your validation is very complicated and does not fit in any of the validators, what will you do ?

Best is to go for CustomValidators. Below is a sample code for a custom validator which checks that a textbox should not have zero value.

<asp:CustomValidator id="CustomValidator1" runat="server"

ErrorMessage="Number not divisible by Zero"

ControlToValidate="txtNumber"

OnServerValidate="ServerValidate"

ClientValidationFunction="CheckZero" /><br />

Input:

<asp:TextBox id="txtNumber" runat="server" />

<script language="javascript">

<!-- function CheckZero(source, args) { int val = parseInt(args.Value, 10); if (value==0) { args.IsValid = false;

} else { args.IsValid = true;

}

}

// -->

</script>

How can I show the entire validation error message in a message box on 8.

the client side?

In ValidationSummary control set property called "ShowMessageBox" to true.

9.

What is Tracing in ASP.NET?

Tracing allows us to view how the code was executed in detail.

10.

How do we enable tracing?

On the Application level we can add directive <trace enabled="true" to the web.config between <system.web>…</system.web> directives. On the page level we can add

Trace ="true" to the @Page directive in the beginning of the page.

11.

What exactly happens when ASPX page is requested from Browser?

 The browser sends the request to the webserver. Let us assume that the

 webserver at the other end is IIS.

Once IIS receives the request he looks on which engine can serve this request. When I mean engine means the DLL who can parse this page or compile and send a response back to browser. Which request to map to is decided by file extension of the page requested. Depending on file extension following are some mapping: .aspx for ASP.NET Web pages, .asmx for ASP.NET

Web services, .config for ASP.NET configuration files, .ashx for custom ASP.NET

HTTP handlers, .rem for remoting resources etc.

Once IIS passes the request to ASP.NET engine page has to go through two section HTTP module section and HTTP handler section. Both these section have their own work to be done in order that the page is properly compiled and sent to the IIS.

HTTP modules inspect the incoming request and depending on that they can change the internal workflow of the request. HTTP handler actually compiles the page and generates output. If you see your machine.config file you will see section of HTTP modules.

HTTP handler is where the actual compilation takes place and the output is generated. HTTP handler section is present in WEB.CONFIG file. Depending on the File extension handler decides which Namespace will generate the output.

Example all .ASPX extension files will be compiled by

System.Web.UI.PageHandlerFactory

Once the file is compiled it will be send back again to the HTTP modules and from there to IIS and then to the browser.

12.

How can we kill a user session?

We can use Session.Abandon directive.

13.

How do you upload a file in ASP.NET?

The code snippet given below enables you to upload a file to a folder named temp on your server: string strdir = "D:\\temp\\"; string strfilename = Path.GetFileName( txtFile.PostedFile.

FileName); txtFile.PostedFile.SaveAs(strdir+strfilename);

Make sure to create the specified folder and change the path before attempting to execute the program. In the above code, you can the HTML File control so that users can browse for the required file. As you may know, an HTML control can be converted into an ASP.NET server control with the addition of the runat = "server" attribute. The system retrieves and saves the file using the PostedFile property. Because the HTML file control is used, you have to specifically give the enctype attribute of the Form tag:

<form method = "post" name = "frmemail" runat = "server" enctype = "multipart/form-data" onSubmit = "return Tocheck(this)">

Visual Studio 2005 ships with a built-in control named "FileUpload". Hence, the usage of the HTML File control can be avoided. Also, there is no need to give the enctype attribute as shown above. The new control automatically handles the encryption.

14.

How do I send email message from ASP.NET ?

To send an email from your ASP.NET page, you need to:

 import the System.Web.Mail namespace in your ASP.NET page. create an instance of the MailMessage class set all the properties of the MailMessage instance. send the message with SmtpMail.Send method.

15.

What are different IIS isolation levels?

IIS has three level of isolation:

 Low (IIS process) In this main IIS process and ASP.NET application run in same process. So if any one crashes the other is also affected. So all application and the IIS process runs on the same process. In case any website crashes it

16.

 affects everyone.

Medium (Pooled) In Medium pooled scenario the IIS and web application run in different processes. So in this case there are two processes process1 and process2. In process1 the IIS process is running and in process2 we have all

Web applications running.

High (Isolated) In high isolated scenario every process is running is their own process. This consumes heavy memory but has highest reliability.

ASP used STA threading model, what is the threading model used for

ASP.NET ?

ASP.NET uses MTA threading model.

17.

What is the use of <%@ page aspcompat=true %> attribute?

This attribute works like a compatibility option. As mentioned before ASP worked in

STA model and ASP.NET works in MTA model, but what if your ASP.NET application is using a VB COM component. In order that VB COM runs properly in ASP.NET threading model we have to set attribute. After defining the ASPCOMPAT directive attribute

ASP.NET pages runs in STA model thus building the compatibility between ASP.NET and old COM components that does not support MTA model.

18.

If cookies are not enabled at browser end does form Authentication work?

No, it does not work.

19.

What is the difference between "Web farms" and "Web garden"?

"Web farms" are used to have some redundancy to minimize failures. It consists of two or more web server of the same configuration and they stream the same kind of contents. When any request comes there is switching / routing logic which decides which web server from the farm handles the request. For instance we have two servers "Server1" and "Server2" which have the same configuration and content. So there is a special switch which stands in between these two servers and the users and routes the request accordingly.

A router in between which takes a request and sees which one of the server is least loaded and forwards the request to that server. So for request1 it route‘s server1, for request2 it routes server2, for request3 it routes to server3 and final request4 is routed to server4. So you can see because we have web farm at place server1 and server2 are loaded with two request each rather than one server loading to full. One more advantage of using this kind of architecture is if one of the servers goes down we can still run with the other server thus having 24×7 uptime.

The routing logic can be a number of different options:

Round-robin : Each node gets a request sent to it "in turn". So, server1 gets a request, then server2 again, then server1, then server2 again.

Least Active Whichever node show to have the lowest number of current connects gets new connects sent to it. This is good to help keep the load balanced between the server nodes

Fastest Reply Whichever node replies faster is the one that gets new requests. This is also a good option - especially if there are nodes that might not be "equal" in performance. If one performs better than the other, then send more requests there rather than which is moving slowly?

Web Garden

All requests to IIS are routed to "aspnet_wp.exe" for IIS 5.0 and "w3wp.exe" for IIS

6.0. In normal case i.e. without web garden we have one worker process instance

("aspnet_wp.exe" / "w3wp.exe") across all requests. This one instance of worker process uses the CPU processor as directed by the operating system.

But when we enable web garden for a web server it creates different instances of the worker process and each of these worker process runs on different CPU. You can see in the below diagram we have different worker process instances created which run on different CPU‘s.

In short we can define a model in which multiple processes run on multiple CPUs in a single server machine are known as a Web garden.

20.

How do we configure "WebGarden"?

"Web garden" can be configured by using process model settings in "machine.config" or "Web.config" file. The configuration section is named <processModel> and is shown

in the following example. The process model is enabled by default enable="true").

Below is the snippet from config file.

<processModel enable="true" timeout="infinite" idleTimeout="infinite" shutdownTimeout="0:00:05" requestLimit="infinite" requestQueueLimit="5000" memoryLimit="80" webGarden="false" cpuMask="12" userName="" password="" logLevel="errors" clientConnectedCheck=‖0:00:05"

/>

From the above processModel section for web garden we are concerned with only two attributes "webgarden" and "cpuMask". webGarden : Controls CPU affinity. True indicates that processes should be affinitized to the corresponding CPU. The default is False. cpuMask : Specifies which processors on a multiprocessor server are eligible to run

ASP.NET processes. The cpuMask value specifies a bit pattern that indicates the CPUs eligible to run ASP.NET threads. ASP.NET launches one worker process for each eligible CPU. If webGarden is set to false, cpuMask is ignored and only one worker process will run regardless of the number of processors in the machine. If webGarden is set to true, ASP.NET launches one worker process for each CPU that corresponds to a set bit in cpuMask. The default value of cpuMask is 0xffffffff.

Use 1 for the processor that you want to use for ASP.NET. Use 0 for the processor that you do not want to use for ASP.NET. For example, if you want to use the first two processors for ASP.NET of a four-processor computer, type 1100.

21.

What is the main difference between Gridlayout and FlowLayout ?

GridLayout provides absolute positioning for controls placed on the page. Developers that have their roots in rich-client development environments like Visual Basic will find it easier to develop their pages using absolute positioning, because they can place items exactly where they want them. On the other hand, FlowLayout positions items down the page like traditional HTML. Experienced Web developers favor this approach because it results in pages that are compatible with a wider range of browsers.

If you look in to the HTML code created by absolute positioning you can notice lot of

DIV tags. While in Flow layout you can see more of using HTML table to position elements which is compatible with wide range of browsers.

22.

What’s the difference between trace and debug in ASP.NET?

A. The system.Diagnostics namespace contains the Debug and

Trace classes that include shared methods.

The diffetrnce between these two classes is in the way

Trace and Debug statements are treated at the of creating a release bulid.

Trace statements are included by default when the program is compiled in to release build,where as debug statements

are not.The Debug class is used for debugging,however, the

Trace class is used for testing and optimization even after an application is compiled and released.

23.

How do you enable tracing in on an ASP.NET page?

A. Instead of enabling tracing for individual pages, you can enable it for your entire application. In that case, every page in your application displays trace information.

Application tracing is useful when you are developing an application because you can easily enable it and disable it without editing individual pages. When your application is complete, you can turn off tracing for all pages at once.

When you enable tracing for an application, ASP.NET collects trace information for each request to the application, up to the maximum number of requests you specify.

The default number of requests is 10. You can view trace information with the trace viewer.

By default, when the trace viewer reaches its request limit, the application stops storing trace requests. However, you can configure application-level tracing to always store the most recent tracing data, discarding the oldest data when the maximum number of requests is reached.

To enable tracing for an application

Open your Web site's Web.config file. If no Web.config file exists, create a new file in the root folder and copy the following into it:

<?xml version="1.0"?>

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

<system.web>

</system.web>

</configuration>

Add a trace element as a child of the system.web

element.

In the trace element, set the enabled attribute to true .

If you want trace information to appear at the end of the page that it is associated with, set the trace element's pageOutput attribute to true . If you want tracing information to be displayed only in the trace viewer, set the pageOutput attribute to false .

For example, the following application trace configuration collects trace information for up to 40 requests and allows browsers on computers other than the server of origin to display the trace viewer. Trace information is not displayed in individual pages.

<configuration>

<system.web>

<trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false"/>

</system.web>

</configuration>

You can control whether tracing is enabled or disabled for individual pages. If tracing is enabled, when the page is requested, ASP.NET appends to the page a series of tables containing execution details about the page request. Tracing is disabled by default.

To enable tracing for a page

Include an @ Page directive at the top of your .aspx file.

Add a Trace attribute and set its value to true , as shown in the following example:

<%@ Page Trace="true" %>

Optionally, include the TraceMode attribute to specify the order in which you want your trace messages to appear:

Set TraceMode to SortByTime to sort trace messages in the order in which they are processed.

Set TraceMode to SortByCategory to sort trace messages by the categories that you specified in the TraceContext.Warn

and TraceContext.Write

method calls in your page or server control code.

The following example shows how to enable tracing in a page and to sort trace messages by category.

<%@ Page Language="VB" Trace="True" TraceMode="SortByCategory" %>

24.

Which namespace is needed to implement debug and trace ?

A. System.diagnostic() namespace.

25. Can you explain the concept of trace listener?

A. ‗Tracelistener‘ are objects that get tracing information from the trace class and they output the data to some medium. For instance you can see from the figure

‗TraceListener‘ how it listens to the trace object and outputs the same to UI, File or a windows event log. There are three different types of ‗tracelistener‘ first is the

‗defaulttracelistener‘ (this outputs the data to UI), second is ‗textwritertracelistener‘

(this outputs to a file) and the final one is ‗Eventlogtracelistener‘ which outputs the same to a windows event log.

Below is a code snippet for ‗textwritertracelistener‘ and ‗eventlogtracelistener‘. Using

‗textwritertracelistener‘ we have forwarded the trace‘s to ‗ErrorLog.txt‘ file and in the second snippet we have used the ‗Eventlogtracelistener‘ to forward the trace‘s to windows event log.

25.

What are trace switches?

A. Trace switches helps us to control and govern the tracing behavior of a project. There are two types of trace switches ‗BooleanSwitch‘ and ‗TraceSwitch‘. BooleanSwitch, as the name says, is a kind of on/off switch which can be either enabled (true) or disabled (false).

‗TraceSwitch‘ on the other hand offers more options rather than simple true/false like

‗BooleanSwitch‘. Tracing is enabled for a TraceSwitch object using the Level property. When we set the Level property of a switch to a particular level, it includes all levels from the indicated level down. For example, if you set a TraceSwitch's Level property to

TraceLevel.Info, then all the lower levels, from TraceLevel.Error to TraceLevel.Warning, will be taken in to account. Below are the various levels in ‗TraceSwitch‘ object.

Off a Outputs no messages to Trace Listeners

Error a Outputs only error messages to Trace Listeners

Warning a Outputs error and warning messages to Trace Listeners

Info a Outputs informational, warning and error messages to Trace Listeners

Verbose a Outputs all messages to Trace Listeners

TraceSwitch objSwitch = new TraceSwitch("TraceWarningandError", "Error in trace") ; objSwitch.Level = TraceLevel.Warning ;

Chapter 8: NET Architecture

1.

What are design patterns?

Design patterns are recurring solution to recurring problems in software architecture. There are three basic classification of patterns - creational, structural and behavioral patterns.

Creational Patterns

Abstract Factory: creates an instance of several families of classes

Builder: Separates object construction from its representation

Factory: Creates an instance of several derived classes

Prototype: A fully initialized instance to be copied or cloned

Singleton: A class in which only a single instance can exist

Structural Patterns

Adapter: Match interfaces of different classes

Bridge: Separates an object‘s interface from its implementation

Composite: A tree structure of simple and composite objects

Decorator: Add responsibilities to objects dynamically

Façade: A single class that represents an entire subsystem

Flyweight:A fine-grained instance used for efficient sharing

Proxy:An object representing another object

Behavioral Patterns

Mediator: Defines simplified communication between classes

Memento:Capture and restore an object‘s internal state

Interpreter: A way to include language elements in a program

 Iterator: Sequentially access the elements of a collection

Chain of Responsibility: A way of passing a request between a chain of objects

Command: Encapsulate a command request as an object

State: Alter an object‘s behavior when its state changes

Strategy: Encapsulates an algorithm inside a class

Observer: A way of notifying change to a number of classes

Template: Defer the exact steps of an algorithm to a subclass

Visitor: Defines a new operation to a class without change

2.

What is the difference between Factory and Abstract Factory Patterns?

The main difference between factory and Abstract factory is factory method uses inheritance to decide which object has to be instantiated while abstract factory uses delegation to decide instantiation of object. We can say Abstract factory uses factory method to complete the architecture. Abstract Factory is one level higher in abstraction over Factory.

Here is an example: The actual product section i.e. Class ―Product‖ it inherits from an abstract class ―AbstractProduct‖. The creational aspect section i.e. ―ConcreteCreator‖ class which inherits from class ―Creator‖.

There are some rules the client will have to follow who will need the ―Product‖ object. He will never refer directly to the actual ―Product‖ object he will refer the ―Product‖ object using

―AbstractProduct‖. Client will never use ―New‖ keyword to create the ―Product‖ object but will use the ―Creator‖ class which in turn will use the ―ConcreteCreator‖ class to create the actual

―Product‖ object. So what are the benefits from this architecture? All creational and initializing aspects are now detached from the actual client. As your creational aspect is now been handled in ―ConcreteCreator‖ and the client has reference to only ―Creator‖, so any implementation change in ―CreateProduct‖ will not affect the client code. In short now your creational aspect of object is completely encapsulated from the client‘s logic.

―Abstract factory‖ pattern creates objects for families of classes. In short it describes collection of factor methods from various different families. In groups related factory methods. It creates objects from multiple families rather one product.

3.

What is MVC pattern?

The main purpose using MVC pattern is to decouple the GUI from the Data. It also gives the ability to provide multiple views for the same Data. MVC pattern separates objects in to three important sections:

Model: This section is specially for maintaining data. It is actually where business logic, querying database, database connection etc. is actually implemented.

View: Displaying all or some portion of data, or probably different view of data. View is

 responsible for look and feel, sorting, formatting etc.

Controller: They are event handling section which affects either the model or the view.

Controller responds to the mouse or keyboard input to command model and view to change. Controllers are associated with views. User interaction triggers the events to change the model, which in turn calls some methods of model to update its state to notify other registered views to refresh their display.

Here are the various sections of ASP.NET which maps to MVC sections:

Model: This section is represented by DataView, DataSet, Typed DataSet, Business components, business entity models etc. Now this section can then be tied up to either windows application or web UI.

View: ASPX, ASCX, or windows application UI like data grid etc. form the view part of it.

Controller: In ASP.NET the behind code is the controller as the events are handled by that part. Controller communicates both with Model as well as view.

4.

How can we implement Singleton pattern in .NET?

Singleton pattern mainly focuses on having one and only one instance of the object running.

Example a windows directory service which has multiple entries but you can only have single instance of it throughout the network.

Following are the three steps needed to implement singleton pattern in .NET:

 First create your class with static members.

Public class ClsStaticClass

Private shared objCustomer as clsCustomer

End class

This ensures that there is actually only one Customer object throughout the project.

Define a private constructor to your class. Defining a private constructor to class does not allow a client to create objects directly.

Finally provide a static method to get access to your Singleton object.

5.

How do you implement Prototype pattern in .NET?

We need to implement cloning. Cloning is achieved by using ICloneable of the System namespace. It has a ―Clone‖ method which actually returns the reference of the same copy.

Clone method allows a Shallow copy and not a deep copy. In Shallow copy if you make changes to the cloned object it actually changes on the main object itself. So how is deep copy achieved, by using ―ISerializable‖ interface? So what you do is first serialize the object then deserialize back to a complete new copy. Now any changes to this new copy do not reflect on the original copy of the object, this is called as Deep copy.

6.

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

―Web services‖ uses ―remoting‖ concepts internally. But the major difference between ―web service‖ and ―remoting‖ is that ―web service‖ can be consumed by clients who are not .NET platform. While remoting you need the client to be .NET compliant. Regarding the speed issue

―Remoting‖ is faster than ―Web Services‖. /p>

7.

Can you give a practical implementation of FAÇADE patterns?

Façade pattern sits on the top of lot of subsystems and makes access easy to interfaces of these subsystems. Basic purpose of Façade is to make interfacing between many modules and classes manageable.

Let‘s say we have four subsystems :

Customer

Product

Payment

Invoicing

All the four modules were built at initial stage completely independent. The main interaction between all these subsystems is customer placing order. This functionality can be attained by using all these subsystems, which involves complex interaction between them.

That is where FAÇADE comes in to action. We have built a FAÇADE called as ―FACADEORDER‖ which sits on the top of all these subsystem and fulfill our functionality.

8.

What is three tier architecture?

The three tier software architecture emerged in the 1990s to overcome the limitations of the two-tier architecture. There are three layers when we talk about three tier architecture:

User Interface (Client): This is mostly the windows user interface or the Web interface but this has only the UI part.

Mid layer: Middle tier provides process management where business logic and rules are executed and can accommodate hundreds of users (as compared to only 100 users with the two tier architecture) by providing functions such as queuing, application execution, and database staging.

Data Access Layer: This is also called by the famous acronym ―DAL‖ component. It has mainly the SQL statement which do the database operation part of the job. The three tier architecture is used when an effective distributed client/server design is needed that provides (when compared to the two tier) increased performance, flexibility, maintainability, reusability, and scalability, while hiding the complexity of distributed processing from the user.

9.

What are Microsoft Application Blocks?

Application Blocks are C# and VB.NET classes distributed as Visual Studio projects that can be downloaded from Microsoft‘s Web site and used in any .NET application, including ASP.NET Web applications. They are useful and powerful tools that can make applications more maintainable, scalable and efficient

Secondly which application blocks has been used depends on really what you have implemented. But there are two famous MAB:

 Data Access Block The Data Access Block provides static methods located in the

SqlHelper class that encapsulates the most common data access tasks performed with

Microsoft SQL server. If the term ―static method‖ is new to you, it means that the class

 methods can be called without instantiating an instance of the class. For example, the method ExecuteReader () within the SqlHelper class can be called by simply using the statement SqlHelper.ExecuteReader () - no object instantiation of the SqlHelper class is required.

Exception Management block The Exception Management Application Block provides a simple yet extensible framework for handling exceptions. With a single line of application code you can easily log exception information to the Event Log or extend it by creating your own components that log exception details to other data sources or notify operators, without affecting your application code. The Exception Management Application Block can easily be used as a building block in your own .NET application

10.

What is Service Oriented architecture?

―Services‖ are components which expose well defined interfaces and these interfaces communicate through XML messages. Using SOA you can build workflow, which uses interfaces of these components. SOA is typically useful when you are crossing heterogeneous technical boundaries, organizations, domain etc.

In .NET SOA technically uses Web services to communicate with each service which is crossing boundaries. You can look SOA which sits on top of web services and provides a workflow.

SOA uses service components which operate in their own domain boundary. Here are some points of service :

They are independent components and operate in their own boundary and own technology.

They have well defined interfaces which use XML and WSDL to describe themselves.

Services have URL where anyone can find them and clients can bind to these URL to avail for the service.

Services have very loosely coupled architecture. In order to communicate to service you only have to know the WSDL. Your client can then generate proxy from the WSDL of the service.

11.

What are different ways you can pass data between tiers?

There are many ways you can pass data between tiers :

Dataset the most preferred one as they maintain data in XML format

Datareader

Custom classes

XML

12.

What is Windows DNA architecture?

The Windows Distributed interNet Applications Architecture (DNA) is a Microsoft blueprint for robust, scalable, distributed business software. Windows DNA has evolved over time and was not preplanned. It gives all combined advantages of Centralized mainframe, application servers, internet technologies and Personal computers. Windows DNA is an evolution which started from mainframes (where all logic was centralized), Fox pro ages ( where we talked in terms of two tier systems), VB6 / SQL SERVER (three tier where we talked in terms of having one more tier which was mainly COM where business logic resided), COM+ ( looking in terms of transactions and fulfilling ACID rules) and finally the DNA.

13.

What is aspect oriented programming?

Aspect-oriented software development is a new technology for separation of concerns (SOC) in software development. The techniques of AOSD make it possible to modularize crosscutting aspects of a system.

Aspect oriented programming does not oppose OOP but rather supports it and makes it more maintainable. When we talk in terms of objects it is an entity which maps to real world domain.

Object has attributes which represent the state of object and also define its behavior. By rule of object oriented programming object should be stand alone and communicate with other objects using messages or defined interface.

One object should not communicate with other object directly rather communicate through defined interfaces. Every object satisfies some ―Concern‖ in relation to the system.

There are mainly two types of concern from an object perspective:

Core / Main concerns which it and its work should satisfy.

System concerns which are not related to business functionalities but software related concerns example audit trail, Error handling, Security etc.

When one or many concerns span across module it is called as cross cutting.

Chapter 9: ADO.NET

1.

What are the .Net namespaces with the data functionality classes?

System.Data This namespace contains the basic objects used for accessing and storing relational data, such as DataSet, DataTable, and DataRelation. Each of these is independent of the type of data source and the type of the connection.

System.Data.OleDB: It contains the objects that we use to connect to a data source via an OLE-DB provider, such as OleDbConnection, OleDbCommand, etc. These objects inherit from the common base classes, and so have the same properties, methods, and events as the SqlClient equivalents.

System.Data.SqlClient: This contains the objects that we use to connect to a data source via the Tabular Data Stream (TDS) interface of Microsoft SQL Server (only).

This can generally provide better performance as it removes some of the intermediate layers required by an OLE-DB connection.

System.XML: This Contains the basic objects required to create, read, store, write, and manipulate XML documents according to W3C recommendations.

2.

Give an overview of ADO.Net architecture.

The most important thing to mention in ADO.NET architecture is "Data Provider". Data

Provider provides access to datasource (Access, SQL Server, Oracle etc.).

In short it provides object to achieve functionalities like opening and closing connection, retrieve data and update data. In the below figure you can see the four main sections of a data provider :

Connection object.

Command object (This object is responsible for using stored procedures, queries etc).

Data Adapter (This object acts as a bridge between datastore and DataSet). 

Datareader (This object reads data from data store in forward only mode).

Dataset object (This objects represents disconnected and cached data).

Dataset object represents disconnected and cached data. If you see the diagram it is not in direct connection with the data store, it communicate with Data Adapter, who is responsible for filling the Dataset. Dataset can have one or more Datatable and relations.

3.

What are the two fundamental objects in ADO.NET ?

Datareader and Dataset.

4.

Describe main differences between DataSet and DataReader.

Following are some major differences between DataSet and DataReader :

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

DataSet object providesrandom access and can hold more than one table (in other words more than one rowset) from the same data source as well as the relationships between them.

DataSet is a disconnected architecture while DataReader is connected architecture.

DataSet can persist contents while DataReader cannot.

5.

Describe main differences between ADO.NET and classic ADO.

 As in classic ADO we had client and server side cursors they are no more

 present in ADO.NET. Note it‘s a disconnected model so they are no more applicable.

Locking is not supported due to disconnected model.

All data are stored in XML in ADO.Net as compared to classic ADO where data can be stored in binary format also.

6.

What is the use of connection object ?

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

 An OleDbConnection object is used with an OLE-DB provider.

 A SqlConnection object uses Tabular Data Services (TDS) with MS SQL

Server.

7.

Why do we need a Command object ?

It is used to connect connection object to DataReader or DataSet. Following are the methods provided by command object :

ExecuteNonQuery : Executes the command defined in the CommandText property against the connection defined in the Connection property for a query that does not return any row (an UPDATE, DELETE or INSERT). Returns an

Integer indicating the number of rows affected by the query.

ExecuteReader : Executes the command defined in the CommandText

 property against the connection defined in the Connection property. Returns a

"reader" object that is connected to the resulting rowset within the database, allowing the rows to be retrieved.

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

8.

What is the DataAdapter ?

It is an object that connect one or more Command objects to a DataSet object. They provide logic that would get data from the data store and populates the tables in the

DataSet, or pushes the changes in the DataSet back into the data store.

 An OleDbDataAdapter object is used with an OLE-DB provider.

 A SqlDataAdapter object uses Tabular Data Services with MS SQL Server.

9.

What are basic methods of DataAdapter?

There are three most commonly used methods of DataAdapter :

 Fill : Executes the SelectCommand to fill the DataSet object with data from

 the data source. It can also be used to update (refresh) an existing table in a

DataSet with changes made to the data in the original datasource if there is a primary key in the table in the DataSet.

FillSchema : Uses the SelectCommand to extract just the schema for a table from the data source, and creates an empty table in the DataSet object with all

 the corresponding constraints.

Update : Calls the respective InsertCommand, UpdateCommand, or

DeleteCommand for each inserted, updated,or deleted row in the DataSet so as to update the original data source with the changes made to the content of the

DataSet. This is a little like the UpdateBatch method provided by the ADO

Recordset object, but in the DataSet it can be used to update more than one table.

10.

What is Dataset object?

The DataSet provides the basis for disconnected storage and manipulation of relational data. We fill it from a data store,work with it while disconnected from that data store, then reconnect and flush changes back to the data store if required.

11.

What are the various objects in Dataset ?

Dataset has a collection of DataTable object within the Tables collection. Each

DataTable object contains a collection of DataRow objects and a collection of

DataColumn objects. There are also collections for the primary keys, constraints, and default values used in this table which is called as constraint collection, and the parent and child relationships between the tables. Finally, there is a DefaultView object for

12.

each table. This is used to create a DataView object based on the table, so that the data can be searched, filtered or otherwise manipulated while displaying the data.

How can we connect to the databse, other than SQL Server (Microsoft

Access , Foxpro , Oracle etc ?

Microsoft provides System.Data.OleDb namespace to communicate with databases like scess , Oracle etc. In short any OLE DB-Compliant database can be connected using System.Data.OldDb namespace.

Private Sub loadData()

Dim strPath As String strPath = AppDomain.CurrentDomain.BaseDirectory

Dim objOLEDBCon As New OleDbConnection(―Provider=Microsoft.Jet.OLEDB.4.0;Data

Source =‖ & strPath & ―Nwind.mdb‖)

Dim objOLEDBCommand As OleDbCommand

Dim objOLEDBReader As OleDbDataReader

Try objOLEDBCommand = New OleDbCommand(―Select FirstName from Employees‖) objOLEDBCon.Open() objOLEDBCommand.Connection = objOLEDBCon objOLEDBReader = objOLEDBCommand.ExecuteReader()

Do While objOLEDBReader.Read() lstNorthwinds.Items.Add(objOLEDBReader.GetString(0))

Loop

Catch ex As Exception

Throw ex

Finally objOLEDBCon.Close()

End Try

End Sub

―Loaddata()‖ method actually loads the data in listbox.

Note : This source code has the ConnectionString hard coded in the program itself which is not a good programming practice. For windows application the best place to store connectionstring is ―App.config‖. Also note that the final block which executes irrespective that there is error or not. Thus ensuring that all the connection to the datastore is freed. Its best practice to put all clean up

statements in finally block thus ensuring that the resources are deallocated properly.

13.

How do we use stored procedure in ADO.NET and how do we provide parameters to the stored procedures?

ADO.NET provides the SqlCommand object which provides the functionality of executing stored procedures.

Note :

Sample code is provided in folder ―WindowsSqlClientCommand‖. There are two stored procedures created in same database ―Employees‖ which was created for the previous question.

CREATE PROCEDURE SelectByCustomer @FirstName nvarchar(200) AS

Select FirstName from Customers where FirstName like @FirstName + ‗%‘

CREATE PROCEDURE SelectCustomer AS

Select FirstName from Customers

If txtCustomerName.Text.Length = 0 Then objCommand = New SqlCommand(―SelectCustomer‖)

Else objCommand = New SqlCommand(―SelectByCustomer‖) objCommand.Parameters.Add(―@FirstName‖, Data.SqlDbType.NVarChar, 200) objCommand.Parameters.Item(―@FirstName‖).Value = txtEmployeeName.Text.Trim()

End If

In the above sample not much has been changed only that the SQL is moved to the stored procedures. There are two stored procedures one is ―SelectCustomer‖ which selects all the customers and the other is ―SelectByCustomer‖ which returns customer name starting with a specific character. As you can see to provide parameters to the stored procedures we are using the parameter object of the command object.

14.

How to force the connection object to close after Datareader is closed ?

Command method Executereader takes a parameter called as CommandBehavior where in we can specify saying close connection automatically after the Datareader is closed. pobjDataReader = pobjCommand.ExecuteReader(CommandBehavior.CloseConnection)

15.

How to force the Datareader to return only schema of the datastore rather

16.

than data ?

reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly)

How can we fine tune the command object when we are expecting a single row?

CommandBehaviour enumeration provides two values - SingleResult and SingleRow.

If you expect a single value pass ―CommandBehavior.SingleResult‖ and the query is optimized accordingly, if you expect single row then pass

―CommandBehavior.SingleRow‖.

17.

Which is the best place to store connection string in .NET projects?

Config files are the best places to store connectionstrings. If it is a web-based application ―Web.config‖ file will be used and if it is a windows application ―App.config‖ files will be used.

18.

What are the various methods provided by the dataset object to generate

XML?

Note: XML is one of the most important leap between classic ADO and ADO.NET.

So this question is normally asked more generally how can we convert any data to

XML format. Best answer is convert in to dataset and use the below methods.

ReadXML

Read‘s a XML document in to Dataset.

GetXML

This is a function which returns the string containing XML document.

WriteXML

This writes a XML data to disk.

1.

How can we save all data from DataSet?

Dataset has AcceptChanges method which commits all the changes since last time AcceptChanges has been executed.

2.

How to check that some changes have been made to dataset since it was loaded?

For tracking down changes DataSet has two methods which comes as rescue GetChanges and HasChanges .

GetChanges

Returns DataSet which are changed since it was loaded or since AcceptChanges was executed.

HasChanges

This property indicates that has any changes been made since the dataset was loaded or AcceptChanges method was executed. If we want to revert or abandon all changes since the dataset was loaded use RejectChanges .

Note: One of the most misunderstood things about these properties is that it tracks the changes of actual database. That is a fundamental mistake; actually the changes are related to only changes with dataset and have nothing to with changes happening in actual database. As Dataset is disconnected and do not know anything about the changes happening in actual database.

3.

How can we add/remove row’s in “DataTable” object of “DataSet” ?

―Datatable‖ provides ―NewRow‖ method to add new row to ―DataTable‖. ―DataTable‖ has ―DataRowCollection‖ object which has all rows in a ―DataTable‖ object. Following are the methods provided by ―DataRowCollection‖ object :

 Add

Adds a new row in DataTable

Remove

It removes a ―DataRow‖ object from ―DataTable‖

RemoveAt

It removes a ―DataRow‖ object from ―DataTable‖ depending on index position of the ―DataTable‖.

4.

What is basic use of “DataView” ?

―DataView‖ represents a complete table or can be small section of rows depending on some criteria. It is best used for sorting and finding data within ―Datatable‖. Dataview has the following method‘s :

Find

It takes a array of values and returns the index of the row.

FindRow

This also takes array of values but returns a collection of ―DataRow‖.

If we want to manipulate data of ―DataTable‖ object create ―DataView‖ (Using the ―DefaultView‖ we can create ―DataView‖ object) of the ―DataTable‖ object

5.

 and use the following functionalities :

AddNew

Adds a new row to the ―DataView‖ object.

Delete

Deletes the specified row from ―DataView‖ object.

What is the difference between “DataSet” and “DataReader” ?

Following are the major differences between ―DataSet‖ and ―DataReader‖ :

 ―DataSet‖ is a disconnected architecture, while ―DataReader‖ has live

 connection while reading data. If we want to cache data and pass to a different tier ―DataSet‖ forms the best choice and it has decent XML support.

When application needs to access data from more than one table ―DataSet‖

 forms the best choice.

If we need to move back while reading records, ―datareader‖ does not support this functionality.

 But one of the biggest drawbacks of DataSet is speed. As ―DataSet‖ carry considerable overhead because of relations, multiple tables etc speed is slower than ―DataReader‖. Always try to use ―DataReader‖ wherever possible, as it‘s meant specially for speed performance.

6.

How can we load multiple tables in a DataSet?

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

Above is a sample code which shows how to load multiple ―DataTable‖ objects in one

―DataSet‖ object. Sample code shows two tables ―Table1‖ and ―Table2‖ in object

ObjDataSet. lstdata.DataSource = objDataSet.Tables("Table1").DefaultView

In order to refer ―Table1‖ DataTable, use Tables collection of DataSet and the

Defaultview object will give you the necessary output.

7.

How to add relations between tables in a DataSet?

Dim objRelation As DataRelation objRelation=New DataRelation("CustomerAddresses", _ objDataSet.Tables("Customer").Columns("Custid"),objDataSet.Tables("Addresses").Co

lumns("Custid_fk")) objDataSet.Relations.Add(objRelation)

Relations can be added between ―DataTable‖ objects using the ―DataRelation‖ object.

Above sample code is trying to build a relationship between ―Customer‖ and

―Addresses‖ ―Datatable‖ using ―CustomerAddresses‖ ―DataRelation‖ object.

8.

What is the use of CommandBuilder?

CommandBuilder builds ―Parameter‖ objects automatically. Below is a simple code which uses commandbuilder to load its parameter objects.

Dim pobjCommandBuilder As New OleDbCommandBuilder(pobjDataAdapter) pobjCommandBuilder.DeriveParameters(pobjCommand)

Be careful while using ―DeriveParameters‖ method as it needs an extra trip to the

Datastore which can be very inefficient.

9.

What’s difference between “Optimistic” and “Pessimistic” locking?

In pessimistic locking when user wants to update data it locks the record and till then no one can update data. Other user‘s can only view the data when there is pessimistic locking. In optimistic locking multiple users can open the same record for updating, thus increase maximum concurrency. Record is only locked when updating the record.

This is the most preferred way of locking practically. Now a day‘s browser based application is very common and having pessimistic locking is not a practical solution.

10.

How many ways are there to implement locking in ADO.NET ?

Following are the ways to implement locking using ADO.NET :

 When we call ―Update‖ method of DataAdapter it handles locking internally. If the DataSet values are not matching with current data in Database it raises concurrency exception error. We can easily trap this error using Try..Catch

 block and raise appropriate error message to the user.

Define a Datetime stamp field in the table.When actually you are firing the

UPDATE SQL statements compare the current timestamp with one existing in the database. Below is a sample SQL which checks for timestamp before updating and any mismatch in timestamp it will not update the records. This is the best practice used by industries for locking.

Update table1 set field1=@test where LastTimeStamp=@CurrentTimeStamp

Check for original values stored in SQL SERVER and actual changed values. In stored procedure check before updating that the old data is same as the current. Example in the below shown SQL before updating field1 we check that is the old field1 value same. If not then someone else has updated and necessary action has to be taken.

Update table1 set field1=@test where field1 = @oldfield1value

Locking can be handled at ADO.NET side or at SQL SERVER side i.e. in stored procedures.

11.

How can we perform transactions in .NET?

The most common sequence of steps that would be performed while developing a transactional application is as follows:

 Open a database connection using the Open method of the connection object.

 Begin a transaction using the Begin Transaction method of the connection object. This method provides us with a transaction object that we will use later to commit or rollback the transaction. Note that changes caused by any queries executed before calling the Begin Transaction method will be committed to the database immediately after they execute. Set the Transaction property of the command object to the above mentioned transaction object.

 Execute the SQL commands using the command object. We may use one or more command objects for this purpose, as long as the Transaction property of

 all the objects is set to a valid transaction object.

Commit or roll back the transaction using the Commit or Rollback method of the transaction object.

Close the database connection. 

12.

What is difference between Dataset.Clone and Dataset.Copy?

Clone: It only copies structure, does not copy data.

Copy: Copies both structure and data.

13.

Can you explain the difference between an ADO.NET Dataset and an ADO

Recordset?

There two main basic differences between recordset and dataset :

With dataset you can retrieve data from two databases like oracle and sql server and merge them in one dataset , with recordset this is not possible

All representation of Dataset is using XML while recordset uses COM.

Recordset cannot be transmitted on HTTP while Dataset can be. 

14.

Explain in detail the fundamental of connection pooling?

When a connection is opened first time a connection pool is created and is based on the exact match of the connection string given to create the connection object.

Connection pooling only works if the connection string is the same. If the connection string is different, then a new connection will be opened, and connection pooling won‘t be used

15.

What is Maximum Pool Size in ADO.NET Connection String?

The maximum number of connections allowed in the pool. By default, the max pool size is 100. If we try to obtain connection more than max pool size, then ADO.NET waits for Connection Timeout for the connection from the pool. If even after that connection is not available, we get the exception:

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

16.

How to enable and disable connection pooling?

A.

For .NET it is enabled by default but if you want to just make sure set

Pooling=true in the connection string. To disable connection pooling set

Pooling=false in connection string if it is an ADO.NET Connection. If it is an

OLEDBConnection object set OLE DB Services=-4 in the connection string.

17. What extra features does ADO.Net 2.0 have ?

A. Bulk Copy Operation

Bulk copying of data from a data source to another data source is a newly added feature in

ADO.NET 2.0. ADO.NET inrtoduces bulk copy classes which provide fastest way to transfer\ data from once source to the other. Each ADO.NET data provider has bulk copy classes. For example, in SQL .NET data provider, the bulk copy operation is handled by SqlBulkCopy class, which can read a DataSet, DataTable, DataReader, or XML objects.

Data Paging

A new method is introduced ExecutePageReader which takes three parameters -

CommandBehavior, startIndex, and pageSize. So if you want to get rows ony from 10 - 20, you can simply call this method with start index as 10 and page size as 10.

Batch Update

If you want to update large number of data on set ADO.NET 2.0 provides UpdateBatchSize property, which allows you to set number of rows to be updated in a batch. This increases the performance dramatically as round trip to the server is minimized.

Load and Save Methods

In previous version of ADO.NET, only DataSet had Load and Save methods. The Load method can load data from objects such as XML into a DataSet object and Save method saves the data to a persistent media. Now DataTable also supports these two methods. You can also load a DataReader object into a DataTable by using the Load method.

New Data Controls

In toolbox you can see three new controls - DataGridView, DataConnector, and

DataNavigator.

DataReader's New Execute Methods

Some new execute methods introduced are ExecutePageReader, ExecuteResultSet, and

ExecuteRow.

Chapter 10: SQL SERVER

1. What is normalization? What are different types of normalization?

A. Database normalization is a technique for designing relational database tables to minimize duplication of information and, in so doing, to safeguard the database against certain types of logical or structural problems, namely data anomalies.

1NF Eliminate Repeating Groups - Make a separate table for each set of related attributes, and give each table a primary key.

2NF Eliminate Redundant Data - If an attribute depends on only part of a multi-valued key, remove it to a separate table.

3NF Eliminate Columns Not Dependent On Key - If attributes do not contribute to a description of the key, remove them to a separate table.

BCNF Boyce-Codd Normal Form - If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables.

4NF Isolate Independent Multiple Relationships - No table may contain two or more 1:n or n:m relationships that are not directly related.

5NF Isolate Semantically Related Multiple Relationships - There may be practical constrains on information that justify separating logically related many-to-many relationships.

ONF Optimal Normal Form - a model limited to only simple (elemental) facts, as expressed in Object Role Model notation.

DKNF Domain-Key Normal Form - a model free from all modification anomalies.

Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.

2. What is denormalization?

A. De-normalization is the process of attempting to optimize the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement the relational model poorly.

A true relational DBMS would allow for a fully normalized database at the logical level, while

providing physical storage of data that is tuned for high performance. De-normalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access.

Denormalization of Database! Why?

Only one valid reason exists for denormalizing a relational design - to enhance performance.

However, there are several indicators which will help to identify systems and tables which are potential denormalization candidates. These are:

* Many critical queries and reports exist which rely upon data from more than one table.

Often times these requests need to be processed in an on-line environment.

* Repeating groups exist which need to be processed in a group instead of individually.

* Many calculations need to be applied to one or many columns before queries can be successfully answered.

* Tables need to be accessed in different ways by different users during the same timeframe.

* Many large primary keys exist which are clumsy to query and consume a large amount of

DASD when carried as foreign key columns in related tables.

* Certain columns are queried a large percentage of the time. Consider 60% or greater to be a cautionary number flagging denormalization as an option.

Be aware that each new RDBMS release usually brings enhanced performance and improved access options that may reduce the need for denormalization. However, most of the popular

RDBMS products on occasion will require denormalized data structures. There are many different types of denormalized tables which can resolve the performance problems caused when accessing fully normalized data. The following topics will detail the different types and give advice on when to implement each of the denormalization types.

3. What is a candidate key?

A. A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

4. What are the different types of joins? What is the difference between them?

A. A join combines records from two or more tables in a relational database. In the

Structured Query Language (SQL), there are two types of joins: "inner" and "outer". Outer joins are subdivided further into left outer joins, right outer joins, and full outer joins.

Inner join

This is the default join method if nothing else is specified. An inner join essentially finds the intersection between the two tables. The join takes all the records from table A and finds the matching record(s) from table B. If no match is found, the record from A is not included in the results. If multiple results are found in B that match the predicate then one row will be returned for each (the values from A will be repeated).

Special care must be taken when joining tables on columns that can be NULL since NULL values will never match each other

Left outer join

A left outer join is very different from an inner join. Instead of limiting results to those in both tables, it limits results to those in the "left" table (A). This means that if the ON clause matches 0 records in B, a row in the result will still be returned—but with NULL values for

each column from B.

Right outer join

A right outer join is much like a left outer join, except that the tables are reversed. Every record from the right side, B, will be returned, and NULL values will be returned for those that have no matching record in A.

Full outer join

Full outer joins are the combination of left and right outer joins. These joins will show records from both tables, and fill in NULLs for missing matches on either side.

5. What are indexes? What is the difference between clustered and nonclustered indexes?

A. When data volumes increase, organizations are faced with problems relating to data retrieval and posting. They feel the need for a mechanism that will increase the speed of data access. An index, like the index of a book, enables the database retrieve and present data to the end user with ease. An index can be defined as a mechanism for providing fast access to table rows and for enforcing constraints.

An index can be created by selecting one or more columns in a table that is being searched.

It is a kind of ‗on disk‘ structure associated with the table or view and contains keys that are built from one or more of the columns in the table or view. This structure known as B-Tree helps the SQL Server find the row or rows associated with the key values. Indexes can be created on computed columns or xml columns also.

Indexes can be clustered or non clustered.

A clustered index stores data rows in the table based on their key values. Each table can have only one clustered index as the key values in the data rows are unique and the index is built on the unique key column. When a table has a clustered index, it is known as a clustered table. Non-Clustered indexeshave structures that are different from the data rows. A non clustered index key value is used to point to data rows that contain the key value. This value is known as row locator. The structure of the row locator is determined on the basis of the type of storage of the data pages. If the data page is stored as a heap, a row locator becomes a pointer to a row. If the data page is stored in a clustered table the row locator is a clustered index key. Clustered and Non clustered indexes can be unique and indexes are automatically maintained for a table or view whenever the data table is modified.

6. How can you increase SQL performance?

A. Following are tips which will increase your SQl performance :-

1.Every index increases the time it takes to perform INSERTS, UPDATES and

DELETES, so the number of indexes should not be very much. Try to use maximum 4-5 indexes on one table, not more. If you have read-only table, then the number of indexes may be increased.

2.Keep your indexes as narrow as possible. This reduces the size of the index and reduces the number of reads required to read the index.

3. Try to create indexes on columns that have integer values rather than character values.

4.If you create a composite (multi-column) index, the order of the columns in the key are very important. Try to order the columns in the key as to enhance selectivity, with the most selective columns to the left most of the key.

5.If you want to join several tables, try to create surrogate integer keys for this purpose and create indexes on their columns.

Create surrogate integer primary key (identity for example) if your table will not have many insert operations.

6.Clustered indexes are more preferable than nonclustered, if you need to select by a range of values or you need to sort results set with GROUP BY or ORDER

BY.

7.If your application will be performing the same query over and over on the same table, consider creating a covering index on the table.

8.You can use the SQL Server Profiler Create Trace Wizard with "Identify Scans of Large Tables" trace to determine which tables in your database may need indexes. This trace will show which tables are being scanned by queries instead of using an index

7. What is the use of OLAP?

A. OLAP stands for On Line Analytical Processing, a series of protocols used mainly for business reporting. Using OLAP, businesses can analyze data in all manner of different ways, including budgeting , planning, simulation, data warehouse reporting, and trend analysis . A main component of OLAP is its ability to make multidimensional calculations, allowing a wide and lightning -fast array of possibilities. In addition, the bigger the business, the bigger its business reporting needs. Multidimensional calculations enable a large business to complete in seconds what it otherwise would have waited a handful of minutes to receive.

One main benefit of OLAP is consistency of calculations. No matter how fast data is processed through OLAP software or servers, the reporting that results is presented in a consistent presentation, so executives always know what to look for where. This is especially helpful when comparing information from previous reports to information contained in new ones and projected future ones. "What if" scenarios are some of the most popular uses of OLAP software and are made eminently more possible by multidimensional processing.

Another benefit of multidimensional data presentation is that it allows a manager to pull down data from an OLAP database in broad or specific terms. In other words, reporting can be as simple as comparing a few lines of data in one column of a spreadsheet or as complex as viewing all aspects of a mountain of data. Also, multidimensional presentation can create an understanding of relationships not previously realized. All of this, of course, can be done in the blink of an eye.

8. What is the difference between DELETE TABLE and TRUNCATE TABLE commands?

A. TRUNCATE is a DDL command and cannot be rolled back. All of the memory space is released back to the server.

DELETE is a DML command and can be rolled back.

Both commands accomplish identical tasks (removing all data from a table), but TRUNCATE is much faster.

TRUNCATE : You can't use WHERE clause

DELETE : You can use WHERE clause

9. If locking is not implemented, what issues can occur?

A.

Following are the problems that occur if you do not implement locking properly in SQLSERVER .

Lost Updates

Lost updates occur if you let two transactions modify the same data at the same time, and the transaction that completes first is lost. You need to watch out for lost updates with the

READ UNCOMMITTED isolation level. This isolation level disregards any type of locks, so two simultaneous data modifications are not aware of each other. Suppose that a customer has due of 2000$ to be paid. He pays 1000$ and again buys a product of500$. Let‘s say that

these two transactions are now been entered from two different counters of the company.

Now both the counter user starts making entry at the same time 10:00AM. Actually speaking at 10:01 AM the customer should have 2000$-1000$+500 =1500$ pending to be paid. But as said in lost updates the first transaction is not considered and the second transaction overrides it. So the final pending is 2000$+500$ = 2500$.....I hope the company does not lose the customer.

Non-Repeatable Read

Non-repeatable reads occur if a transaction is able to read the same row multiple times and gets a different value each time. Again, this problem is most likely to occur with the READ

UNCOMMITTED isolation level. Because you let two transactions modify data at the same time, you can get some unexpected results. For instance, a customer wants t book flight, so the travel agent checks for the flights availability. Travel agent finds a seat and goes ahead to book the seat .While the travel agent is booking the seat, some other travel agent books the seat. When this travel agent goes to update the record, he gets error saying that ―Seat is already booked‖. In short the travel agent gets different status at different times for the seat.

Dirty Reads

Dirty reads are a special case of non-repeatable read. This happens if you run a report while transactions are modifying the data that you're reporting on. For example there is a customer invoice report which runs on 1:00 AM in afternoon and after that all invoices are sent to the respective customer for payments. Let us say one of the customer has1000$ to be paid. Customer pays 1000$ at 1:00 AM and at the same time report is run. Actually customer has no money pending but is still issued an invoice.

Phantom Reads

Phantom reads occur due to a transaction being able to read a row on the first read, but not being able to modify the same row due to another transaction deleting rows from the same table. Let‘s say you edit a record in the mean time somebody comes and deletes the record, you then go for updating the record which does not exist....Panicked.

Interestingly, the phantom reads can occur even with the default isolation level supported by SQL Server: READ COMMITTED. The only isolation level that doesn't allow phantoms is

SERIALIZABLE, which ensures that each transaction is completely isolated from others. In other words, no one can acquire any type of locks on the affected row while it is being modified.

10. What are different transaction levels in SQL SERVER?

A. 1. READ UNCOMMITTED Isolation Level: This is very useful in case you need higher concurrency in the transactions. Here one transaction can access the data that has been modified by the second transaction even if the second transaction is not committed.

Syntax:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

Example: Suppose the User1 is trying to update the EngineType from ‗petrol‘ to ‗diesel‘ for

Car_Sl_No with value 2. And at the same time User2 is trying to read the data for the

Car_Sl_No with value 2. Under normal condition or default setting, User2 cannot read the data from that row. But if the User2 sets the transaction isolation level to ‗Read

Uncommitted‘, then it is possible to read that row with updated information even if the transaction is not committed by User1.

For User1 :

USE OLAP

Go

BEGIN TRAN

UPDATE [ OLAP ] .

[ dbo ] .

[ car_info ]

SET [ EngineType ] = 'diesel'

WHERE Car_Sl_No = 2

Here, note that the transaction is still running, as there is no commit statement in the above code. Under default condition, the query ran by User2 will keep executing till the

User1 commits the transaction.

For User2:

USE OLAP

Go

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

--Above statment is used to read the updated value even if the transation is not committed.

SELECT [ Car_Sl_No ]

, [ CarCompany ]

, [ CarBodyType ]

, [ CarName ]

, [ EngineType ]

FROM [ OLAP ] .

[ dbo ] .

[ car_info ]

WHERE Car_Sl_No = 2

As in the above code, we set the transaction isolation level to ‗Read Uncommitted‘; User2 can access that record with updated data.

Output :

Although it increases the concurrency of the transactions but did you notice the disadvantage behind this. What if User1 ROLLBACK his transaction or if somehow the management studio of User1 crashed or hanged (As the transaction is not committed yet, it will rollback itself, resulting false or inconsistent value to User2).

Limitations:

Dirty-reads

Lost Updates

Phantom reads

Non-repeatable reads

Advantages:

Higher Concurrency

In SSIS (SQL Server Integration Service): To achieve the above norm in SSIS, select the task or container on which you want to set the isolation level. Then go to Properties, and set the property named ‗ IsolationLevel ‘ to ― ReadUncommitted ‖.

The benefit here is that more than one task can access the same table simultaneously in case of parallel execution of the package.

2. READ COMMITTED Isolation Level: This is the default level set in SQL Server 2005 and the immediate higher level of ‗READ UNCOMMITTED Isolation Level‘. It prevents transactions to read data if some other transaction is doing some update operation on the data as a result eliminates Dirty Reads. It prevents reading of uncommitted data . But is affected with other demerits like ‗Lost Updates‘.

Syntax:

SET TRANSACTION ISOLATION LEVEL READ COMMITTED

Example: Considering our previous example, let the EngineType for Car_Sl_No with value 2 is NULL and User1 is trying to update the EngineType to ‗ petrol ‘, but at the same time User2 started a new transaction checked the value as Null and starts updating the record to ‗ diesel’ before the transaction is committed by User1. As a result User1 lost its updated value, it is overwritten by User2.

For User1:

USE OLAP

Go

BEGIN TRAN

DECLARE @EngineType VARCHAR ( 20 )

SELECT @EngineType = [ EngineType ] FROM [ OLAP ] .

[ dbo ] .

[ car_info ] WHERE Car_Sl_No = 2

--The below waitfor statement is used for other opearations that User1 is doing for this transaction.

WAITFOR DELAY '00:00:10' --For acheiving real time Concurrency in this example

IF @EngineType IS NULL

BEGIN

UPDATE [ OLAP ] .

[ dbo ] .

[ car_info ]

SET [ EngineType ] = 'petrol'

WHERE Car_Sl_No = 2

END

ELSE

BEGIN

PRINT 'Record is already updated'

END

COMMIT TRAN

For User2:

USE OLAP

Go

BEGIN TRAN

DECLARE @EngineType VARCHAR ( 20 )

SELECT @EngineType = [ EngineType ] FROM [ OLAP ] .

[ dbo ] .

[ car_info ] WHERE Car_Sl_No = 2

--Here waitfor statement is same for User2 also

WAITFOR DELAY '00:00:10' --For acheiving real time Concurrency in this example

IF @EngineType IS NULL

BEGIN

UPDATE [ OLAP ] .

[ dbo ] .

[ car_info ]

SET [ EngineType ] = 'diesel'

WHERE Car_Sl_No = 2

END

ELSE

BEGIN

END

PRINT

COMMIT TRAN

'Record is already updated'

Here both the users successfully updated the value, but the value updated by User2 persists and User1 lost its updated value.

Output: The final output for the record is

Limitations:

Lower Concurrency than ReadUncommitted

Lost Updates

Advantage:

Eliminates Dirty Reads

In SSIS (SQL Server Integration Service): Select the task or container on which you want to set the isolation level. Then go to Properties, and set the property named

‗ IsolationLevel ‘ to ― ReadCommitted ‖.

3. REPEATABLE READ Isolation Level: It is the next higher level than the previous isolation level and the main point here is it does not release the shared lock once the transaction starts for reading data. In simple terms, a transaction cannot read data if it has been modified by other transaction but not yet committed. Also no other transactions can modify data if that data has been read by the current transaction until the current transaction completes. Here in this isolation level, the concurrency rate is very low. As a result, eliminates ‗Lost updates‘, non-repeatable reads, etc. But still has a big problem and that is called ‗Phantom read‘. Let‘s have an example to elaborate this.

Syntax:

SET TRANSACTION ISOLATION LEVEL REPEATABLE READ

Example: Suppose the manager of a showroom declares to transfer all the cars manufactured by Honda Company to another showroom and to maintain a proper record for this operation. We need to add one more column called ‗TransferredSatus‘ to indicate whether that car is transferred or not. Here, the DBA will check for the presence of any

Honda Company cars in the record that are not yet transferred by checking the value of the column ‗TransferredSatus‘. If he found some, then corresponding transfer operations will be performed and the record will be updated to ‗1‘ (i.e. transferred). Here by using ‗Repeatable

Read‘ isolation level, we can eliminate ‗Lost Update‘, ‗dirty reads‘ and ‗non-repeatable reads‘. But what if at the time of updating the database, someone else from the inventory system inserts one record about the new Honda Company car that just arrived to the showroom. Let‘s see the effect.

For User1:

USE OLAP

Go

SET TRANSACTION ISOLATION LEVEL REPEATABLE READ

BEGIN TRAN

--check the existance Honda company cars

DECLARE @Car_Sl_No INT

DECLARE TransferingCarsCursor CURSOR FOR

SELECT Car_Sl_No FROM dbo.

car_info WHERE CarCompany = 'Honda' and

TransferredSatus = 0

OPEN TransferingCarsCursor

FETCH NEXT FROM TransferingCarsCursor

INTO @Car_Sl_No

WHILE @@FETCH_STATUS = 0

BEGIN

----------------------------------

------Car transfering operations--

----------------------------------

FETCH NEXT FROM TransferingCarsCursor

INTO @Car_Sl_No

END

CLOSE TransferingCarsCursor

DEALLOCATE TransferingCarsCursor

WAITFOR DELAY '00:00:10' --For acheiving real time Concurrency in this example

-- This is the time when the other user inserts new record about new Honda car.

UPDATE dbo.

car_info

SET TransferredSatus = 1 WHERE CarCompany = 'Honda' and

TransferredSatus = 0

COMMIT TRAN

Here it found only 2 records from Honda Company.

For User2:

USE OLAP

Go

BEGIN TRAN

INSERT INTO [ OLAP ] .

[ dbo ] .

[ car_info ]

([ CarCompany ]

, [ CarBodyType ]

, [ CarName ]

, [ EngineType ]

, [ TransferredSatus ])

VALUES

( 'Honda' , 'sedan' , 'Civic GX' , 'petrol' , 0 )

COMMIT TRAN

But in between the execution of the transaction by User1, User2 inserts one new record about the new Honda Car. Assume the record is inserted before the Update statement of

User1, as a result instead of updating only 2 records; User1 updates the new record as well along with the earlier records, showing wrong information in the chart. This is called

‗Phantom Read‘. Even ‗Repeatable Read‘ isolation mode can‘t resolve this problem. For this, you need to implement higher isolation level i.e. SERIALIZABLE.

Output for User1 :

(3 row(s) affected)

Limitations:

Lower Concurrency

Phantom Reads

Advantage:

Eliminates Dirty Reads

Eliminates Lost Updates

Eliminates Non-Repeatable Reads

In SSIS (SQL Server Integration Service): Select the task or container on which you want to set the isolation level. Then go to Properties, and set the property named

‗ IsolationLevel ‘ to ― RepeatableRead ‖.

1.

2.

3.

4. SERIALIZABLE Isolation Level: It is highest level in Isolation levels as a result the concurrency rate is low. But it eliminates all issues related to concurrency like dirty read, non repeatable reads, lost updates and even phantom reads. According to this Isolation

Level:

Statements cannot read data if other transactions are performing update operations on the data and is not committed yet.

Also no other transactions can perform any update operations until the current transaction completes its read operations.

And the important point here is that it is performing a Range Lock based on the filters used to get the data from the table i.e. it locks not only the current records but also the new records that are falling under the current filter condition. In simple language, no other transactions can insert new rows that are falling under the current filter condition until the transaction completes.

Considering our previous example, we will set the isolation level to Serializable.

Syntax:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

For User1:

USE OLAP

Go

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN TRAN

--check the existance Honda company cars

DECLARE @Car_Sl_No INT

DECLARE TransferingCarsCursor CURSOR FOR

SELECT Car_Sl_No FROM dbo.

car_info WHERE CarCompany = 'Honda' and

TransferredSatus = 0

OPEN TransferingCarsCursor

FETCH

INTO

NEXT FROM

@Car_Sl_No

TransferingCarsCursor

WHILE @@FETCH_STATUS = 0

BEGIN

----------------------------------

------Car transfering operations--

FETCH

END

----------------------------------

NEXT FROM

INTO @Car_Sl_No

CLOSE TransferingCarsCursor

DEALLOCATE TransferingCarsCursor

TransferingCarsCursor

WAITFOR DELAY '00:00:10'

UPDATE dbo.

car_info

--For acheiving real time Concurrency in this example

-- This is the time when the other user inserts new record about new Honda car.

SET TransferredSatus = 1 WHERE CarCompany = 'Honda' and

TransferredSatus = 0

COMMIT TRAN

For User2:

USE OLAP

Go

BEGIN TRAN

INSERT INTO [ OLAP ] .

[ dbo ] .

[ car_info ]

([ CarCompany ]

, [ CarBodyType ]

, [ CarName ]

, [ EngineType ]

, [ TransferredSatus ])

VALUES

( 'Honda' , 'sedan' , 'Civic GX' , 'petrol' , 0 )

COMMIT TRAN

Output for User1 :

(2 row(s) affected)

Here User2 transaction will wait till the User1 transaction completed avoiding ‗Phantom reads‘.

Limitations:

Lower Concurrency

Advantage:

Eliminates Dirty Reads

Eliminates Lost Updates

Eliminates Non-Repeatable Reads

Eliminates Phantom Reads

In SSIS (SQL Server Integration Service): Select the task or container on which you want to set the isolation level. Then go to Properties, and set the property named

‗ IsolationLevel ‘ to ― Serializable ‖.

5. SNAPSHOT Isolation Level: It specifies that the data accessed by any transaction is consistent and valid for that particular transaction and the data will be same throughout the

whole transaction. It implements Row Versioning to isolate data for each transaction i.e. it will keep separate version of each modified row in the transaction in the tempdb database totally dedicated to that transaction. Any update of data in the original row will not affect the current transaction.

The ALLOW_SNAPSHOT_ISOLATION database option must be set to ON before you can start a transaction that uses the SNAPSHOT isolation level. It is by default kept as OFF because of performance issues.

To enable SNAPSHOT isolation level, use the below alter database command.

ALTER DATABASE OLAP SET ALL OW_SNAPSHOT_ISOLATION ON

We will consider a small example to illustrate the above condition.

Syntax:

SET TRANSACTION ISOLATION LEVEL SNAPSHOT

Example: We will try to insert a new record in the [car_info] table by User1 and at the same time we will try to fetch the records by User2.

For User1:

USE OLAP

Go

BEGIN TRAN

INSERT INTO [ OLAP ] .

[ dbo ] .

[ car_info ]

([ CarCompany ]

, [ CarBodyType ]

, [ CarName ]

, [ EngineType ]

, [ TransferredSatus ])

VALUES

( 'Honda' , 'sedan' , 'Civic Hybrid' , 'petrol' , 0 )

Note: The above transaction is not committed yet.

For User2:

Go

SET TRANSACTION ISOLATION LEVEL SNAPSHOT

BEGIN TRAN

SELECT * FROM dbo.

car_info WHERE CarCompany = 'Honda'

COMMIT TRAN

Output for User1 :

(1 row(s) affected)

Output for User2 :

One record is successfully inserted by User1, but a consisted version of the previous data is kept in Version store (in tempdb ) before the starting of the transaction. So User2 is accessing the data from the version store and is unable to show the newly inserted record.

Now commit the transaction for User1 by ― COMMIT TRAN ‖ command, and again run the transaction for User2, the output will be as below:

You can check the version store for the current transaction along with other information regarding the current transaction by running the below DMVs before committing User1 transaction.

SELECT * FROM sys.

dm_tran_active_snapshot_database_transactions

Output:

Limitations:

Low performance due to versioning in tempdb

Advantage:

Eliminates Dirty Reads

Eliminates Lost Updates

Eliminates Non-Repeatable Reads

Allows multiple updates by versioning

In SSIS (SQL Server Integration Service): Select the task or container on which you want to set the isolation level. Then go to Properties, and set the property named

‗ IsolationLevel ‘ to ― Snapshot ‖.

1.

2.

3.

Other Isolation Levels in SSIS :

Chaos Isolation Level : Behaves the same way as ReadUncommitted, with additional features as stated below:

It permits viewing uncommitted changes by other transactions.

It checks any other uncompleted update transactions with higher restrictive isolation levels to ensure not to raise any conflicts i.e. any pending changes from more highly isolated transactions cannot be overwritten.

Rollback is not supported in this Isolation level.

If you want to perform read operations over the data once per transaction, then go for the Chaos isolation level .

In SSIS (SQL Server Integration Service): Select the task or container on which you want to set the isolation level. Then go to Properties, and set the property named

‗ IsolationLevel ‘ to ― Chaos ‖.

 Unspecified Isolation Level : When the Isolation level of any transaction cannot be determined, then it comes under ‗Unspecified Isolation Level‘ i.e. a different isolation level than the ones above are used. For example performing custom transaction operation

like ODBCtransaction , if the transaction level does not set by the user then it will execute according to the isolation level associated by the ODBC driver.

In SSIS (SQL Server Integration Service): Select the task or container on which you want to set the isolation level. Then go to Properties, and set the property named

‗ IsolationLevel ‘ to ― Unspecified ‖.

11. What are the different locks in SQL SERVER?

A. Types of Locks :

Shared Locks(S) : This lock is useful when you are doing some read operations and no manipulations like write operations (update/delete/insert). This is compatible with other shared locks, update locks and Intent shared locks. It can prevent users from performing dirty reads (described below).

Exclusive Locks(X) : These locks are big possessive types. They are not compatible with any other locks. Like these locks will not work if any other locks are already there with the resource neither it will let other locks to be created on the resource until it finishes its job.

This lock used for data-modification operations, such as INSERT, UPDATE or DELETE.

Update Locks (U) : This can be treated as a mixture and perfect collaboration of the above two locks (Shared and Exclusive). Let‘s take an example. You are going to perform an update operation on a table at row number 23. So here you are doing two types of operation, one is searching the record 23 which can be achieved by implementing shared lock and the other is updating the record after it has found which will be achieved by

Exclusive lock. So, here the shared lock transforms to exclusive lock when it finds the target or else it will be remain as shared lock only. This prevents deadlocks to a great extent. This lock is compatible with Intent shared and shared locks.

Intent locks ( also called as Demand Locks): These are used to establish a lock hierarchy.

Here it will protect placing a shared (S) lock or exclusive (X) lock on a resource lower in the lock hierarchy. For example, suppose you are performing a read operation on a piece of data with shared lock. At the same time another user wants to modify data with exclusive lock, but the shared lock is compatible with other shared locks as a result any number of shared locks can be obtained on a piece of data and hence the user with exclusive has to wait indefinitely till the completion of all shared lock operations. So to avoid this type of starving situation, Intent locks are very useful. Here if the second user comes with Intent

Exclusive lock, then no other transaction can grab a shared lock. Here it can claim the use of exclusive lock after the first transaction completes.

There are basically three types of Intent Locks that are most popular: a) Intent Shared Lock(IS) b) Intent exclusive (IX) c) Shared with intent exclusive (SIX)

Schema Locks: These locks protect the schema of the database. This deals with the DDL

(Data Definition Language) commands like adding or dropping column information for a table, rename table, drop table, blocking any DDL operation during the execution of the query. There are two types of Schema Locks: a) Schema modification (Sch-M): This lock is applied only when the SQL Server engine is modifying the structure of the schema like adding or dropping the columns of a table.

During this period if any other transaction tries to access that object then that will be denied or delayed.

b) Schema stability (Sch-S): This indicates a query using this table being compiled. Here it will not block any transactional locks like shared locks or exclusive locks to perform any operation on the data. But if the query is in running condition, it will prevent execution of any DDL commands on that table.

Bulk Update Locks: This lock is useful while performing BULK operation on the TABLE like

BULK INSERT. It will prevent any other types of normal T-SQL operations to be executed on the table except BULK processing of the data.

12. Can we suggest locking hints to SQL SERVER?

A. Yes

13. What is LOCK escalation?

A.

Lock Escalation:

If you consider the hierarchy of the objects in a SQL Server instance, at the top level you have the database, followed by schema, tables, table partitions, pages and then finally the individual rows. If you acquire a lock at higher level, it can cover more resources there by you consume fewer lock resources (each lock structure takes approximately 100 bytes) and the locking overhead but this comes at a price of lower concurrency. So for example, if you want to select all the rows of a table, if you acquire a lock a table level, you will not need to lock individual rows or pages but then it will block any concurrent update transaction.

Similarly, if you lock individual rows, you will get higher concurrency but then you will incur the overhead of acquiring/releasing locks on each row and lot more locking resources depending upon the isolation level of your transaction, as you may need to hold the locks on all the rows till the end of transaction. Fortunately, for most users don‘t need not concern themselves with nuances of locking strategy as deployed by SQL Server. Depending upon the estimates during query compilation, the SQL Server recommends the locking granularity

(i.e. row, page or table) appropriately and during query execution, depending on the concurrent work load, the appropriate locking granularity is applied. User can override the locking granularity option explicitly by providing locking hints and/or by executing sp_indexoption stored procedure. While locking granularity is chosen at the start of query execution but during the execution, the SQL Server may choose to escalate the lock to coarser level of granularity depending on the number of locks acquired and the availability of memory at run time. Currently, SQL Server only supports escalating the locks to the table level. The locks can only be escalated from rows to the table or pages to the table level. Locks are never escalated from rows to the parent page or from pages to the owning partition.

Triggering Lock Escalation:

A lock escalation is triggered when any of the following conditions is true

 The number of locks held (different from acquired) by a statement on an index or a heap within a statement exceeds the threshold (currently set to 5000 (approx)). These locks include the intent locks as well. Note the lock escalation will not trigger if o The transaction acquires 2,500 locks each on two index/heap(s) in a single statement. o The transaction acquires 2,500 locks on the non-clustered index and 2,500 locks on the corresponding base table in a single statement. o The same heap/index is referenced more than one time in a statement; the locks on each instance of those are counted separately. So for example, in the case of a self-join on a table t1, if each instance has 3000 locks within the statement, it will not trigger lock escalation

 The memory taken by lock resources > 40% of the non-AWE (32-bit) or regular (64bit) enabled memory when the locks configuration option is set to 0, the default value. In this case, the lock memory is allocated dynamically as needed.

 The memory taken by lock resources is > 40% of the configured memory of locks

(i.e. when a non-zero value for the locks configuration option). When locks configuration option is used, the locks memory is statically allocated when SQL Server starts.

When the lock escalation is triggered, the SQL Server attempts to escalate the lock to table level but the attempt may fail if there are conflicting locks. So for example, if the SH locks need to be escalated to the table level and there are concurrent X locks on one or more rows/pages of the target table, the lock escalation attempt will fail. However, SQL Server periodically, for every 1250 (approx) new locks acquired by the lock owner (e.g. transaction), attempts to escalate the lock. If the lock escalation succeeds, the SQL Server releases the lower granularity locks, and the associated lock memory, on the index or the heap. A successful lock escalation can potentially lead to blocking (because at the time of lock escalation, there cannot be any conflicting access) of future concurrent access to the index or the heap by transactions in conflicting lock mode. So the lock escalation is not always a good idea for all applications.

Disabling Lock Escalation:

SQL2005 provides supports disabling lock escalation using two trace flags as follows:

 TraceFlag-1211: It disables lock escalation at the current threshold (5000) on a per index/heap per statement basis. When this trace flag is in effect, the locks are never escalated. It also instructs SQL Server to ignore the memory acquired by the lock manager up to a maximum statically allocated lock memory or 60% of non-AWE(32-bit)/regular(64bit) of the dynamically allocated memory. At this time ran out of lock memory error is generated. This can potentially be damaging as a misbehaving application can exhaust SQL

Server memory by acquiring large number of locks. This, in the worst case, can stall the

Server or degrade its performance to an unacceptable level. For these reasons, a caution must be exercised when using this trace flag

 TraceFlag-1224: This trace flag is similar to trace flag 1211 with one key difference.

It enables lock escalation when lock manager acquires 40% of the statically allocated memory or (40%) non-AWE(32-bit)/regular(64-bit) dynamically allocated memory.

Additionally, if this memory cannot be allocated due to other components taking up more memory, the lock escalation can be triggered earlier. SQL Server will generate an out of memory error when memory allocated to lock manager exceeds the statically allocated memory or 60% of non-AWE(32-bit)/regular memory for dynamic allocation.

If both trace flags (1211 and 1224) are set at the same time, the trace flag 1211 takes precedence. You can use deck tracestatus (-1) command to find the status of all trace flags enabled in SQL Server.

14. What are the different ways of moving data between databases in SQL Server?

A. There are a variety of methods :-

1. The fastest method for whole databases is to use the DUMP DATABASE and LOAD

DATABASE commands. You need to make sure that the databases are the same size and made up of the same segment fragments in the same order. If you do an sp_help_revdatabase on both this will allow you to check the required DDL for this. You can

DUMP and LOAD from a local tape device and transport the tape if you do not have a network connection. (With SQL 7.0 the commands are BACKUP DATABASE and RESTORE

DATABASE)

2. If you only want tables/data you can use the SQL BCP.EXE tool. This is a command-line program and is fully doc'd in the books-online. It works on one table at a time and allows

you to create a flat file on disk.

3. For stored-procedures/views etc. there is an old command-line based tool called

DEFNCOPY.EXE that works like BCP. It isn't used much these days unless you still have SQL

Server on OS/2 - though it still works on NT at least up until 6.5.

4. SQL Enterprise Manager comes with a built-in gui transfer function, and SQL 7 comes with a separate, equivalent tool based on DTS. This allows transfer of all objects between two databases/servers but requires a network connection between the two.

5. The transfer tool supplied with SQL EM is exposed via the DMO interface and can be called using the SQLOLE calls from TSQL or your own VB program for automation purposes.

See Q152801 for an example of how to do this.

6. 3rd-party DBMS management tools no doubt offer similar/better transfer/scripting tools to the above. v1.03 2000.02.02

Applies to SQL Server versions : All

Related FAQ articles : n/a

Related Microsoft Kb articles : n/a

Other related information : n/a

15. What are advantages of SQL 2005 over SQL 2000 and SQl 7.0?

A. SQL Server 2005 has reduced application downtime, increased scalability and performance, and tight yet flexible security controls.

SQL Server 2005 makes it simpler and easier to deploy, manage, and optimize enterprise data and analytical applications.

It enables you to monitor, manage, and tune all of the databases in the effective way.

Failure of the primary system, applications can immediately reconnect to the database on the secondary server using Database Mirroring.

SQL Server 2005 provides a new capability for the partitioning of tables across filegroups in a database.

Has Features of XML, Multidimensional Expressions (MDX), and XML for Analysis (XMLA).

Integration with the Visual Studio development environment provides more efficient development and debugging of line-of-business and business intelligence (BI) applications

16. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

A. Where and Having are two different things. Having is NOT just another WHERE clause.

DB2 will not let you use HAVING without GROUP BY . SYBASE and SQL Server allow HAVING to be used alone but the results can be very unexpected. Be very careful of this it usually will not produce what you want.

WHERE applies to rows HAVING applies to summarized rows (summarized with GROUP BY) if you wanted to find the average salary in each department GREATER than 333 you would code:

SELECT DEPARTMENT AVG(SALARY)

FROM EMP

WHERE DEPARTMENT > 333

GROUP BY DEPARTMENT

IF you then wanted to filter the intermediate result to contain departments where the average salarywas greater that 50 000 you would code:

SELECT DEPARTMENT AVG(SALARY)

FROM EMP

WHERE DEPARTMENT > 333

GROUP BY DEPARTMENT

HAVING AVG(SALARY) > 50000.

Where executes first

GROUP BY next and finally HAVING

WHERE clause is used to impose condition on SELECT statement as well as single row function and is used before GROUP BY clause where as HAVING clause is used to impose condition on GROUP Function and is used after GROUP BY clause in the query

17. What is the difference between UNION and UNION ALL SQL syntax?

A. union is used to select distinct values from two tables where as union all is used to select all values including duplicates from the tables

18. How can you raise custom errors from stored procedure?

A. you have to use RaiseError method to raise errors in SQL please check follwoing article for more information

19. what is ACID fundamental? What are transactions in SQL SERVER?

A. A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties, called the ACID (Atomicity, Consistency,

Isolation, and Durability) properties, to qualify as a transaction:

Atomicity

A transaction must be an atomic unit of work; either all of its data modifications are performed or none of them is performed.

Consistency

When completed, a transaction must leave all data in a consistent state. In a relational database , all rules must be applied to the transaction's modifications to maintain all data integrity. All internal data structures, such as B-tree indexes or doubly-linked lists, must be correct at the end of the transaction.

Isolation

Modifications made by concurrent transactions must be isolated from the modifications made by any other concurrent transactions. A transaction either see data in the state it was before another concurrent transaction modified it, or it sees the data after the second transaction has ompleted, but it does not see an intermediate state. This is referred to as serializability because it results in the ability to reload the starting data and replay a series of transactions to end up with the data in the same state it was in after the original transactions were performed.

Durability

After a transaction has completed, its effects are permanently in place in the system. The modifications persist even in the event of a system failure.

20. What is DBCC?

A. DBCC stands for database consistency checker. We use these commands to check the consistency of the databases.

Example, maintenance, validation task and status checks.

DBCC CHECKALLOC - Check consistency of disk allocation.

DBCC CHECKCATALOG - Check catalog consistency

DBCC CHECKCONSTRAINTS - Check integrity of table constraints.

DBCC CHECKDB - Check allocation, and integrity of all objects.

DBCC CHECKFILEGROUP - Check all tables and indexed views in a filegroup.

DBCC CHECKIDENT - Check identity value for a table.

DBCC CHECKTABLE - Check integrity of a table or indexed view.

DBCC CLEANTABLE - Reclaim space from dropped variable-length columns.

DBCC dllname - Unload a DLL from memory.

DBCC DROPCLEANBUFFERS - Remove all clean buffers from the buffer pool.

DBCC HELP - Help for DBCC commands.

DBCC INPUTBUFFER - Display last statement sent from a client to a database instance.

DBCC OPENTRAN - Display information about recent transactions.

DBCC OUTPUTBUFFER - Display last statement sent from a client to a database instance.

DBCC PROCCACHE - Display information about the procedure cache

DBCC SHOW_STATISTICS - Display the current distribution statistics

DBCC SHRINKDATABASE - Shrink the size of the database data and log files.

DBCC SHRINKFILE - Shrink or empty a database data or log file.

DBCC SQLPERF - Display transaction-log space statistics. Reset wait and latch statistics.

DBCC TRACE - Enable or Disable trace flags

DBCC UPDATEUSAGE - Report and correct page and row count inaccuracies in catalog views

DBCC USEROPTIONS - Return the SET options currently active

DBCC deprecated commands

21. What is the purpose of Replication?

A. Replication is way of keeping data synchronized in multiple databases. SQL server replication has two important aspects publisher and subscriber.

Publisher

Database server that makes data available for replication is called as Publisher.

Subscriber

Database Servers that get data from the publishers is called as Subscribers.

22. What are the different types of replication supported by SQL SERVER?

A. Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios:

Snapshot replication

Transactional replication (with immediate updating subscribers, with queued updating subscribers)

Merge replication

22. What is BCP utility in SQL SERVER?

A. The bcp utility (Bcp.exe) is a command-line tool that uses the Bulk Copy Program (BCP)

API. The bcp utility performs the following tasks:

 Bulk exports data from a SQL Server table into a data file.

 Bulk exports data from a query.

 Bulk imports data from a data file into a SQL Server table.

 Generates format files.

Chapter 11: UML

1. What is UML?

A. The Unified Modeling Language (UML) is a standard language for specifying, visualizing, constructing, and documenting the artifacts of software systems, as well as for business modeling and other non-software systems. The UML represents a collection of best engineering practices that have proven successful in the modeling of large and complex systems.

1 The UML is a very important part of developing object oriented software and the software development process. The UML uses mostly graphical notations to express the design of software projects. Using the UML helps project teams communicate, explore potential designs, and validate the architectural design of the software.

2. How many types of diagrams are there in UML?

A. There are nine standard UML diagrams, roughly ordered here by their by their utility during the analysis and design timeline.

Diagram Impression Significance

Use Case

Diagram

Object

Diagram

Class

Diagram

Sequence

Diagram and

Collaboration

Diagram

(Interaction

Diagrams)

A set of use cases and actors and their relationships.

Important for organizing and modeling system behaviors.

Cruicial for requirements management and communication with end users using their own domain terminology.

Uses very few symbols, all software independent.

A set of objects (instances of classes) and their relationships.

A static snapshot of a dynamic view of the system.

Reperesent real or prototypical cases.

A set of classes, interfaces, collaborations, and relationships

Reflects the static design of a system.

Can be confusing if used to explain system dynamics; use less abstract Object Diagrams instead.

Composed of objects and messages dispatched between them.

Shows a dynamic view of the system.

Sequence Diagram exposes time ordering of messages.

Collaboration Diagram exposes exposes structural organization of messages.

In some tools (i.e. Rational Rose), these diagrams can be interchanged from the same underlying information.

Statechart

Diagram

Represents a state machine, composed of states and transitions.

Addresses the dynamic view of the system.

Useful for reactive behaviors.

Important for modeling interfaces, classes, or collaborations.

Activity

Diagram

Addresses a dynamic view of the system.

Important for modeling system functions.

Emphasizes the flow of objects and synchronization of the flow in support of parallel processing.

An extension of the old "flow chart" diagram combined with

Petri nets.

Addresses larger system engineering issues, and package dependence.

Package

Diagram

Component

Diagram

Shows organization and dependencies among a set of components.

Components are composed of one or more classes or interfaces.

A static view of the system implementation.

Deployment

Diagram

Shows the configuration of run-time processing nodes in the system.

Nodes contain one or more components.

Address a static deployment view of the system.

3. What are advantages of using UML?

A. There are two main advantages of modeling:-

Readability: - Representing your whole architecture in flowchart, class diagrams, ER diagrams etc makes your project more readable. Especially when programmer‘s change jobs handover becomes easier. More the project is not readable more the dependencies.

Reusability: - After the system is more readable and broken down to pieces, it becomes easier to identify redundant and similar modules. Thus increasing reusability.

So why UML, well different language‘s have different ways of coding and syntaxes. In order to bring all languages in one roof UML is in to picture. As the term comes in

UNIFIED, it unifies all disparate languages in one roof so that can be understood by people who are working on some other platforms.

4. What is the sequence of UML diagrams in project?

A.

5. Give a small brief explanation of all Elements in activity diagrams?

A.

6. Explain Different elements of a collaboration diagram?

A.

7. Explain all parts of a deployment diagram?

A

8. Describe the various components in sequence diagrams?

A.

9. What are the elements in State Chart diagrams?

A.

10. Describe different elements in Static Chart diagrams?

A.

11. Explain the different elements of a Use Case?

A.

Chapter 12: Project Management

(B) What is project management?

(A) Is spending in IT projects constant throughout the project?

(B) Who is a stakeholder?

(B) Can you explain project life cycle?

(B) Are risk constant throughout the project?

(A) Can you explain different software development life cycles?

(B) What is triple constraint triangle in project management?

(B) What is a project baseline?

(B) What is effort variance?

(B) How is normally a project management plan document organized?

(I)How do you estimate a project?

(B)What is CAR (Causal Analysis and Resolution)?

(B) What is DAR (Decision Analysis and Resolution)?

(B) What is a fish bone diagram?

(B) What is Pareto principle?

(B) How do you handle change request?

(I) What is internal change request?

(B) What is difference between SITP and UTP in testing?

(B) Which software have you used for project management?

(I) What are the metrics followed in project management?

(B)People in your project do not peform , what will you do?

(B)What is black box testing and White box testing?

(B) What is the difference between Unit testing, Assembly testing and Regression testing?

(I) What is V model in testing?

(B)How do you start a project?

(B)How did you do resource allocations?

(I) How will you do code reviews?

(A)What is CMMI?

(A) What are the five levels in CMMI?

(A) What is continuous and staged representation?

(A)What is SIX sigma?

(A)What are DMAIC and DMADV?

(A)What are the various roles in Six Sigma implementation?

(I)What are function points?

(I)What are the different types of elementary process in FPA?

(I)What are the different elements in Functions points?

(A) Can you explain in GSC and VAF in function points?

(I) What are unadjusted function points and how is it calculated?

(I) Can you explain steps in function points?

(I) What is the FP per day in your current company?

(A)Do you know Use Case points?

(A)What is COCOMO I, COCOMOII and COCOMOIII?

(A) What is SMC approach of estimation?

(A)How do you estimate maintenance project and change requests?

Chapter 13: XML

(B) What is XML?

(I) What is the version information in XML?

(B) What is ROOT element in XML?

(B) If XML does not have closing tag will it work?

(B) Is XML case sensitive?

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

(B) Is XML meant to replace HTML?

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

(B) What is DTD (Document Type Definition)?

(B) What is well formed XML?

(B) What is a valid XML?

(B) What is CDATA section in XML?

(B) What is CSS?

(B) What is XSL?

(B) What is element and attributes in XML?

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

(A) What are the standard ways of parsing XML document?

(A)In What scenarios will you use a DOM parser and SAX parser?

(A) How was XML handled during COM times?

(A)What is the main difference between MSML and .NET Framework XML classes?

(B) What are the core functionalities in XML .NET framework? Can you explain in detail those functionalities?

(B )What is XSLT?

(I) Define XPATH?

(A) What is the concept of XPOINTER?

(B) What is an XMLReader Class?

(B) What is XMLTextReader?

(I) How do we access attributes using ―XmlReader‖?

(I) Explain simple Walk through of XmlReader.

(A) What does XmlValidatingReader class do?

Chapter 14: Localization/Globalization

(B) What is Unicode & Why was it introduced?

(I) Does .NET support UNICODE and how do you know it supports?

(A) What is the difference between localization and globalization?

(A)What architecture decisions you should consider while planning for international software‘s?

(I) How do we get the current culture of the environment in windows and ASP.NET?

(B) Which are the important namespaces during localization and globalization?

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

(I) Can resource file be in any other format other than resx extensions?

(I) How is resource files actually used in project?

(A) How can we use Culture Auto in project?

(B) What are satellite assemblies?

(A) How do we generate Satellite assemblies?

(A) What is AL.EXE and RESGEN.EXE? 275

(I) What is the use of resource manager class?

(A) What precautions do we need to take while deploying satellite assemblies?

(A) Can we get a strongly typed resource class rather than using resource manager?

(A) Can you explain the fundamentals of ―GetGlobalResourceObject‖ and

―GetLocalResourceObject‖ functions?

(A) Can we sign a satellite assembly?

(I) Can you explain collation sequence in sql server?

(A)How do we define collation sequence for database and tables?

(A)Can we change the order in a select query with a specified collation sequence?

(A) Can you list best practices for globalization and localization?

(A) Why is the culture set to the current thread?

Chapter 15: Windows Communication Foundation

(I) What are the important principles of SOA (Service oriented Architecture)?

(I) What are ends, contract, address, and bindings?

(A) Which specifications does WCF follow?

(A) What are the main components of WCF?

(I) Explain how Ends, Contract, Address, and Bindings are done in WCF?

(I) what is a service class?

(I) what is a service contract, operation contract and Data Contract?

(I) what are the various ways of hosting a WCF service?

(I) How do we host a WCF service in IIS?

(I) what are the advantages of hosting WCF Services in IIS as compared to self-hosting?

(I) what are the major differences between services and Web services?

(I) What is the difference WCF and Web services?

(A) What are different bindings supported by WCF?

(A) Which are the various programming approaches for WCF?

(A) What is one-way operation?

(A) Can you explain duplex contracts in WCF?

(A) How can we host a service on two different protocols on a single server?

(A) How can we use MSMQ bindings in WCF?

(A) Can you explain transactions in WCF?

(A) What different transaction isolation levels provided in WCF?

(A) Can we do transactions using MSMQ?

(A)Can we have two-way communications in MSMQ?

(A) What are Volatile queues?

(A) What are Dead letter queues?

(A) What is a poison message?

Chapter 16: Windows Presentation Framework

(B) What is WPF?

(B) What is XAML?

(I) What are dependency properties?

(A) Are XAML file compiled or built on runtime?

(B) Can you explain how we can separate code and XAML?

B) How can we access XAML objects in behind code?

(A) What kind of documents are supported in WPF?

Chapter 17: Windows workflow foundation

(B) What is Windows Workflow Foundation?

(B) What is a Workflow?

(B) What are different types of Workflow in Windows Workflow foundation?

(I) when should we use a sequential workflow and when should we use state machines?

(I) How do we create workflows using designer?

(I) How do we specify conditions in Work flow?

(I) How do you handle exceptions in workflow?

(I) What is the use of XOML files.

(A) How can we pass parameters to workflow?

Chapter 18: ATLAS-AJAX

(B) What problem does Ajax solve?

(B) What is Ajax?

(B) What is the fundamental behind Ajax?

(B) What is JSON?

(B) How do we use XMLHttpRequest object in JavaScript?

(B) How do we do asynchronous processing using Ajax?

(B) What are the various states in XMLHttpRequest and how do we check the same?

(B) How can we get response text?

(B) How can we send request to the server using the XMLHttpRequest component?

(I) How do we pass parameters to the server?

(I) How can we create a class in JavaScript using Atlas?

(A) How do we do inheritance-using Atlas?

(A) How do we define interfaces using Atlas?

(A) How do we reference HTML controls using Atlas?

(I) Can you explain Scriptmanager control in Ajax?

(B) Can you explain Enablepartialrendering and UpdatePanel control in Ajax?

(I) Can you explain the concept of triggers in ‗UpdatePanel‘ control?

(I) Can you explain the ‗UpdateProgress‘ component?

(A) How can you do validations in Ajax?

(A) How do we do exception handling in Ajax?

(A) How do we consume web service in Atlas?

(A) How can we consume data directly in web services?

Chapter 19:- Reports

(B) How do we access crystal reports in .NET?

(I) What are the various components in crystal reports?

(I) What basic steps are needed to display a simple report in crystal?

(I) Can crystal reports be published as a web service?

(I) How do we invoke the crystal report web service?

(I) How do we add formulas using crystal reports?

(I) How do we pass parameters to crystal reports?

(I) How do we export from crystal reports?

(I) How do we print to printer using crystal?

(I) How do we generate cross tab reports?

(A) How can we do grouping in crystal?

(A) Can you explain three-pass reporting which crystal report uses?

(B) Can you explain reporting services architecture?

(B) We have two IIS application ‗Reports‘ and ‗Reportserver‘ what do they do ?

(A) Can you explain Report definition language (RDL) file in reporting services?

(B) What is the basic process of making a report in reporting services?

(B) How can we consume reports in ASP.NET?

(I) Can you explain the difference between private and shared data sources?

(A) How does reports caching in reporting services work ?

(I) What are the major differences between Crystal and SQL reporting services?

Chapter 20:- ASP.NET 2.0

(I) What improvements are provided in ASP.NET 2.0?

(I) How does ASP.NET 2.0 eliminate tedious coding?

(I) How do we encrypt web.config files in ASP.NET 2.0 ?

(A) With the above technique can you encrypt everything in the web.config file?

(A) In .NET 1.X how was the encryption implemented for config files?

(B) Can you explain membership and role providers in ASP.Net 2.0?

(I) What kind of security web controls are introduced in ASP.NET 2.0?

(I) Can you explain master pages concept in ASP.NET?

(I) what is the concept of Web parts?

(A) What are the different components of the web part framework?

(I) What are partial classes in ASP.NET ?

(I) Can you explain generics in .NET ?

(I) Can you explain the concept of generic collection?

(B) How do you send a email using ASP.NET?

(B) How did you deployment and setup in ASP.NET?

Chapter 22:- .NET 3.5

(I) Define LINQ ?

(I) We already have common data access model what is special about LINQ?

(I) How can you make entity classes from the table itself ?

(A) How can we transform LINQ to objects ?

(A) How to transform LINQ to ADO.NET ?

(A) How to transform LINQ to SQL ?

(A) How to transform LINQ to XML ?

(A) How to transform LINQ to entities ?

(A) Can you explain Delegate Instantiation?

(A) Can you explain Anonymous methods ?

(A) What is Yield in LINQ ?

(A) Can you explain Lambda Expressions ?

(A) What are Instance methods and Extension methods ?

(A) What are Anonymous types ?

(A) Revision of Simple Query syntax for LINQ ?

(I) What is silver light?

What is normalization? Explain different levels of normalization?

Check out the article Q100139 from Microsoft knowledge base and of course, there's much more information available in the net. It'll be a good idea to get a hold of any RDBMS fundamentals text book, especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.

What is denormalization and when would you go for it?

As the name indicates, denormalization is the reverse process of normalization. It's the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.

One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.

Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.

It will be a good idea to read up a database designing fundamentals text book.

What's the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined.

But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

What are user defined datatypes and when you should go for them?

User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is

a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.

See sp_addtype, sp_droptype in books online.

What is bit datatype and what's the information that can be stored inside a bit column?

Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL

Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.

Define candidate key, alternate key, composite key.

A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

What are defaults? Is there a column to which a default can't be bound?

A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE DEFUALT in books online.

Back to top

SQL Server architecture (top)

What is a transaction and what are ACID properties?

A transaction is a logical unit of work in which, all the steps must be performed or none.

ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book.

Explain different isolation levels

An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed,

Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level.

CREATE INDEX myIndex ON myTable(myColumn)

What type of Index will get created after executing the above statement?

Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.

What's the maximum size of a row?

8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'. Check out SQL Server books online for the page titled: "Maximum

Capacity Specifications".

Explain Active/Active and Active/Passive cluster configurations

Hopefully you have experience setting up cluster servers. But if you don't, at least be familiar with the way clustering works and the two clusterning configurations Active/Active and Active/Passive. SQL Server books online has enough information on this topic and there is a good white paper available on Microsoft site.

Explain the architecture of SQL Server

This is a very important question and you better be able to answer it if consider yourself a

DBA. SQL Server books online is the best place to read about SQL Server architecture. Read up the chapter dedicated to SQL Server Architecture.

What is lock escalation?

Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening,

SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it's dynamically managed by SQL Server.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?

DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.

Explain the storage models of OLAP

Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more infomation.

What are the new features introduced in SQL Server 2000 (or the latest release of SQL

Server at the time of your interview)? What changed between the previous version of SQL

Server and the current version?

This question is generally asked to see how current is your knowledge. Generally there is a section in the beginning of the books online titled "What's New", which has all such information. Of course, reading just that is not enough, you should have tried those things to better answer the questions. Also check out the section titled "Backward Compatibility" in books online which talks about the changes that have taken place in the new version.

What are constraints? Explain different types of constraints.

Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.

Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

For an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE TABLE", "ALTER TABLE"

Whar is an index? What are the types of indexes? How many clustered indexes can be created on a table? I create a separate index on each column of a table. what are the advantages and disadvantages of this approach?

Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as

B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it's row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same t ime, data modification operations (such as INSERT, UPDATE,

DELETE) will become slow, as every time data changes in the table, all the indexes need to

be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.

Back to top

Database administration (top)

What is RAID and what are different types of RAID configurations?

RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance. MSDN has some information about RAID levels and for detailed information, check out the RAID advisory board's homepage

What are the steps you will take to improve performance of a poor performing query?

This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. But some general issues that you could talk about would be: No indexes, table scans, missing or out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors and temporary tables.

Some of the tools/ways that help you troubleshooting performance problems are: SET

SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server

Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in Query

Analyzer.

Download the white paper on performance tuning SQL Server from Microsoft web site. Don't forget to check out sql-server-performance.com

What are the steps you will take, if you are tasked with securing an SQL Server?

Again this is another open ended question. Here are some things you could talk about:

Preferring NT authentication, using server, databse and application roles to control access to the data, securing the physical database files using NTFS permissions, using an unguessable

SA password, restricting physical access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web server etc.

Read the white paper on SQL Server security from Microsoft website. Also check out My SQL

Server security best practices

What is a deadlock and what is a live lock? How will you go about resolving deadlocks?

Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's process.

A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.

Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also check out the article Q169960 from Microsoft knowledge base.

What is blocking and how would you troubleshoot it?

Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding efficient transactions.

Explain CREATE DATABASE syntax

Many of us are used to craeting databases from the Enterprise Manager or by just issuing the command: CREATE DATABAE MyDB. But what if you have to create a database with two filegroups, one on drive C and the other on drive D with log on drive E with an initial size of

600 MB and with a growth factor of 15%? That's why being a DBA you should be familiar with the CREATE DATABASE syntax. Check out SQL Server books online for more information.

How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?

SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL Server books online for more parameters and their explanations.

As a part of your job, what are the DBCC commands that you commonly use for database maintenance?

DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC

SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful for DBAs. Check out SQL Server books online for more information.

What are statistics, under what circumstances they go out of date, how do you update them?

Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values.

Query optimizer uses these indexes in determining whether to choose an index or not while executing a query.

Some situations under which you should update statistics:

1) If there is significant change in the key values in the index

2) If a large amount of data in an indexed column has been added, changed, or removed

(that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated

3) Database is upgraded from a previous version

Look up SQL Server books online for the following commands: UPDATE STATISTICS,

STATS_DATE, DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats, sp_updatestats

What are the different ways of moving data/databases between servers and databases in

SQL Server?

There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

Explian different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would you go about choosing a backup plan?

Types of backups you can create in SQL Server 7.0+ are Full database backup, differential database backup, transaction log backup, filegroup backup. Check out the BACKUP and

RESTORE commands in SQL Server books online. Be prepared to write the commands in your interview. Books online also has information on detailed backup/restore architecture and when one should go for a particular kind of backup.

What is database replicaion? What are the different types of replication you can set up in

SQL Server?

Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios:

Snapshot replication

Transactional replication (with immediate updating subscribers, with queued updating subscribers)

Merge replication

See SQL Server books online for indepth coverage on replication. Be prepared to explain how different replication agents function, what are the main system tables used in replication etc.

How to determine the service pack currently installed on SQL Server?

The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed. To know more about this process visit SQL Server service packs and versions.

Back to top

Database programming (top)

What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

Cursors allow row-by-row prcessing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike

Salary between 40000 and 55000 -- 7000 hike

Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =

CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000

WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000

WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000

END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don't have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing, check out the 'My code library' section of my site or search for WHILE.

Write down the general syntax for a SELECT statements covering all the options.

Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).

SELECT select_list

[INTO new_table_]

FROM table_source

[WHERE search_condition]

[GROUP BY group_by_expression]

[HAVING search_condition]

[ORDER BY order_expression [ASC | DESC] ]

What is a join and explain different types of joins.

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

For more information see pages from books online titled: "Join Fundamentals" and "Using

Joins".

Can you have a nested transaction?

Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and

@@TRANCOUNT

What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?

An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-SQL, see 'My code library' section of this site.

What is the system function to get the current user's user id?

USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER,

SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().

What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?

Triggers are special kind of stored procedures that get executed automatically when an

INSERT, UPDATE or DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for

UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and

you could create multiple triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder

Triggers can't be invoked on demand. They get triggered only when an associated action

(INSERT, UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers.

Also check out books online for 'inserted table', 'deleted table' and COLUMNS_UPDATED()

There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better?

Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful.

What is a self join? Explain it with an example.

Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp

( empid int, mgrid int, empname char(10)

)

INSERT emp SELECT 1,2,'Vyas'

INSERT emp SELECT 2,3,'Mohan'

INSERT emp SELECT 3,NULL,'Shobha'

INSERT emp SELECT 4,2,'Shridhar'

INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]

FROM emp t1, emp t2

WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]

FROM emp t1

LEFT OUTER JOIN emp t2

ON t1.mgrid = t2.empid

Download