Anda di halaman 1dari 117

1. Delegate?

Ans:-Delegates are Objects that you can use to call the methods of other objects.
They exist for situation in which you want to pass methods around to other
2. Tell me one scenario why u want to use delegates
Ans:-You have method that does something, and rather than working data, the
method might need to do something that involves invoking another method.
You do not know at compile time what the second method is. That information
is only available only at run-time and hence will need to passed in a a
parameter to the first method.
1. Starting Thread: if you want to start new thread you have to supply it
with the details of where to start -in other words the Thread.Start()
method has to take a parameter that defines the method to be involved by
the thread.
2. General Class: say we want to write a process involves repeatedly taking
two of the objects in the array, and comparing them in order to see which
one should come first. The client code will have to pass our class details
of an appropriate method that can be called, which does the comparison
3. Events: In GUI programming if any event occurs we have to inform
windows or .NET run time which method should be called in response to a
3. If I want to get schema along with data to to the dataset what I
have to do
Ans:-There are three ways to create the schema
 Run Time Schema Generation: FillSchema() or using MissingSchema
 Hand Coded : Create Data table and add it to data set and fill with data
 Use the XML schemas generator : create xml Schema ,and use XSD
tool to generate dataset with schems
xsd products.xsd /d
4. Which object supports DOM specification in .NET
Ans:-The XmlNode and XmlNodeList classes meake up the core of the DOM
implementation in .NET
XmlLinkedNode, XmlDocument, XmlDocmentFragment, XmlAttribute,
XmlEntity, XmlNotation are derived form Xml Node
XmlDeclaratin, XmlDocumentType, XmlElement, XmlEntityReferenceNode,
XmlProcessingInstruction are derived from XmlLinkedNode
There is another abstract class, XmlCharacterData that extends
XmlLinkedNOde and provides text manipulation methods for other classes
5. What is Binary formatter
Ans:-Enables you to serilize /Deserilize Object in to Binery Format
6. I am having one text box for date ,how can I validate date format
for text box. Date format will be supplied by client.
Ans:-Using CulterInfo we can format date, time, numbers. A culture is a set of
preferences based on a user’s languae and cultureal conventions
7. I am having one <Asp: Button..> How can execute client side
validation for that ?
I don’t want to use <asp:CustomValidator ……..ClientValidateFunction>
Ans:-Adding Html Attribute using Buttton.Attribute.Add and Using <script> tag
with out run at server
8. Tell me about Attribute
Ans:-Providing Extra information to the runtime about elements
9. Which event will execute first in Form_load and Form_PreRender

10. Tell me different types of Joins
Ans:-Joins can be specified on tables at a time using a column from each table as
connecting or join column
INNER JOINS: Inner joins connect two tables into a a third table that
includes only the rows that satisfy the join condition.Two common types
of inner joins are
1. Equi Join : is a join in which the cloumn values being compared are
equal. An equijoin produces redundant cloumn information because
the join colun join is desplayed twice.
2. Natural Joins: same as Equi join but join column will be displayed
CROSS JOINS: A cross or Unresticted Join produces a result set that includes
every combination of all the rows between the tables in the join
OUTER JOINS: An outer join allows you to restrict the rows in one table
while not restricting the rows in the other table. An outer join can only be
done between two tables.
1. Left Outer Join includes all rows from the first-named table (the
table ont the left of the expression
2. Right Outer Join includes all row from second…right
3. Full Outer Join includes all non matching rows for both the left and
right side table
SELF JOINS: A self join Correlates rows of a table with other rows to that
same table.
11. What is Abstract Class
Ans:-A class that can not be instantiated but is used as a base class
12. What is Shared Members
Ans:-Shared members are common to all instances of a class, while instance
members can have different values for each class instance. Shared properties
and fields are sometimes called class data. Properties and fields that have
different values for each class instance are sometimes called instance data.
Public Shared Function Create(ByVal Country As String) As Order
13. Can I call Static method from nonstatic method
Ans:-Yes You can
14. Can I call nonstatic method from static method
Ans:-No you can’t acces non static members from static members
15. Can I install same version Assemblies on GAC
Ans:-No. Assembly should be unique in name and version
16. What’ s the difference between Having and Where clause
Ans:-Where: to establish individual candidate rows
Having: to select Groups for display.
17. What is function pointer
Ans:-Function pointer is a pointer which holds addresses of the method
18. which keyword u r going to use for abstract class in
19. what are the validation controls
alidator, CusotmValidator,ValidationSummary
20. what is data set
Ans:-Which provided an in-memory relational representaion of data
21. what is data reader

Ans:-Provide a forward-only ,readonly stream of data from a data source
22. what is data adapter
Ans:-Which provides bridge between data set and data source
23. difference between VB and VB.NET
Ans:-The new edition of the Visual Basic development system has significant
improvements. New concepts like full object orientation, structured exception
handling, delegates, and events. This new version of Visual Basic does not
just add new features. Mainly because of the integration into the .NET
Framework, some changes became necessary in addition to a long-expected
review and redesign of certain inconsistencies and irregularities within the
24. what’s meant by ENABLE VEIWSTATE
Ans:-By enabling View State the standard controls preserve their state in
hidden span element
25. what’s the default argument passing in
Ans:-BY Val
26. what is Data Grid
Ans:-DataGrid is a Data Bound control which supports sorting,Paging evey thing
u expect from a databound control.
27. compilation process in .Net
Ans:-Source Code -> MSIL -> Native Code
28. What is the difference between casting and System.Convert
Ans:-Casting never changes the it’s type where as Convert will change the type
29. Satellite assemblies
Ans:-Satellite assemblies are assembly files (.dll) that contain localized resources
for an application. Each satellite assembly file contains the resources for one
culture. An application can have many satellite assemblies, depending on how
many cultures the application supports.
30. What’s the order of Page events from Page_init to Page_Unload
Ans:-Page_init, ,Page_load,page_prerender,Page_unload
31. You Developed a portal for different countries. Fot that u included
resource filse. Not yet developed for all the countries. After
deployment you have to change which is the place to put the
Resource files
Ans:-Satelite Assemblies
32. Can I inherit from a Webform?
33. <Asp:Button id=”button” OnClick=”fn”> what will be the error?
Ans:-Compilation Error <runAt=”server”> should be present
34. A Custom Control should Override _________?
35. When each control is added using VS.NET what will be added to
Webform Class?
Ans:-A Protected Class Member
36. What is the webfarm?
Ans:-A Web application running on multiple servers is called a Web farm
A Web application running on a single server that has multiple CPUs is called a
Web garden.
37. How do you maintain State in ASP.NET
Ans:-Using ViewState, Session, Application, XML,Database
38. If Web Application is deployed Web farm then how do you
maintain ViewState
Ans:-Using Database or XML file
39. How do u edit data in Data Grid ?

Ans:-Using Property OnEditCOmmand
40. What’s the main Diffrence between DataRepeator and Data List
Ans:-Data List is having Editing capabilities
41. What is runtime Polimorphism?
Ans:-Function pointer are called runtime Polimorphism..Net Delegates are
example for Runtime Polimorphism
42. What is dead Lock
Ans:-A situation when two users, each having a lock on one piece of data,
attempt to acquire a lock on the other's piece. Each user 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

T1 T2
A1 A2

Here T1 holds Exclusive lock on A1 for updation and T2 holds Exclusive Lock ion
A2. After Processing some rows in A1 it needs to be process some rows in A2.
Then it Request for A2. But A2 is allready Locked by T2 for editing. Here T2 is
requesting A1. Here is the Dead Lock

T1-A1(Locked for Editing)

T2-->A2 (Loked for Editing)
T1-A2 (Requested for Editing) (It has to wait up to T2 to Release A2)
T2-A1 (Requested for Editing) (It has to wait up to T 1 to Release A1)
43. Tell me one example for n-n relation
Ans:-Products and Cusomer. Here any Products can be bought by any Customer
and any Customer can Buy any Product
C1-P1 P1-C1
C2-P1 p2-c1
C3-P1 p3-c1
…. ….
44. How do u maintain relation between them
Ans:-By maintaing join table with Primarykeys of the Both Table
45. tell me diffrence between Primary Key and Composite Key
Ans:-Primary Key enforces Unique and Not Null constraints on columns for rows.
Composite key is a Primary key of two or more columns.
46. Tell me Difference between normal Select Statement and a Cursor
Ans:-Cursors are usead for Row level Processing where as select statements are
used for table level processing.
47. fn
Some Arithamatic Operation
Some String Manipulation

Catch (..)
In the above fn is it necessary to to find Exception where occurred. IF
yes why?

Ans:-Yes Necessary. You have to know where the exception arises to take proper
action for example u r doing manipulation in BT..ET if you know that exception
is from Data Maipulation Part then u can roll back the action
48. Which Ex………..for Arithamatic
Ans:-Arithamatic Exception
49. Which Ex…for DataManipulation
50. Tell me one Example for Inheritance in VB.NET built in classes
Ans:-All Controls are Inherited from Component class
51. Which features of the .NET did u used
Ans:-I used features like Validation Controls, Databound Controls, Web form
Controls, Windows Controls
52. can u overload a Operator in VB.NET
53. Tell me one Overloaded Operator in VB.NET
Ans:-= Operator
a=10; ‘Assigns a value
if (a=10) ‘ Compares a values

end if
54. Do u know bit in Sql Server
Ans:-Integer data type 1, 0, or NULL.
Remarks:Columns of type bit cannot have indexes on them.
Ans:-Microsoft® SQL Server™ optimizes the storage used for bit columns. If
there are 8 or fewer bit columns in a table, the columns are stored as 1 byte.
If there are from 9 through 16 bit columns, they are stored as 2 bytes, and
so on.
55. U r having one Assembly. All ur application should use that . what
will u do for that
Ans:-I will regeister Assembly in GAC using GacUtil.exe
56. Tell me ASP objects
57. Can u Write down .NET Architecure


.NET Base Classes
Assemly Assemly
with IL with IL
with IL
code code

Language Interoperability
Through CTS and CLS

Type Safety
Create App Domain
Garbage Collector
COM Interop. Services

58. Tell me about OOPs Concepts
Ans:-In Object Oriented Programming Objects are programmatic constructs that
represent packages of related data and functionality
• The representation of real-world objects as programmatic constructs is
called abstraction. Programmatic objects can represent real-world
objects through their implementation of members.
• Classes are the blueprints for objects. When an object is created, a copy
of the class is created in memory, and values for member variables are
initialized. A class can act as a template for any number of distinct
• Encapsulation is a principle of object-oriented programming. An object
should contain all of the data it requires and all of the code necessary to
manipulate that data. The data of an object should never be made
available to other objects. Only properties and methods should be
exposed in the interface.
• Inheritance The process of basing one class on another. In this process,
a base class provides class members to a derived class. The advantage of
inheritance is that you can write and maintain code once in the base class
and reuse it multiple times in the derived classes.
• Polymorphism The ability of classes to provide different
implementations of the same method
59. Tell about Overloading and Overriding
Ans:-overloading In the context of object-oriented programming, the
programming technique of providing versions of a method that takes different
types of arguments. The ToString method is a good example of an overloaded
overriding In the context of object-oriented programming, the programming
technique of replacing a member inherited from a base class with a different
member in the derived class. Shadowing/Hiding is different from overriding
in shadowing no logner base member available from derived
60. what is interface
Ans:-In the context of object-oriented programming, an interface is a contract
that defines the members that a group of classes provides. Once you
implement a particular interface in a class, instances of that class can be used
for any argument or variable declared as that interface.
61. what’s the differencebetween ADO and ADO.Net
 Designed for connected access
 The RecordSet is the central data container
 RecordSet is one (1) table that contains all the data
 Retrieving data from > 1 table or source requires a database JOIN
 Data is “flattened”: lose relationships; navigation is sequential
 Data types are bound to COM/COM+ data types
 Data sharing via COM marshalling
 Problems marshalling through firewalls (DCOM, binary)
 Designed for disconnected access
 The DataSet replaces the RecordSet
 DataSet can contain multiple tables
 Retrieving data from > 1 table or source does not require a JOIN
 Relationships are preserved: navigation is relational
 Data types are only bound to XML schema
 No data type conversions required

 XML, like HTML, is plaintext: “Firewall friendly”

62. what’s the difference between between DataSet and Data Reader
Ans:-DataSet is Suitable for Disconnected datasource senarios. Data set stores
the data in memory with schema. Where as Data Reader is use full for
Connected Datasources.Data Reader is similar to recordset with readonly and
forward only properties
63. what’s .NET Remoting
Ans:-If you need remote component infrastructure, but do not need the level of
interoperability that Web services provide then u can use . Net Temoting
64. what protocols are supported by .Net remoting
Ans:-HTTP,TCP Protocals are implemented in .NET FRAMEWORK. U can
Implement UDP,IPX,SMTP,MSMQ inheriting Ichannel, IchannelReciever,
65. What’s Web Services
Ans:-Web Services are new way of performing remote method calls over HTTP
that can make use of SOAP
66. What is COM
Ans:-A Microsoft specification for developing component software which is based
on binary protocols. A COM component should implement Iunknown interface
which has three methods QueryInterface, AddRef, Release
67. What is DCOM
Ans:-Dcom is Com over Network. Calling Com Objects Remotely
68. What is the tool used to configure the port range and protocols for
DCOM communications?
69. What is MTS
Ans:-MTS is a set of services built on top of COM. Offers object brokering
,Security , Component Packaging and Transaction coordination
70. what’s the difference between .Net Remoting and Webservices
Ans:-.Net Remoting and Web servics appear very similar to each other. In fact
Web services are built on the .Net Remoting infrastructure. .net Remoting
provides the infrastructure to support object remoting solutions, including
functinality. Web services support only the transport of data, and not
71. When would you use .NET Remoting and when Web services?
Ans:-Use remoting for more efficient exchange of information when you control
both ends of the application. Use Web services for open-protocol-based
information exchange when you are just a client or a server with the other
end belonging to someone else.
72. what is stored procedure
Ans:-A precompiled collection of Transact-SQL statements stored under a name
and processed as a unit. SQL Server supplies stored procedures for managing
SQL Server and displaying information about databases and users. SQL
Server-supplied stored procedures are called system stored procedures.
73. which util u use for creating RCW
Ans:-Type library Importar TlbImp.exe and for ActiveXControls AXImp.exe
74. which util u use for creating CCW
Ans:-Regasm mydll
75. Where will be IL stored
Ans:-In a Assembly
76. can I call Com components from my C# code

Ans:-Yes you can call usig RCW
77. After creation of RCW I deleted com dll weather my application will
run which is using COM dll through RCW
Ans:-NO it won’s work RCW requires COM dll
78. what is GAC
Ans:-A machine-wide cache that stores assemblies that have been specifically
designated to be shared between several applications.
79. how can I instal assemblies in to GAC
Ans:-Using GACUtil.exe
gacutil /I mydll ‘ installs the assembly into GAC
gacutil /u mydll ‘ uninstalls the assembly from GAC
80. Can I instal assemblies directly into GAC
Ans:-No first you have to create Strong name for Shared Assembly. To sign your
assembly with a strong name, you must have access to a key file or create
one with the strong name utility (sn.exe). You then specify the key file in the
AssemblyInfo file and verify that the version number is correct. The assembly
will be signed with a strong name when built. In addition to identifying your
assembly and ensuring version identity, a strong name is required if you want
to install your assembly to the Global Assembly Cache.
81. what is assembly
Ans:-Assemblies are basic deployment units in the .Net Frame work . Asssembly
is a logical collection of dlls or exe
82. what’s the difference between Private assemly and Shared
Ans:-Privatre Asssemblies are usedby single Application, so u will store normally
in application folder. Shared Asssemblies are used by Many Application.
Shared assemblies must be installed to use many application. For the shared
assemblies versioning will be enforced
83. which version of asp u r using in ASP.Net
Ans:-ASP.Net is built from scratch.
84. what is trigger
Ans:-A stored procedure that executes when data in a specified table is modified.
Triggers are often created to enforce referential integrity or consistency
among logically related data in different tables.
85. Tell me different type of triggers
Ans:-Insert, Upadate, Delete
86. What is recursive
Ans:-Iterative process which calls itself upto condition satisfy
87. Can I use Recursive in Stored Procedures
88. what is Index
Ans:-In a relational database, a database object that provides fast access to data
in the rows of a table, based on key values. Indexes can also enforce
uniqueness on the rows in a table. SQL Server supports clustered and
nonclustered indexes.By cahracter indexes are two types Unique and
89. what’s the diffrence between clusterd Index and Non Clustered
Ans:-CI: An index in which the logical order of the key values determines the
physical order of the corresponding rows in a table.
NCI: An index in which the logical order of the index is different than the
physical, stored order of the rows on disk.
90. What’s the Diffrence between Unique and Composite Index

Ans:-UNIQUE INDEX: An index in which no two rows are permitted to have the
same index value, thus prohibiting duplicate index or key values. The system
checks for duplicate key values when the index is created and checks each
time data is added with an INSERT or UPDATE statement.
COMPOSITE INDEX: An index that uses more than one column in a table to
index data
91. How many non-clustered indexes u can create on one table
Ans:-U can create maximum of 249 but in real life maximum 5 indexes will be
created per one table
92. can u use client script for server controls
Ans:-ya Using Atribute.Add
93. what is View State
Ans:-View state is state for controls between postbacks. ASP.Net by default
maintains View State for all controls
94. if I don’t want to use View State how can I turn of it
Ans:-By setting <EnableViewState=”false”>
95. What's the difference between early binding and late binding ?
Ans:-In Early Binding you know at the compile time about object interface and
what methods it supports. For the typeless languages like javascript and
vbscript we have to discover and invoke the method at runtime this iscalled
Late binding. Idispach is an interface that COM uses to all methods of a
component’s default interface to be discovered and invoked by a client
application dynamically at runtime. Becaue before the method can be
invoked, the component has to be asked if it supports it at runtime.
InVB, the Idispatch interface is used whenever a variable of type object is
declared. However we have no choice in ASP –we have to use latebinding.
96. What platforms does ASP.NET run on?
Ans:-Currently, it's supported on Windows 2000 and Windows XP. ASP.NET
integrates with Internet Information Server (IIS) and thus requires that IIS
be installed. It runs on server and non-server editions of Windows 2000 and
XP as long as IIS is installed. Microsoft originally planned to support ASP.NET
on Windows NT 4.0, but had to reconsider due to time and technical
97. Can two different programming languages be mixed in a single
ASPX file?
Ans:-No. ASP.NET uses parsers to strip the code from ASPX files and copy it to
temporary files containing derived Page classes, and a given parser
understands only one language.
98. Why can't I put <%@ Page Language="C++" %> at the top of an
ASPX file and write my server-side scripts in C++?
Ans:-Because the parsers ASP.NET uses to extract code from ASPX files only
understand C#, Visual Basic.NET, and JScript.NET. However, if you use code-
behind to get your code out of the ASPX file and into a separately compiled
source code file. You can write server-side scripts in any language supported
by a .NET compiler.
99. Can I use code-behind with Global.asax files?
Ans:-Yes. Here's a simple Global.asax file that doesn't use code-behind:
<%@ Import Namespace="System.Data" %>
<script language="C#" runat="server">
void Application_Start ()
DataSet ds = new DataSet ();
ds.ReadXml (Server.MapPath ("GlobalData.xml"));
Application["GlobalData"] = ds;

Here's the equivalent file written to use code-behind:
<%@ Application Inherits="MyApp" %>
And here's the MyApp class that it references:
using System.Web;
using System.Data;
public class MyApp : HttpApplication
public void Application_Start ()
DataSet ds = new DataSet ();
ds.ReadXml ("GlobalData.xml");
Application["GlobalData"] = ds;
So that ASP.NET can find the MyApp class, compile it into a DLL (csc /t:library
filename.cs) and place it in the application root's bin subdirectory.
100. Can you override method="post" in a <form runat="server"> tag
by writing <form method="get" runat="server">?
101. Can an ASPX file contain more than one form marked
102. Is it possible to see the code that ASP.NET generates from an ASPX
Ans:-Yes. Enable debugging by including a <%@ Page Debug="true" %>
directive in the ASPX file or a <compilation debug="true"> statement in
Web.config. Then look for the generated CS or VB file in a subdirectory
underneath \%SystemRoot%\Microsoft.NET\Framework\ v1.0.nnnn\
Temporary ASP.NET Files.
103. Does ASP.NET support server-side includes?
Ans:-Yes. Server-side includes work the same in ASP.NET as they do in ASP.
104. Does ASP.NET support server-side object tags?
Ans:-Yes. The following tag creates an instance of a custom type named
ShoppingCart and assigns it session scope (that is, it creates a unique
ShoppingCart instance for each and every session created on the server):
<object id="MyShoppingCart" class="ShoppingCart" scope="session"
runat="server" />
Managed types created this way are identified by class name. Unmanaged types
(COM classes) are identified by CLSID or ProgID.
105. How do I comment out statements in ASPX files?
<asp:Button Text="Click Me" OnClick="OnClick" runat="server" />
106. Can I use custom .NET data types in a Web form?
Ans:-Yes. Place the DLL containing the type in the application root's bin directory
and ASP.NET will automatically load the DLL when the type is referenced.
107. How do I debug an ASP.NET application that wasn't written with
Visual Studio.NET and that doesn't use code-behind?
Ans:-Start the DbgClr debugger that comes with the .NET Framework SDK, open
the file containing the code you want to debug, and set your breakpoints.
Start the ASP.NET application. Go back to DbgClr, choose Debug Processes
from the Tools menu, and select aspnet_wp.exe from the list of processes. (If
aspnet_wp.exe doesn't appear in the list, check the "Show system processes"

box.) Click the Attach button to attach to aspnet_wp.exe and begin
Be sure to enable debugging in the ASPX file before debugging it with DbgClr.
You can enable tell ASP.NET to build debug executables by placing a
<%@ Page Debug="true" %> statement at the top of an ASPX file or a
<compilation debug="true" /> statement in a Web.config file.

108. What event handlers can I include in Global.asax?

Ans:-Application start and end event handlers
Session start and end event handlers
Per-request event handlers (listed in the order in which they're called)
Non-deterministic event handlers
Global.asax can also include handlers for events fired by custom HTTP
modules. The event handlers listed above are intrinsic to ASP.NET.
109. Is it possible to protect view state from tampering when it's
passed over an unencrypted channel?
Ans:-Yes. Simply include an @ Page directive with an
EnableViewStateMac="true" attribute in each ASPX file you wish to
protect, or include the following statement in Web.config:
<pages enableViewStateMac="true" />
This configuration directive appends a hash (officially called the message
authentication code, or MAC) to view state values round-tripped to the
client and enables ASP.NET to detect altered view state. If ASP.NET
determines that view state has been altered when a page posts back to
the server, it throws an exception.
The hash is generated by appending a secret key (the validationKey value
attached to the <machineKey> element in Machine.config) to the view
state and hashing the result. An attacker can't modify view state and fix
up the hash without knowing the secret key, too.
110. Is it possible to encrypt view state when it's passed over an
unencrypted channel?
Ans:-Yes. Set EnableViewStateMac to true and either modify the
<machineKey> element in Machine.config to look like this:
<machineKey validation="3DES" ... />
Or add the following statement to Web.config:
<machineKey validation="3DES" />

111. Can a user browsing my Web site read my Web.config or
Global.asax files?
Ans:-No. The <httpHandlers> section of Machine.config, which holds the master
configuration settings for ASP.NET, contains entries that map ASAX files,
CONFIG files, and selected other file types to an HTTP handler named
HttpForbiddenHandler, which fails attempts to retrieve the associated file.
Here are the relevant statements in Machine.config:
<add verb="*" path="*.asax" type="System.Web.HttpForbiddenHandler, ... />
<add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler, ...
112. Do Web controls support Cascading Style Sheets?
Ans:-Yes. All Web controls inherit a property named CssClass from the base class
System.Web.UI.WebControls.WebControl. The following example defines a
CSS class named Input and uses it to modify a TextBox control to display text
in red 10-point Verdana type:
.Input { font: 10pt verdana; color: red; }
<asp:TextBox CssClass="Input" RunAt="server" />
113. Are ASP.NET server controls compatible with Netscape Navigator?
Ans:-Most are. Some controls, such as Label, emit simple HTML tags that are
compatible with virtually all browsers. Others, such as Calendar, emit a mix of
HTML and client-side JavaScript. Fortunately, that JavaScript is simple enough
to work with any browser that supports client-side scripting. The exception is
the validation controls, which emit complex JavaScript that integrates
intimately with the browser's DHTML Document Object Model (DOM). Because
the DOMs used by Navigator and IE are so different, the ASP.NET validation
controls don't work with Navigator. They can still validate input on
the server, but they don't even attempt to validate on the client in
114. What namespaces are imported by default in ASPX files?
Ans:-The following namespaces are imported by default. Other namespaces must
be imported manually using @ Import directives.
115. What assemblies can I reference in an ASPX file without using @
Assembly directives?
Ans:-ASP.NET links to the following assemblies by default:

This list of "default" assemblies is defined in the <assemblies> section of
Machine.config. You can modify it by editing Machine.config or including
an section in a local Web.config file.
116. How does setting a Web control's AutoPostBack property to true
cause a page to post back to the server?
Ans:-With a sprinkle of JavaScript and a dash of Dynamic HTML (DHTML). Enter
this into a Web form:
<asp:TextBox ID="UserName" AutoPostBack="true" RunAt="server" />

And the control returns this:

<input name="UserName" type="text" id="UserName"
onchange="__doPostBack('UserName','')" language="javascript" />
<script language="javascript">
function __doPostBack(eventTarget, eventArgument) {
var theform = document.ctrl0;
// -->
The <input> tag includes an onchange attribute that activates a JavaScript
function named __doPostBack on the client when the control loses the input
focus following a text change. __doPostBack programmatically posts the page
back to the server by calling the Submit method of the DHTML object that
represents the form (theform).
117. I sometimes see ASP.NET apps that include ASHX files. What are
ASHX files?
Ans:-ASHX files contain HTTP handlers-software modules that handle raw HTTP
requests received by ASP.NET. The following code institutes a simple HTTP
<%@ WebHandler Language="C#" Class="Hello"%>
using System.Web;
public class Hello: IHttpHandler
public void ProcessRequest (HttpContext context)
string name = context.Request["Name"];
context.Response.Write ("Hello, " + name);

public bool IsReusable

get { return true; }

If this code is placed in an ASHX file named Hello.ashx and requested using
the URL http://.../hello.ashx?Name=Jeff, it returns "Hello, Jeff" in the HTTP
response. ASHX files provide developers with a convenient way to deploy

HTTP handlers without customizing CONFIG files or modifying the IIS
118. Can I create ASP.NET server controls of my own?
Ans:-Yes. You can modify existing server controls by deriving from the
corresponding control classes or create server controls from scratch by
deriving from System.Web.UI.Control. Although a full treatment of custom
controls is beyond the scope of this FAQ, here's a simple custom control that
writes "Hello, world" to a Web page:
using System;
using System.Web;
using System.Web.UI;

namespace Wintellect
public class HelloControl : Control
protected override void Render (HtmlTextWriter writer)
writer.Write ("Hello, World!");
A custom control emits HTML by overriding the virtual Render method it
inherits from Control and using the provided HtmlTextWriter to write its
119. What does the System.Web.UI.Page.RegisterClientScriptBlock
method do, and do I need it when I write custom ASP.NET server
Ans:-RegisterClientScriptBlock enables a custom control to register a block of
client-side script that the control returns to a browser. Why does it exist? So
the same script block doesn't get returned multiple times if the page contains
multiple instances of a control that emits client-side script. Here's the source
code for a custom control called AlertButton that renders itself an as <input
type="submit"> tag with an onclick attribute that displays a message using a
JavaScript alert:

using System;
using System.Web;
using System.Web.UI;
using System.Text;
namespace Wintellect
public class AlertButton : Control
protected string _Text;
protected string _Message;

public string Text

get { return _Text; }
set { _Text = value; }

public string Message

get { return _Message; }

set { _Message = value; }

protected override void OnPreRender (EventArgs e)

Page.RegisterClientScriptBlock (
"<script language=\"javascript\">\n" +
"function __doAlert (message)\n" +
"{\n" +
" alert (message);\n" +
"}\n" +

protected override void Render (HtmlTextWriter writer)

StringBuilder builder = new StringBuilder ();

builder.Append ("<input type=\"submit\" value=\"");

builder.Append (_Text);
builder.Append ("\" onclick=\"javascript:__doAlert (\'");
builder.Append (Message);
builder.Append ("\');\" />");

writer.Write (builder.ToString ());

If the control's register tag prefix is win, then the following statement declares an
AlertButton control that, when clicked, displays "Hello, world" in a message
<win:AlertButton Text="Click Me" Message="Hello, world" RunAt="server" />
The control uses RegisterClientScriptBlock to register the client-side script block
that it returns. That script block contains the __doAlert function referenced by
the <input> tag's onclick attribute. It's returned only once no matter
AlertButtons a page contains. RegisterClientScriptBlock should always be
called from the control's OnPreRender method so ASP.NET can control the
script's position in the output.
120. What's the difference between Page.RegisterClientScriptBlock and
Ans:-RegisterClientScriptBlock is for returning blocks of client-side script
containing functions. RegisterStartupScript is for returning blocks of client-
script not packaged in functions-in other words, code that's to execute when
the page is loaded. The latter positions script blocks near the end of the
document so elements on the page that the script interacts are loaded before
the script runs.
121. Can a calendar control be customized so that it limits users to
selecting certain days of the week, and only dates that fall on or
after today's date?
Ans:-Yes. The secret is to customize the control by processing DayRender events,
which are fired as the calendar renders each and every cell. Here's an
example that limits selections to future Fridays and Saturdays:

<asp:Calendar OnDayRender="OnDayRender" RunAt="server" />
void OnDayRender (Object sender, DayRenderEventArgs e)
e.Day.IsSelectable =(e.Day.Date.DayOfWeek == DayOfWeek.Friday ||
e.Day.Date.DayOfWeek == DayOfWeek.Saturday) &&
e.Day.Date >= DateTime.Now;
The DayRenderEventArgs passed to a DayRender event handler has a property
named Day that identifies the day being rendered. This example sets Day's
IsSelectable property to true or false depending on whether the day currently
being rendered represents a legitimate selection. Setting IsSelectable to false
prevents the control from placing a hyperlink in the corresponding cell,
effectively making that cell unselectable.
122. Is it necessary to lock application state before accessing it?
Ans:-Only if you're performing a multistep update and want the update to be
treated as an atomic operation. Here's an example:
Application.Lock ();
Application["ItemsSold"] = (int) Application["ItemsSold"] + 1;
Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1;
Application.UnLock ();
By locking application state before updating it and unlocking it afterwards,
you ensure that another request being processed on another thread doesn't
read application state at exactly the wrong time and see an inconsistent view
of it.
123. The ASP.NET application cache doesn't have Lock and UnLock
methods as application state does. Does this mean I never need to
lock it?
Ans:-No. It means you have to come up with your own mechanism for locking.
System.Threading.ReaderWriterLock is the perfect tool for the job.
Assuming rwlock is an instance of ReaderWriterLock, here's how you'd lock
the application cache during an update:
rwlock.AcquireWriterLock (Timeout.Infinite);
Cache["ItemsSold"] = (int) Cache ["ItemsSold"] + 1;
Cache["ItemsLeft"] = (int) Cache ["ItemsLeft"] - 1;
rwlock.ReleaseWriterLock ();
And here's how you'd read "ItemsSold" and "ItemsLeft" values from the
rwlock.AcquireReaderLock (Timeout.Infinite);
int sold = (int) Cache["ItemsSold"];
int left = (int) Cache ["ItemsLeft"];
rwlock.ReleaseReaderLock ();
As with application state, locking the application cache is only necessary when
performing multistep updates that are to be treated as atomic operations.
124. If I update session state, should I lock it, too? Are concurrent
accesses by multiple requests executing on multiple threads a
concern with session state?
Ans:-Concurrent accesses aren't an issue with session state, for two reasons.
One, it's unlikely that two requests from the same user will overlap. Two, if
they do overlap, ASP.NET locks down session state during request processing
so that two threads can't touch it at once. Session state is locked down when
the HttpApplication instance that's processing the request fires an
AcquireRequestState event and unlocked when it fires a ReleaseRequestState

125. ASP.NET's application cache supports expiration policies and cache
removal callbacks. Expiration policies are based on time
dependencies and file dependencies. Are database dependencies
supported, too? In other words, can I have an item automatically
removed from the cache in response to a database update?
Ans:-In ASP.NET version 1.x, no. However, you can forge a link between
databases and the ASP.NET application cache by combining file dependencies
with database triggers.
126. Do ASP.NET forms authentication cookies provide any protection
against replay attacks? Do they, for example, include the client's
IP address or anything else that would distinguish the real client
from an attacker?
Ans:-No. If an authentication cookie is stolen, it can be used by an attacker. It's
up to you to prevent this from happening by using an encrypted
communications channel (HTTPS). Authentication cookies issued as session
cookies, do, however, include a time-out valid that limits their lifetime. So a
stolen session cookie can only be used in replay attacks as long as the ticket
inside the cookie is valid. The default time-out interval is 30 minutes. You can
change that by modifying the timeout attribute accompanying the <forms>
element in Machine.config or a local Web.config file. Persistent authentication
cookies do not time-out and therefore are a more serious security threat if
127. By default, a persistent forms authentication cookie issued by
ASP.NET is valid for 50 years. Is it possible to shorten that?
Ans:-Yes. Unfortunately, there is no configuration setting you can tweak to
customize the lifetime of a persistent authentication cookie, but you can
customize it programmatically. Here's a snippet of code that returns a
persistent authentication cookie from a forms login page and limits the
cookie's lifetime to 7 days:
string url = FormsAuthentication.GetRedirectUrl ("Elmo", true);
FormsAuthentication.SetAuthCookie ("Elmo", true);
HttpCookie cookie =
cookie.Expires = DateTime.Now + new TimeSpan (7, 0, 0, 0);
Response.Redirect (url);
To set the cookie's lifetime to something other than 7 days, simply modify the
TimeSpan value.
128. I wrote an HTTP handler and registered it in the <httpHandlers>
section of a local Web.config file, but the handler never gets called.
What could be wrong?
Ans:-In addition to being mapped to a file type (or specific file name) in a
CONFIG file, an HTTP handler has to be registered in the IIS metabase. For
example, if you register an HTTP handler with the Web.config file shown
below, you also have to map *.igen to Aspnet_isapi.dll in the IIS metabase.
Otherwise, ASP.NET doesn't see the request and can't forward it to the
<add verb="*" path="*.igen" type="ImageGen, ImageGenLib" />
129. How do I send e-mail from an ASP.NET application?

Ans:-MailMessage message = new MailMessage ();
message.From = "";
message.To = "";
message.Subject = "Scheduled Power Outage";
message.Body = "Our servers will be down tonight.";
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send (message);
MailMessage and SmtpMail are classes defined in the .NET Framework Class
Library's System.Web.Mail namespace. Due to a security change made to
ASP.NET just before it shipped, you need to set SmtpMail's SmtpServer
property to "localhost" even though "localhost" is the default. In addition, you
must use the IIS configuration applet to enable localhost ( to relay
messages through the local SMTP service.
130. How do I read an image from a database using ADO.NET and
display it in a Web page?
Ans:-The following ASPX file reads and displays an image from the Pubs database
that comes with Microsoft SQL Server.
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.IO" %>
<script language="C#" runat="server">
void Page_Load(object sender, System.EventArgs e)
MemoryStream stream = new MemoryStream ();
SqlConnection connection = new SqlConnection
try {
connection.Open ();
SqlCommand command = new SqlCommand ("select logo from
pub_info where pub_id='0736'", connection);
byte[] image = (byte[]) command.ExecuteScalar ();
stream.Write (image, 0, image.Length);
Bitmap bitmap = new Bitmap (stream);
Response.ContentType = "image/gif";
bitmap.Save (Response.OutputStream, ImageFormat.Gif);
finally {
connection.Close ();
stream.Close ();
131. Some Web service classes derive from System.Web.WebServices;
others do not. What's the deal?
Ans:-WebService contributes properties named Application, Session, Context,
Server, and User to derived classes enabling Web services to access the
ASP.NET objects of the same name. If you don't use these objects in your
Web service-for example, if you don't use application state or session state-
then you don't have to derive from WebService, either. Incidentally, if you
want to use ASP.NET session state in a Web method, use the following
WebMethod attribute to enable session state for that method:

[WebMethod (EnableSession="true")]
132. What are VSDISCO files?
Ans:-VSDISCO files are DISCO files that support dynamic discovery of Web
services. If you place the following VSDISCO file in a directory on your Web
server, for example, it returns references to all ASMX and DISCO files in the
host directory and any subdirectories not noted in <exclude> elements:
<?xml version="1.0" ?>
<dynamicDiscovery xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-
<exclude path="_vti_cnf" />
<exclude path="_vti_pvt" />
<exclude path="_vti_log" />
<exclude path="_vti_script" />
<exclude path="_vti_txt" />
How does dynamic discovery work? ASP.NET maps the file name extension
VSDISCO to an HTTP handler that scans the host directory and subdirectories
for ASMX and DISCO files and returns a dynamically generated DISCO
document. A client who requests a VSDISCO file gets back what appears to
be a static DISCO document.
Note that VSDISCO files are disabled in the release version of ASP.NET. You
can reenable them by uncommenting the line in the <httpHandlers> section
of Machine.config that maps *.vsdisco to
System.Web.Services.Discovery.DiscoveryRequestHandler and granting the
ASPNET user account permission to read the IIS metabase. However,
Microsoft is actively discouraging the use of VSDISCO files because they could
represent a threat to Web server security.
133. How does a Web service client call Web methods asynchronously?
Ans:-Web service proxy classes generated by Wsdl.exe contain asynchronous as
well as synchronous versions of the Web service's methods. Suppose a Web
service implements the following Add method:
public int Add (int a, int b)
return a + b;
A proxy generated by Wsdl.exe has BeginAdd and EndAdd methods for calling
Add asynchronously. Assuming calc is an instance of the proxy class,
here's how a client calls Add asynchronously:
// Initiate an async call
IAsyncResult res = calc.BeginAdd (2, 2, null, null);
// Get the results
int sum = calc.EndAdd (res);
If the call hasn't completed when EndAdd is called, EndAdd blocks until it
does. If desired, a client can ask to be notified when an asynchronous call
returns by providing a reference to an AsyncCallback delegate wrapping a
callback method. In the next example, EndAdd won't block because it isn't
called until the client is certain the method call has returned:
AsyncCallback cb = new
AsyncCallback (AddCompleted);
IAsyncResult res = calc.BeginAdd (2, 2, cb, null);

public void AddCompleted (IAsyncResult res)
int sum = calc.EndAdd (res);
Another option is to use the IsCompleted property of the IAsyncResult
interface returned by BeginAdd to determine whether the call has
completed and avoid calling EndAdd until it does:
IAsyncResult res = calc.BeginAdd (2, 2, null, null);
if (res.IsCompleted) {
int sum = calc.EndAdd (res);
else {
// Try again later
134. I wrote code that uses the SmtpMail and MailMessage classes to
send e-mail from an ASP.NET application. The code worked fine in
beta 2, but it throws an exception in the release version of
ASP.NET. What's wrong?
Ans:-Due to a security change made to ASP.NET just before it shipped, you
need to set SmtpMail's SmtpServer property to "localhost" even though
"localhost" is the default. In addition, you must use the IIS configuration
applet to enable localhost ( to relay messages through the local
SMTP service.
135. How do I upload files to Web pages in ASP.NET?
Ans:-Use the HtmlInputFile class, which you can declare an instance of with
an <input type="file" runat="server"/> tag. The following example is a
complete ASPX file that lets a user upload an image file and a comment
descibing the image. The OnUpload method writes the image and the
comment to a table named Pictures in a SQL Server database named
<%@ Import Namespace="System.Data.SqlClient" %>

<form enctype="multipart/form-data" runat="server">

<td>File name</td>
<td><input type="file" id="Upload" runat="server" /></td>
<td><asp:TextBox ID="Comment" RunAt="server" /></td>
<td><asp:Button Text="Upload" OnClick="OnUpload" RunAt="server"
<script language="C#" runat="server">
void OnUpload (Object sender, EventArgs e)

// Create a byte[] from the input file
int len = Upload.PostedFile.ContentLength;
byte[] pic = new byte[len];
Upload.PostedFile.InputStream.Read (pic, 0, len);
// Insert the image and comment into the database
SqlConnection connection = new SqlConnection
try {
connection.Open ();
SqlCommand cmd = new SqlCommand ("insert into Pictures " +
"(Picture, Comment) values (@pic, @text)", connection);
cmd.Parameters.Add ("@pic", pic);
cmd.Parameters.Add ("@text", Comment.Text);
cmd.ExecuteNonQuery ();
finally {
connection.Close ();
136. How do I create an ASPX page that periodically refreshes itself?
Ans:-<meta http-equiv="Refresh" content="nn"> //nn seconds
137. How can an ASP.NET application determine whether cookies are
enabled in a browser?
Ans:-Determining whether cookies are enabled requires a round trip to the
browser and back. If you can live with an extra round trip, the basic strategy
is to return a cookie in an HTTP response and redirect to a page that checks
for the cookie. Here's a page that does just that:
<form runat="server">
<asp:Button Text="Test Cookie Support" OnClick="OnTest" RunAt="server"
<script language="C#" runat="server">
void OnTest (Object sender, EventArgs e)
HttpCookie cookie = new HttpCookie ("Foo", "Bar");
Response.Cookies.Add (cookie);
Response.Redirect ("OtherPage.aspx");
And here's the page that it redirects to (OtherPage.aspx). This page uses the
presence or absence of the cookie to determine whether cookies are enabled
and displays the result:
<%@ Page Language="C#" %>
HttpCookie cookie = Request.Cookies["Foo"];
if (cookie != null && cookie.Value == "Bar")
Response.Write ("Cookies are enabled");
Response.Write ("Cookies are not enabled");

138. Is it possible to prevent a browser from caching an ASPX page?
Ans:-You bet. Just call SetNoStore on the HttpCachePolicy object exposed
through the Response object's Cache property,
Response.Cache.SetNoStore ()
139. How do I create a DataGrid with Delete buttons and pop up a
message box asking the user for confirmation before deleting a
Ans:-The ASPX file below demonstrates the proper technique. It populates a
DataGrid with content from the Titles table of the Pubs database that comes
with Microsoft SQL Server. The DataGrid's leftmost column contains a row of
Delete buttons. The OnDeleteRecord method simulates a record deletion by
writing the Title field of the record to be deleted to a Label control. The
OnAttachScript method, which is called once for each row in the DataGrid in
response to ItemCreated events, attaches to each button an OnClick attribute
that activates a bit of client-side JavaScript. That script displays a
confirmation dialog and prevents the page from posting back to the server
(thus preventing OnDeleteRecord from being called) if the user clicks Cancel
rather than OK.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<form runat="server">
<asp:DataGrid ID="MyDataGrid"
AutoGenerateColumns="false" CellPadding="2"
BorderWidth="1" BorderColor="lightgray"
Font-Name="Verdana" Font-Size="8pt"
GridLines="vertical" Width="90%"
<asp:ButtonColumn Text="Delete"
CommandName="Delete" />
<asp:BoundColumn HeaderText="Item ID"
DataField="title_id" />
<asp:BoundColumn HeaderText="Title"
DataField="title" />
<asp:BoundColumn HeaderText="Price"
DataField="price" DataFormatString="{0:c}"
ItemStyle-HorizontalAlign="right" />
<HeaderStyle BackColor="teal" ForeColor="white"
Font-Bold="true" />
<ItemStyle BackColor="white" ForeColor="darkblue" />
<AlternatingItemStyle BackColor="beige"
ForeColor="darkblue" />
<asp:Label ID="Output" RunAt="server" />

<script language="C#" runat="server">
void Page_Load (Object sender, EventArgs e)
if (!IsPostBack) {
SqlDataAdapter adapter = new SqlDataAdapter
("select * from titles where price != 0",
DataSet ds = new DataSet ();
adapter.Fill (ds);
MyDataGrid.DataSource = ds;
MyDataGrid.DataBind ();

void OnAttachScript (Object sender, DataGridItemEventArgs e)

if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem) {
WebControl button = (WebControl) e.Item.Cells[0].Controls[0];
button.Attributes.Add ("onclick",
"return confirm (\"Are you sure?\");");

void OnDeleteRecord (Object sender, DataGridCommandEventArgs e)

if (e.CommandName == "Delete") {
Output.Text = "Deleted \"" + e.Item.Cells[2].Text + "\"";
140. How do I localize an ASP.NET application so that it formats dates
and times based on the requestor's locale?
Ans:-Deploy the following Global.asax file in the application's virtual root:
<%@ Import Namespace="System.Threading" %>
<%@ Import Namespace="System.Globalization" %>
<script language="C#" runat="server">
void Application_BeginRequest (Object sender, EventArgs e)
try {
if (Request.UserLanguages.Length > 0) {
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture (Request.UserLanguages[0]);
catch (ArgumentException) {
// Do nothing if CreateSpecificCulture fails
Application_BeginRequest executes at the beginning of each and every
request. This example reads the requestor's preferred language from the
Request object's UserLanguage property (which is populated with information
found in the request's Accept-Language header), creates a CultureInfo object

from it, and assigns the CultureInfo object to the CurrentCulture property of
the thread that's processing the request. FCL methods that are culture-aware
(such as DateTime.ToShortDateString) will format dates, times, currency
values, and numbers accordingly.
141. What does AspCompat="true" mean and when should I use it?
Ans:-AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to
false but should be set to true in any ASPX file that creates apartment-
threaded COM objects--that is, COM objects registered
ThreadingModel=Apartment. That includes all COM objects written with Visual
Basic 6.0. AspCompat should also be set to true (regardless of threading
model) if the page creates COM objects that access intrinsic ASP objects such
as Request and Response. The following directive sets AspCompat to true:
<%@ Page AspCompat="true" %>
Setting AspCompat to true does two things. First, it makes intrinsic ASP
objects available to the COM components by placing unmanaged wrappers
around the equivalent ASP.NET objects. Second, it improves the performance
of calls that the page places to apartment-threaded COM objects by ensuring
that the page (actually, the thread that processes the request for the page)
and the COM objects it creates share an apartment. AspCompat="true" forces
ASP.NET request threads into single-threaded apartments (STAs). If those
threads create COM objects marked ThreadingModel=Apartment, then the
objects are created in the same STAs as the threads that created them.
Without AspCompat="true," request threads run in a multithreaded
apartment (MTA) and each call to an STA-based COM object incurs a
performance hit when it's marshaled across apartment boundaries.
Do not set AspCompat to true if your page uses no COM objects or if it uses
COM objects that don't access ASP intrinsic objects and that are registered
ThreadingModel=Free or ThreadingModel=Both.
142. I've developed a custom Windows Forms control that I'd like to
use in a Web Form. I've heard that ASP.NET can use Windows
Forms controls. Is that true? If so, how do I create a Windows
Forms control in a Web Form?
Ans:-You can embed Windows Forms controls in Web pages using <object> tags
similar to those that declare ActiveX controls. To demonstrate, here's the
source code for a very simple slider control-one that derives from the FCL's
TrackBar class:
namespace Wintellect
public class WebSlider : System.Windows.Forms.TrackBar {}
Compile this source code into a DLL with the following command (assuming
the source code file is named Controls.cs):
csc /t:library controls.cs
Copy the resulting DLL (Controls.dll) to the virtual directory of your choice on
your Web server. Now create a text file named Slider.aspx in the same
directory and add the following HTML:
<object id="Slider" classid="http:Controls.dll#Wintellect.WebSlider"
width="64" height="256">
<param name="Minimum" value="0">
<param name="Maximum" value="10">
<param name="Value" value="3">
<param name="Orientation" value="Vertical">
<param name="BackColor" value="gainsboro">

The <object> tag declares an instance of the control and names it Slider. It also
uses <param> tags to initialize some of the control's properties. Open the
ASPX file in your browser and the slider control should be displayed. IE
downloads the control implementation from the Web server, so you don't have
to install Controls.dll on the client. The client must, however, have the .NET
Framework installed. Internet Explorer 5.01 or higher is required on the
client, too.
143. If I use the slider control in the previous example in a Web page,
what must I do to allow a server-side event handler to determine
the position of the slider's thumb?
Ans:-The trick is to intercept the form submit event fired before the form posts
back to the server and add the thumb position to the form's postback data.
Here's a modified version of the ASPX file in the previous example that does
just that. The onsubmit attribute in the <form> tag calls the JavaScript
function SubmitForm before the form posts back to the server. SubmitForm
writes the slider's thumb position to a hidden <input> control named
__THUMBPOS. The browser submits the __THUMBPOS control's value to the
server, and the server-side event handler extracts the value from the request.
In this example, the event handler writes the thumb position to the Web
<form id="MyForm" onsubmit="javascript:return SubmitForm ();"
<input type="hidden" name="__THUMBPOS" value="" >
<object id="Slider"
width="64" height="256">
<param name="Minimum" value="0">
<param name="Maximum" value="10">
<param name="Value" value="3">
<param name="Orientation" value="Vertical">
<param name="BackColor" value="gainsboro">
<input type="submit" value="Test" onserverclick="ShowThumbPos"
<span id="Output" runat="server" />

<script language="JavaScript">
function SubmitForm ()
MyForm.__THUMBPOS.value = MyForm.Slider.value;
return true;

<script language="C#" runat="server">

void ShowThumbPos (Object sender, EventArgs e)
Output.InnerText = "You chose " + Request["__THUMBPOS"];
144. If I use the slider control in the previous example in a Web page,
the slider's thumb snaps back to its default position each time the
page posts back to the server. Is there a way to make the thumb
stay put?
Ans:-The ASPX file below shows one way to do it. The <param> tag that controls
the slider's thumb position is no longer embedded in the page's HTML;
instead, it's output programmatically with Response.Write. That enables the
page to emit a <param> tag containing a default value if the page is fetched
outside of a postback, or a <param> tag containing the __THUMBPOS value
submitted in the request if the page is being returned following a postback.
It's not pretty, but it works.
<%@ Page Language="C#" %>
<form id="MyForm" onsubmit="javascript:return SubmitForm ();"
<input type="hidden" name="__THUMBPOS" value="">
<object id="Slider" classid="http:Controls.dll#Wintellect.WebSlider"
width="64" height="256">
<param name="Minimum" value="0">
<param name="Maximum" value="10">
if (Request["__THUMBPOS"] == null)
Response.Write ("<param name=\"Value\" value=\"3\">\r\n");
Response.Write ("<param name=\"Value\" value=\"" +
Request["__THUMBPOS"] + "\">\r\n");
<param name="Orientation" value="Vertical">
<param name="BackColor" value="gainsboro">
<input type="submit" value="Test" onserverclick="ShowThumbPos"
<span id="Output" runat="server" />

<script language="JavaScript">
function SubmitForm ()
MyForm.__THUMBPOS.value = MyForm.Slider.value;
return true;

<script language="C#" runat="server">

void ShowThumbPos (Object sender, EventArgs e)
Output.InnerText = "You chose " + Request["__THUMBPOS"];

145. How can I create a DataGrid that displays a column of images
obtained from a database?
Ans:-The following ASPX file demonstrates how:
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<form runat="server">
<asp:DataGrid ID="MyDataGrid" RunAt="server"
AutoGenerateColumns="false" CellPadding="2"
BorderWidth="1" BorderColor="lightgray"
Font-Name="Verdana" Font-Size="8pt"
GridLines="vertical" Width="100%">
<asp:TemplateColumn HeaderText="Photo"
<img src='<%# "NorthwindImageGrabber.ashx?id=" +
DataBinder.Eval (Container.DataItem, "EmployeeID") %>'>
<asp:BoundColumn HeaderText="Last Name"
DataField="LastName" />
<asp:BoundColumn HeaderText="First Name"
DataField="FirstName" />
<asp:BoundColumn HeaderText="Title"
DataField="Title" />
<HeaderStyle BackColor="teal" ForeColor="white"
Font-Bold="true" />
<ItemStyle BackColor="white" ForeColor="darkblue" />
<AlternatingItemStyle BackColor="beige"
ForeColor="darkblue" />

<script language="C#" runat="server">

void Page_Load (Object sender, EventArgs e)
if (!IsPostBack) {
SqlConnection connection = new
SqlConnection ("server=localhost;database=northwind;uid=sa;pwd=");
try {
connection.Open ();
SqlCommand command = new SqlCommand ("select employeeid,
lastname, firstname, title from employees", connection);
SqlDataReader reader = command.ExecuteReader ();
MyDataGrid.DataSource = reader;

MyDataGrid.DataBind ();
finally {
connection.Close ();

This ASPX file contains a DataGrid that displays data from the Employees table of
SQL Server's Northwind database. Each row rendered by the DataGrid
represents one employee, and each row's leftmost column contains the
employee's picture. The picture comes from the table's Photo field. The image
is rendered by the <ItemTemplate> tag, which emits an <img> tag
accompanied by a src attribute that points to a file named
NorthwindImageGrabber.ashx. Inside the ASHX file is an HTTP handler that
retrieves an image from the database. A query string appended to the URL
tells the handler which image to retrieve. Here's
NorthwindImageGrabber.ashx's source code:
<%@ WebHandler Language="C#" Class="ImageGrabber" %>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data.SqlClient;
using System.IO;

public class ImageGrabber : IHttpHandler

public void ProcessRequest (HttpContext context)
string id = (string) context.Request["id"];
if (id != null) {
MemoryStream stream = new MemoryStream ();
SqlConnection connection = new SqlConnection
Bitmap bitmap = null;
Image image = null;
try {
connection.Open ();
SqlCommand cmd = new SqlCommand
("select photo from employees where employeeid='" + id + "'",
byte[] blob = (byte[]) cmd.ExecuteScalar ();
stream.Write (blob, 78, blob.Length - 78);
bitmap = new Bitmap (stream);
// Shrink the image, but maintain its aspect ratio
int width = 48;
int height = (int) (width * ((double) bitmap.Height / (double)
image = bitmap.GetThumbnailImage (width, height,
context.Response.ContentType = "image/jpeg";
image.Save (context.Response.OutputStream, ImageFormat.Jpeg);
finally {

if (image != null)
image.Dispose ();
if (bitmap != null)
bitmap.Dispose ();
stream.Close ();
connection.Close ();

public bool IsReusable

get { return true; }

The ProcessRequest method, which is called every time the ASHX file is
requested, retrieves the image from the database and returns it to the client
as a JPEG. For good measure, it also shrinks the image down to thumbnail
size using Image.GetThumbnailImage. NorthwindImageGrabber.ashx discards
the first 78 bytes of each image because the Northwind database's Photo field
doesn't store raw images; it stores BMP bitmaps prefixed by 78 bytes of
unrelated header information.
146. Is it possible to write an ASP.NET handler that works like an ISAPI
filter-that is, that sees requests and responses and perhaps
modifies them, too?
Ans:-You can do it by writing an HTTP module-a class that implements
IHttpModule-and registering it in Web.config. Here's a simple HTTP module
written in C# that appends "Hello, world" to every response:
using System;
using System.Web;

public class MyModule : IHttpModule

public void Init (HttpApplication application)
application.EndRequest += new EventHandler

void Application_EndRequest (Object source, EventArgs e)

HttpApplication application = (HttpApplication) source;
HttpContext context = application.Context;
context.Response.Write ("Hello, world");

public void Dispose ()

Here's how you register it if MyModule is in an assembly named CustomModules:
<add name="MyModule" type="MyModule, CustomModules" />

An HTTP module can handle the per-request events fired by HttpApplication
instances, and it can fire events of its own that can be processed in
Global.asax. To deploy the module, simply drop the DLL containing MyModule
into the application root's bin subdirectory.

147. How can ASP.NET apps transmit data from one page to another?
One way to transfer data from page to page is to have the sending page encode
the data in a query string and the receiving page read the data from the
request. Here's the source code for a page named PageOne.aspx that encodes
a string typed by the user in a query string and passes it to PageTwo.aspx:
<!-- PageOne.aspx -->
<form runat="server">
<asp:TextBox ID="Input" RunAt="server" />
<asp:Button Text="NextPage" OnClick="OnNextPage" RunAt="server" />

<script language="C#" runat="server">

void OnNextPage (Object sender, EventArgs e)
Response.Redirect ("PageTwo.aspx?Input=" + Input.Text);
And here's the page it redirects to, which echoes what the user typed:
<!-- PageTwo.aspx -->
<%@ Page Language="C#" %>

<% Response.Write ("You typed \"" + Request["Input"] + "\""); %>
Another way to pass data from one page to another--a technique that has the
added benefit of keeping the data on the server and not exposing it to the
user--is to pass the data in session state, as demonstrated here:
<!-- PageOne.aspx -->

<form runat="server">
<asp:TextBox ID="Input" RunAt="server" />
<asp:Button Text="NextPage" OnClick="OnNextPage" RunAt="server" />

<script language="C#" runat="server">

void OnNextPage (Object sender, EventArgs e)

Session["Input"] = Input.Text;
Response.Redirect ("PageTwo.aspx");

<!-- PageTwo.aspx -->

<%@ Page Language="C#" %>

<% Response.Write ("You typed \"" + Session["Input"] + "\""); %>
If you use Server.Transfer rather than Response.Redirect to transfer
control to another page, you can use public fields in the sending
page's code-behind class to transmit data. The following example
demonstrates how:
<!-- PageOne.aspx -->
<%@ Page Inherits="PageOneClass" %>

<form runat="server">
<asp:TextBox ID="Input" RunAt="server" />
<asp:Button Text="NextPage" OnClick="OnNextPage" RunAt="server" />
// PageOneClass.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

public class PageOneClass : Page

public string _Input;
protected TextBox Input;
public void OnNextPage (Object sender, EventArgs e)
_Input = Input.Text;
Server.Transfer ("PageTwo.aspx");
<!-- PageTwo.aspx -->
<%@ Page Language="C#" %>

PageOneClass prevpage = (PageOneClass) Context.Handler;
Response.Write ("You typed \"" + prevpage._Input + "\"");
148. How do I display an ASPX or HTML page in a new browser window

Ans:-The following tag creates a hyperlink that, when clicked, opens an ASPX file
in a new window:
<asp:HyperLink Text="Wintellect home page"
NavigateUrl="" Target="_new"
RunAt="server" />
149. How do I initialize a TextBox whose TextMode is "password" with
a password? Initializing the TextBox's Text property doesn't seem
to work.

Ans:-This won't work:

<asp:TextBox Text="imbatman" TextMode="Password" ID="Password"
RunAt="server" />
But this will:
<asp:TextBox TextMode="Password" ID="Password" RunAt="server" />
<script language="C#" runat="server">
void Page_Load (Object sender, EventArgs e)
Password.Attributes.Add ("value", "imbatman");
The latter code fragment manually adds a value="imbatman" attribute to the
<input> tag output by the TextBox control, causing the specified text to
appear in the TextBox.
You can also initialize a password TextBox by including a Value attribute in the
control tag, as demonstrated below:
<asp:TextBox Value="imbatman" TextMode="Password" ID="Password"
RunAt="server" />
150. I know I can write custom server controls by deriving from Control
or WebControl. But can I modify the behavior of existing controls
by deriving from them and modifying their output?
Ans:-You bet. Here's a custom control named NumTextBox that derives from
TextBox and adds an onkeydown attribute to the <input> tag that TextBox
outputs. That attribute references a local JavaScript function that filters out
non-numeric keys, producing a TextBox that accepts only numbers. For good
measure, NumTextBox senses the browser type and renders differently to
Internet Explorer and Netscape Navigator, enabling it to work in either
browser. It also overrides TextBox's Text property and implements a set
accessor that throws an exception if a non-numeric string is written to it.
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Wintellect
public class NumTextBox : TextBox
string IEClientScriptBlock =
"<script language=\"javascript\">\n" +
"<!--\n" +
"var keys = new Array (8, 9, 13, 33, 34, 35, " +
"36, 37, 39, 45, 46);\n" +
"function isKeyValid (keyCode)\n" + "{\n" +
" return ((keyCode >= 48 && keyCode <= 57) || " +
"isAuxKey (keyCode));\n" +
"}\n" +
"function isAuxKey (keyCode)\n" +
"{\n" +

" for (i=0; i<keys.length; i++)\n" +
" if (keyCode == keys[i])\n" +
" return true;\n" +
" return false;\n" +
"}\n" +
"-->\n" +

string NetscapeClientScriptBlock =
"<script language=\"javascript\">\n" +
"<!--\n" +
"function isKeyValid (keyCode)\n" +
"{\n" +
" return ((keyCode >= 48 && keyCode <= 57) || " +
"keyCode == 8 || keyCode == 13);\n" +
"}\n" +
"-->\n" +

public override string Text

get { return base.Text; }
// Make sure value is numeric before storing it
Convert.ToInt64 (value);
base.Text = value;

protected override void OnPreRender (EventArgs e)

string browser = Context.Request.Browser.Type.ToUpper ();
int version = Context.Request.Browser.MajorVersion;

if (browser.IndexOf ("IE") > -1 && version >= 4)

Page.RegisterClientScriptBlock ("NumTextBoxScript",
else if (browser.IndexOf ("NETSCAPE") > -1 && version >= 4)
Page.RegisterClientScriptBlock ("NumTextBoxScript",

protected override void Render (HtmlTextWriter writer)

string browser = Context.Request.Browser.Type.ToUpper ();
int version = Context.Request.Browser.MajorVersion;

if (browser.IndexOf ("IE") > -1 && version >= 4)

writer.AddAttribute ("onkeydown",
"javascript:return isKeyValid (window.event.keyCode)");
else if (browser.IndexOf ("NETSCAPE") > -1 && version >= 4)
writer.AddAttribute ("onkeydown",
"javascript:return isKeyValid (event.which)");

base.Render (writer);

Here's an ASPX file you can use to test the control. It assumes that the control is
compiled into an assembly named NumTextBoxControl.
<%@ Register TagPrefix="win" Namespace="Wintellect"
Assembly="NumTextBoxControl" %>

<form runat="server">
<win:NumTextBox runat="server" />
151. Is it possible to associate hidden values--say, values from an
identity field in a database table--with items in a DataGrid?
Ans:-You bet. Just declare a BoundColumn in the DataGrid and set its Visible
property to false, like so:
<asp:BoundColumn DataField="ItemID" Visible="false" />
The column won't show up in the DataGrid, but you'll be able to read data
from it following a postback just as if it were visible.
152. How do I configure a DataGrid to show a column of row numbers:
1, 2, 3, 4, and so on?
Ans:-The easiest way to do it is to use a TemplateColumn. The following ASPX file
demonstrates how. The TemplateColumn displays the value of a rownum field
that is incremented each time a row is output.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<form runat="server">
<asp:DataGrid ID="MyDataGrid" AutoGenerateColumns="false"
<asp:TemplateColumn HeaderText="Number" ItemStyle-
<%# rownum++ %>
<asp:BoundColumn HeaderText="Title" DataField="title" />
<HeaderStyle HorizontalAlign="center" />
<script language="C#" runat="server">
int rownum = 1;
void Page_Load (Object sender, EventArgs e)
if (!IsPostBack) {
SqlDataAdapter adapter = new SqlDataAdapter ( "select title from
titles where price != 0", "server=localhost;database=pubs;uid=sa"
DataSet ds = new DataSet ();

adapter.Fill (ds);
MyDataGrid.DataSource = ds;
MyDataGrid.DataBind ();
153. Is it possible to call Fill on a DataAdapter and fill two DataTables in
a DataSet with a single call?
Ans:-You bet. Here's a sample that demonstrates how by performing a double
query and binding each of the resulting DataTables to a different DataGrid.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<form runat="server">
<asp:DataGrid ID="DataGrid1" RunAt="server" />
<asp:DataGrid ID="DataGrid2" RunAt="server" />

<script language="C#" runat="server">

void Page_Load (Object sender, EventArgs e)
if (!IsPostBack) {
SqlDataAdapter adapter = new SqlDataAdapter (
"select * from titles; select * from authors",
DataSet ds = new DataSet ();
adapter.Fill (ds);
DataGrid1.DataSource = ds.Tables[0];
DataGrid1.DataBind ();
DataGrid2.DataSource = ds.Tables[1];
DataGrid2.DataBind ();
154. I'm trying to use Server.CreateObject to instantiate a legacy COM
component in an ASPX page. If I use VB.NET, I can create and call
the COM object just fine. But the same code written in C# doesn't
compile. The compiler complains that the method I'm calling isn't a
member of Object. What gives?
Ans:-You've discovered an interesting feature of VB.NET--namely, that it trades
type safety for simplicity when late binding to COM objects. Check out the
following VB.NET code sample, which instantiates a COM object
(ProgID="Wintellect.Math") and calls its Add method to add 2 and 2:
Dim Sum As Integer
Dim WinMath As Object
WinMath = Server.CreateObject ("Wintellect.Math")
Sum = WinMath.Add (2, 2)
This code works just fine, despite that fact that Add is not a member of
System.Object. The VB.NET compiler relaxes its type-checking rules to
simplify your code. The C# compiler, however, does not. The following
code won't compile:

Object math = Server.CreateObject ("Wintellect.Math")
int sum = WinMath.Add (2, 2)
The solution for C# programmers is to late-bind to the COM object using
System.Type.InvokeMember. Here's the C# equivalent of the VB.NET
code above:
Type t = Type.GetTypeFromProgID ("Wintellect.Math");
Object math = Server.CreateObject (t);
Object[] args = { 2, 2 };
int sum = (int) t.InvokeMember ("Add", BindingFlags.InvokeMethod, null,
math, args);
It's not pretty, but it works, and it perfectly illustrates the extra effort
required to accomplish late binding in C#.
155. I'm trying to use ASP.NET's HtmlInputFile control to upload files to
a Web server, but the control's PostedFile property is always null—
even after I select a file and post back to the server. What am I
doing wrong?
Ans:-Most likely you forgot to include an enctype="multipart/form-data"
attribute in your <form> tag.
<form enctype="multipart/form-data" runat="server">
156. ASP.NET's @ OutputCache directive lets me cache different
versions of a page based on varying input parameters, HTTP
headers, and browser types. I'd also like to be able to cache based
on varying session IDs. Is that possible?
Ans:-You bet. Here's a sample page that uses a VaryByCustom attribute to
cache different versions of a page based on session IDs:
<%@ Page Language="C#" %>
<%@ OutputCache Duration="10" VaryByParam="None"
VaryByCustom="SessionID" %>

Session["MyData"] = "Foo"; // Make the session persistent
Response.Write ("Your session ID is " + Session.SessionID);
Response.Write ("<br>");
Response.Write ("The current time is " +
DateTime.Now.ToLongTimeString ());

In order for VaryByCustom="SessionID" to work, you must include in the

application root a Global.asax file containing the following
GetVaryByCustomString method:
<script language="C#" runat="server">
public override string GetVaryByCustomString (HttpContext context, string
if (arg.ToLower () == "sessionid") {
HttpCookie cookie = context.Request.Cookies["ASP.NET_SessionId"];
if (cookie != null)
return cookie.Value;
return base.GetVaryByCustomString (context, arg);

GetVaryByCustomString is a mechanism for extending ASP.NET's page output
cache. This implementation of GetVaryByCustomString, which overrides the
one inherited from HttpApplication, responds to a VaryByCustom="SessionID"
attribute in an @ OutputCache directive by returning the current session ID, if
present. ASP.NET responds by caching different versions of the page if the
session IDs differ.
Note that GetVaryByCustomString extracts the session ID from the session
cookie, not from the session's SessionID property. That's because the request
has yet to be associated with a session when GetVaryByCustomString is
called. An unpleasant side effect is that this technique doesn't work with
cookieless session state. Also note that the page won't be cached until a user
requests the page for the second time, because the first request lacks a valid
session cookie.
157. I've noticed that DataGrids round-trip tons of information in view
state, decreasing the effective bandwidth of the connection. Is
there anything I can do to reduce the DataGrid's view state usage?
Ans:-You bet. Set the DataGrid's EnableViewState property to false, as shown
<asp:DataGrid RunAt="server" EnableViewState="false" ... />
Once you make this change, you'll also have to reinitialize the DataGrid in every
request (even during postbacks), because the DataGrid will no longer retain
its state across postbacks. In other words, instead of doing this:
void Page_Load (Object sender, EventArgs e)
if (!IsPostBack) {
// TODO: Initialize the DataGrid
Do this:
void Page_Load (Object sender, EventArgs e)
// TODO: Initialize the DataGrid
The performance you lose may be more than compensated for by the effective
bandwidth you gain--especially if instead of querying a database on every
request, you query once, cache the data, and initialize the DataGrid from the
158. Is it possible to create a DataGrid that uses scrolling rather than
paging to provide access to a long list of items?
Ans:-With a little help from a <div> tag, yes. The following ASPX file displays the
"Products" table of SQL Server's Northwind database in a scrolling table:
<%@ Import Namespace="System.Data.SqlClient" %>

<form runat="server">
<div style="height: 256px; overflow: auto">
<asp:DataGrid ID="MyDataGrid" Width="100%" RunAt="server" />

<script language="C#" runat="server">

void Page_Load (Object sender, EventArgs e)

if (!IsPostBack) {
SqlConnection connection = new SqlConnection

try {
connection.Open ();
SqlCommand command = new SqlCommand ("select * from
products", connection);
SqlDataReader reader = command.ExecuteReader ();
MyDataGrid.DataSource = reader;
MyDataGrid.DataBind ();
finally {
connection.Close ();
159. By default, ASP.NET's worker process uses the identity of a special
account named ASPNET that's created when ASP.NET is installed.
By including a user name and password in Machine.config's
element, I can configure ASP.NET to run using an account of my
choosing. However, my company has a strict policy against
encoding plaintext passwords in configuration files. I want to
specify the account that ASP.NET uses, but I also need to secure
the password. Is that possible?
Ans:-Out of the box, ASP.NET 1.0 requires the user name and password to be
encoded in plaintext in Machine.config. However, you can obtain a patch from
Microsoft that allows the user name and password to be stored in encrypted
form in a secure registry key that's off limits to non-administrators. The hotfix
also allows you to secure the credentials used to access ASP.NET's ASPState
database when using SQL Server to store session state.
You'll find instructions for obtaining the hotfix (and information about a helper
utility that encrypts user names and passwords for you) at;en-us;Q329250.
Microsoft plans to build the hotfix into the "Everett" release of the .NET
Framework, which will ship with Windows .NET Server. Be aware, however,
that Windows .NET Server comes with IIS 6.0, which supports an alternative
means for securing process credentials. Applications can be assigned to
arbitrary application pools, and application pools can be assigned unique
identities using encrypted credentials stored in the IIS metabase. As Microsoft
security guru Erik Olsen recently noted, this is probably the better long-term
direction for companies whose policies prevent them from storing plaintext
credentials in CONFIG files.
160. I want to make DataGrid paging more efficient by using custom
paging. Oracle makes custom paging easy by supporting query-by-
row-number. SQL Server is just the opposite. There's no obvious
way to ask SQL Server for, say, rows 101-150 in a 500-row result
set. What's the best way to do custom paging when you have SQL
Server on the back end?
Ans:-You can use a query of the following form to retrieve records by row
number from Microsoft SQL Server:

Replace {0} with the page size (the number of records displayed on each
page), {1} with the page size * page number (1-based),
{2} with the name of the table you wish to query, and {3} with a field name.
The following example retrieves rows 41-50 from the
"Products" table of the Northwind database:
Products ORDER BY ProductID) AS t1 ORDER BY ProductID DESC)
AS t2 ORDER BY ProductID
You can combine this query technique with custom paging to make
DataGrid paging more efficient. With default paging, you must initialize
the data source with all records displayed on all pages. With custom
paging, you can initialize the data source with just those records that
pertain to the current page.
161. Is it possible to prevent a Web form from scrolling to the top of the
page when it posts back to the server?
Ans:-One way to do it is to add a SmartNavigation="true" attribute to the
page's @ Page directive. That requires Internet Explorer 5.0 or higher on the
client. To prevent unwanted scrolling in a wider range of browsers, you can
use a server-side script that generates client-side script. The first step is to
replace the page's <body> tag with the following statements:
if (Request["__SCROLLPOS"] != null &&
Request["__SCROLLPOS"] != String.Empty) {
int pos = Convert.ToInt32 (Request["__SCROLLPOS"]);
Response.Write ("<body id=\"theBody\" "
+ "onscroll=\"javascript:document.forms[0].__SCROLLPOS.value = " +
"theBody.scrollTop;\" " +
"onload=\"javascript:theBody.scrollTop=" + pos + ";\">");
else {
Response.Write ("<body id=\"theBody\" " +
"onscroll=\"javascript:document.forms[0].__SCROLLPOS.value =" +
Step two is to add the following line somewhere between the <form
runat="server"> and </form> tags:
<input type="hidden" name="__SCROLLPOS" value="" />
How does it work? The server-side script block outputs a <body> tag containing
an onscroll attribute that keeps tabs on the scroll position and an onload
attribute that restores the last scroll position following a postback. The scroll
position is transmitted to the server in a hidden <input> control named
__SCROLLPOS. Note that this technique is compatible with Internet Explorer
but not with Netscape Navigator.
162. If I use the same user control in two different pages and include
an @ OutputCache directive in the ASCX file, will the user control
be cached once or twice?
Ans:-In ASP.NET version 1.0, the control will be cached twice. In version 1.1, you
can include a Shared="true" attribute in the @ OutputCache directive to
cache the control just once.
163. How do I set the focus to a specific control when a Web form
Ans:-With a dash of client-side script. Upon loading, the following page sets the
focus to the first of its three TextBox controls:

<form runat="server">
<asp:TextBox ID="TextBox1" RunAt="server" /><br>
<asp:TextBox ID="TextBox2" RunAt="server" /><br>
<asp:TextBox ID="TextBox3" RunAt="server" />
<script language="javascript">
document.forms[0].TextBox1.focus ();
164. Is it possible to post a page containing a runat="server" form to a
page other than itself? Adding an action attribute to the <form>
tag is futile because ASP.NET overrides it with an action attribute
that points back to the same page.
Ans:-ASP.NET forbids a runat="server" form from posting back to another page,
but you may be able to accomplish what you're after by taking a slightly
different approach. It turns out that if you remove runat="server" from the
<form> tag, ASP.NET won't alter the tag's action attribute. The bad news is
that a form lacking a runat="server" attribute can't host Web controls. The
good news is that it can host HTML controls, which means that if you can do
without DataGrids and other rich controls, you can post back to other pages
just fine.
165. When configured to store session state in a SQL Server database,
ASP.NET stores sessions in the Tempdb database, which means
sessions are lost if the database server is rebooted. Is it possible
to configure ASP.NET to store session in the ASPState database
instead for added robustness?
Ans:-You bet. Read Microsoft Knowledge Base article 311209, which is titled
"Configure ASP.NET for Persistent SQL Server Session State Management"
and located at;EN-
US;q311209. The article contains a link for downloading
InstallPersistSqlState.sql, an installation script that creates the ASPState
database and configures it to store session data in ASPState tables rather
than Tempdb tables. This simple configuration change enables session state to
survive server restarts and is a boon for small- and medium-size sites that
can't justify building clustered arrays of database servers on the back end.
166. I'm using an <error> element in Web.config to redirect to a
custom error page when a 404 error occurs. Inside the error page,
I want to retrieve the URL that caused the 404 error so I can write
it to a log file. How do I get that URL?
Ans:-When ASP.NET redirects to a custom error page, it passes the original URL
(the one that caused the error) in a query string. Here's an example in which
PageNotFound.aspx is the custom error page and foo.aspx is the page that
produced the error:
PageNotFound.aspx can therefore obtain the URL of the page that generated the
error (in your case, the nonexistent page that resulted in a 404 error) like
string badurl = Request["aspxerrorpath"];
If you'd like to retrieve the IP address from which the request originated for
logging purposes as well, read it from
Request.ServerVariables["REMOTE_ADDR"] or Request.UserHostAddress.

167. How does System.Web.UI.Page's IsPostBack property work? How
does it determine whether a request is a postback?
Ans:-IsPostBack checks to see whether the HTTP request is accompanied by
postback data containing a __VIEWSTATE or __EVENTTARGET parameter. No
parameters, no postback.
168. Forms authentication protects ASPX files and other resources
owned by ASP.NET, but it does not restrict access to HTML files and
other non-ASP.NET resources. Is it possible to extend forms
authentication to protect ordinary HTML files and other resources
that don't belong to ASP.NET?
Ans:-The best way to do it is map *.htm, *.html, and other file name extensions
to Aspnet_isapi.dll in the IIS metabase. (You can use the IIS configuration
manager to do the mapping.) Transferring ownership of these resources to
ASP.NET degrades performance a bit, but it might be worth it for the added
169. How do I build a DataGrid that contains a column of check boxes?
Ans:-The column of check boxes is created easily enough with a
TemplateColumn. What's not so obvious is how to read the state of the
check boxes following a postback. The solution is to reach into the DataGrid
and extract references to the check boxes. The sample below, which uses the
"Titles" table of SQL Server's pubs database to populate a DataGrid,
demonstrates how it's done. Click the push button and a list of all the titles
with check marks next to them appears at the bottom of the page.
<%@ Import Namespace="System.Data.SqlClient" %>
<form runat="server">
<asp:DataGrid ID="MyDataGrid" RunAt="server"
AutoGenerateColumns="false" CellPadding="2"
BorderWidth="1" BorderColor="lightgray"
Font-Name="Verdana" Font-Size="8pt"
GridLines="vertical" Width="100%">
<asp:TemplateColumn HeaderText="Buy"
<asp:CheckBox RunAt="server" />
<asp:BoundColumn HeaderText="Title" DataField="title" />
<asp:BoundColumn HeaderText="Price"
DataField="price" DataFormatString="{0:c}"
ItemStyle-HorizontalAlign="right" />
<HeaderStyle BackColor="teal" ForeColor="white"
Font-Bold="true" HorizontalAlign="center" />
<ItemStyle BackColor="white" ForeColor="darkblue" />
<AlternatingItemStyle BackColor="beige" ForeColor="darkblue" />
<asp:Button Text="Check Out" OnClick="OnCheckOut" RunAt="server"
<asp:Label ID="Output" RunAt="server" />

<script language="C#" runat="server">
void Page_Load (Object sender, EventArgs e)
if (!IsPostBack) {
SqlConnection connection = new SqlConnection

try {
connection.Open ();
SqlCommand command = new SqlCommand
("select * from titles where price != 0", connection);
SqlDataReader reader = command.ExecuteReader ();
MyDataGrid.DataSource = reader;
MyDataGrid.DataBind ();
finally {
connection.Close ();

void OnCheckOut (Object sender, EventArgs e)

StringBuilder builder = new StringBuilder (1024);
foreach (DataGridItem item in MyDataGrid.Items) {
if (item.ItemType == ListItemType.Item ||
item.ItemType == ListItemType.AlternatingItem) {
CheckBox box = (CheckBox) item.Cells[0].Controls[1];
if (box.Checked) {
builder.Append (item.Cells[1].Text);
builder.Append ("<br>");

Output.Text = builder.ToString ();

170. I'm dynamically adding columns to a DataGrid at run-time, but am
finding that the DataGrid's events don't fire properly.
Interestingly, if I define the columns statically, the events work
just fine. Any idea what I'm doing wrong?
Ans:-You're probably adding the columns to the DataGrid in Page_Load. Add
them in Page_Init instead and the events will fire just fine. In general,
Page_Init is the ideal place to modify the page and its controls, while
Page_Load is the place to modify control state. Keep this simple dictum in
mind and you'll save yourself a lot of headaches down the road.
171. When hosting a Windows Forms control in a Web page, is it
possible to connect the control's events to a handler implemented
in client-side script?
Ans:-You bet. But you, the control developer, have to do a little work to allow it
to happen. Here's a summary of the steps required:
Declare in the control DLL an interface containing methods whose names and
signatures match the events you wish to expose to client-side script.
Attribute the interface [InterfaceType

(ComInterfaceType.InterfaceIsDispatch)] so the Framework will expose it
as an IDispatch interface to COM clients. Use [DispId] attributes to assign
each of the interface's methods a unique dispatch ID.
Adorn the control class with a [ComSourceInterfaces] attribute naming the
interface defined in step 1. This instructs the Framework to expose the
interface's methods to COM clients as COM events.
Grant the assembly containing the control (the control DLL) full trust on the
client. You can use the Microsoft .NET Framework Wizards found in
Control Panel/Administrative Tools to grant the assembly full trust.
To demonstrate, here's a WebSlider control whose Scroll events (which are
inherited from and fired by the TrackBar base class) can be processed in a
using System;
using System.Runtime.InteropServices;
namespace Wintellect
[ComSourceInterfaces (typeof (IWebSliderEvents))]
public class WebSlider : System.Windows.Forms.TrackBar {}
[InterfaceType (ComInterfaceType.InterfaceIsIDispatch)]
public interface IWebSliderEvents
[DispId (1)] void Scroll (Object sender, EventArgs e);
And here's a Web page that you can use to test the control and prove that you
can respond to its events in client-side script:
<form id="MyForm">
<object id="Slider" classid="http:WebSlider2.dll#Wintellect.WebSlider"
width="64" height="256">
<param name="Minimum" value="0">
<param name="Maximum" value="10">
<param name="Value" value="0">
<param name="Orientation" value="Vertical">
<param name="BackColor" value="gainsboro">
<span id="Output" runat="server">0</span>

<script for="Slider" event="Scroll (source, args)" language="javascript">

Output.innerText = MyForm.Slider.value;
As you move the slider's thumb, the client-side event handler continually
updates the positional value beneath the slider to reflect the thumb's latest
172. How does ASP.NET generate session IDs? Are they random?
Predictable session IDs increase the risk of session hijacking.
Ans:-ASP.NET uses random, non-sequential session IDs. Specifically, it uses the
FCL's System.Security.Cryptography.RNGCryptoService Provider class
to generate highly random 120-bit session IDs. Sessions can still be hijacked
by stealing session cookies or, if cookieless session state is being used, by
reading session IDs from the browser's address bar. But ASP.NET's use of

random session IDs should preclude the possibility of hijacking sessions by
guessing session IDs.
173. How can I get the name of the Windows security principal that a
request is executing as? Page.User.Identity.Name is no help at all
when forms authentication is used.
Ans:-The best way to do it is to use P/Invoke to call the Win32
GetUserName function. The ASPX file below demonstrates how. In order for
this to work, your code must be running with a high-enough trust level to
permit callouts to unmanaged code.
<%@ Import Namespace="System.Runtime.InteropServices" %>
<asp:Label ID="Output" RunAt="server" />

<script language="C#" runat="server">

[DllImport ("Advapi32.dll")]
static extern bool GetUserName (StringBuilder name, ref int size);

void Page_Load (Object sender, EventArgs e)

StringBuilder name = new StringBuilder (1024);
int size = name.Capacity;
if (GetUserName (name, ref size))
Output.Text = name.ToString ();
174. Is it possible to generate the source code for an ASP.NET Web
service from a WSDL contract?
wsdl /server
Wsdl.exe responds by generating a CS file containing a WebService-derived
base class that you can further derive from to implement a Web service.
The Wsdl.exe-generated class contains abstract methods representing the
Web methods described in the WSDL document; you'll need to override
and implement these methods in your derived class. You must also
manually copy the attributes in the Wsdl.exe-generated source code file
to the corresponding elements in your source code file.
175. When I call DataAdapter.Fill to fill a DataTable, the data comes
back just fine, but any constraints placed on that data in the
database do not. For example, if the table I query contains a
unique key constraint, the resulting DataTable does not. If I
modify the DataTable and violate a constraint, I don't learn about
my mistake until I call DataAdapter.Update. Is there a reasonable
way to read constraints from a database and apply them to a
Ans:-There is: it's called FillSchema. The page below demonstrates its use. The
record added to the DataTable violates a uniqueness constraint because the
"title_id" of the Pubs database's "titles" table is a primary key and it already
contains a record with a "title_id" value of TC7777. Thanks to FillSchema, the
call to Rows.Add throws an exception.
SqlDataAdapter adapter = new SqlDataAdapter ( "select * from
titles", "server=localhost;database=pubs;uid=sa");
DataSet ds = new DataSet ();
adapter.Fill (ds, "Titles");

DataTable table = ds.Tables["Titles"];
adapter.FillSchema (table, SchemaType.Mapped);
DataRow row = table.NewRow ();
row["title_id"] = "TC7777";
row["title"] = "Programming Microsoft .NET";
row["price"] = "59.99";
row["ytd_sales"] = "1000000";
row["type"] = "business";
row["pubdate"] = "May 2002";
table.Rows.Add (row); // Get ready for an exception!
As an aside, you generally want to call FillSchema after DataAdapter.Fill, not
before. Placing constraints on a DataTable before filling it slows down the
176. I'm using Windows authentication in an ASP.NET intranet app to
identify callers, and Windows authentication to authenticate
callers to a back-end SQL Server database. However, it doesn't
work: the caller's credentials are apparently not being propagated
to the database. What's wrong?
Ans:-I'll bet you're using Integrated Windows Authentication (IWA) to
authenticate callers, and if that's the case, you've encountered the famous
Windows "one-hop" problem. By default, Windows only allows security
credentials to travel one hop over the network. If you're using IWA, you use
up your one hop going from the browser to the Web server. Several solutions
exist, but none are perfect. The best solution, assuming you want to continue
using IWA, is to enable delegation. Here are some links to articles with more
177. I'm using a SqlDataAdapter to update my database and a
SqlCommandBuilder to generate INSERT, UPDATE, and DELETE
commands. Everything works fine until I try to update a table that
has spaces in its name. Then, SqlDataAdapter.Update throws a
SqlException. Why does this happen, and how do I fix it?
Ans:-The problem is that CommandBuilder isn't smart enough to figure out that
table names with embedded spaces must be delimited with special characters
such as [ and ], even if your SELECT statement contains a table name
surrounded by those characters. The solution lies in CommandBuilder's
QuotePrefix and QuoteSuffix properties. A CommandBuilder used this way will
fail when it encounters a table whose name includes spaces:
SqlCommandBuilder builder = new SqlCommandBuilder (adapter);
adapter.Update (table);
But a CommandBuilder used this way will work just fine with most databases:
SqlCommandBuilder builder = new SqlCommandBuilder (adapter);
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
adapter.Update (table);
178. How can I use ASP.NET validation controls to check for leading and
trailing spaces in user input and display an error message if either
is present?
Ans:-function __checkLeadingAndTrailingSpaces (source, args)
args.IsValid = !((args.Value.charAt (0) == ' ') |
(args.Value.charAt (args.Value.length - 1) == ' '));

179. Why do uploads fail when I use an ASP.NET file upload control to
upload large files?
Ans:-ASP.NET limits the size of requests (and therefore file uploads) as a
precaution against denial-of-service attacks. By default, ASP.NET won't accept
requests whose size exceeds 4 MB. You can change that by modifying the
maxRequestLength attribute of Machine.config's <httpRuntime> element. The
following maxRequestLength attribute expands the permissible request size to
8 MB (8192K):
<httpRuntime ... maxRequestLength="8192" ... />
180. I upgraded my company's Web server to ASP.NET 1.1 and it broke
one of my apps. Can I revert to ASP.NET 1.0 for that application
and leave others running under 1.1?
Ans:-You bet. Simply modify the IIS metabase to point that application to version
1.0.3705 of Aspnet_isapi.dll instead of version 1.1.4322. The easy way to do
it is to run the Aspnet_regiis utility that came with version 1.0 of the .NET
Framework. The following command uses Aspnet_regiis to configure the
application in the virtual directory named MyApp to use ASP.NET 1.0:
Aspnet_regiis -sn w3svc/1/root/myapp
If you later decide to migrate the application to ASP.NET 1.1, simply repeat
the command, but this time use the Aspnet_regiis utility that came with
version 1.1.
181. Can an ASP.NET app figure out at run-time what version of
ASP.NET it's hosted by?
Ans:-Yes, by reading the static Version property of the Framework's
System.Environment class.
void Page_Load (Object sender, EventArgs e)
Output.Text = String.Format ("This page is using ASP.NET {0}.{1}",
Environment.Version.Major, Environment.Version.Minor);

Should you need them, build and revision numbers are also present in the
System.Version object returned by the property's get accessor.
182. ASP.NET suddenly stopped working on my Web server. Every
attempt to fetch a page results in a "Server Application
Unavailable" error. What's wrong, and how do I fix it?
Ans:-This is a symptom of a problem that occurs when you install recent
Windows security updates (specifically, Security Update MS02-32 and possibly
later updates, too) on Web servers running ASP.NET 1.0. It doesn't affect
ASP.NET 1.1.
183. What platforms do .NET XML Web Services run on?
Ans:-Currently, they're supported on Windows 2000 and Windows XP. ASP.NET
integrates with Internet Information Server (IIS) and thus requires that IIS
be installed. It runs on server and non-server editions of Windows 2000 and
XP as long as IIS is installed.
184. Can two different programming languages be mixed in a single
ASMX file?
185. How do I require a SOAP Header when designing my Web Service?
Ans:-.NET is rich with classes and Web Service support, and SOAP Headers are
but another example. Following up with the authentication theme... The first
thing to do is create a class that will represent the header:
public class AuthToken : SoapHeader

protected string m_strAuthToken;
public AuthToken ()
m_strAuthToken = "";

public string Token

get { return m_strAuthToken; }
set { m_strAuthToken = value; }
As it happens, SOAP Headers within the .NET Framework are actually
implemented as attributes of the Web Method. Therefore, within your Web
Service class you'll create an instance of the header class that may be
referenced by each interested Web Method:
public class Service1 : System.Web.Services.WebService
public AuthToken m_authToken;


public string MyBillableWebMethod()
m_authToken.DidUnderstand = true; // else SoapFault!
if ( !Authenticate(m_authToken.Token) )
return "";
// Continue processing...
Note that we needed to inform .NET that we, in fact, did understand the SOAP
header or .NET will throw the requisite SOAP Fault (if we didn't do this, to
.NET's way of thinking SOAP's mustUnderstand constraint wasn't met). You
will also need to provide an implementation for Authenticate() to actually
validate the authentication token.
186. How do I provide information to the Web Service when the
information is required as a SOAP Header?
Ans:-The key here is the Web Service proxy you created using wsdl.exe or
through Visual Studio .NET's Add Web Reference menu option. If you happen
to download a WSDL file for a Web Service that requires a SOAP header, .NET
will create a SoapHeader class in the proxy source file. Using the previous
public class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol {
public AuthToken AuthTokenValue;
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://tempur", IsNullable=false)]
public class AuthToken : SoapHeader {
public string Token;

In this case, when you create an instance of the proxy in your main
application file, you'll also create an instance of the AuthToken class and
assign the string:
Service1 objSvc = new Service1();
// Create the header itself. This header will go to the
// Web Service for processing
objSvc.AuthTokenValue = new AuthToken();
objSvc.AuthTokenValue.Token = <actual token value>;
// Call the Web Service
string strResult = objSvc.MyBillableWebMethod();
.NET will make sure the SOAP Header is created and filled with the
authentication token's value
187. Which ASP.NET configuration options are supported in the ASP.NET
implementation on the shared web hosting platform?
Ans:-Many of the ASP.NET configuration options are not configurable at the site,
application or subdirectory level on the shared hosting platform. Certain
options can affect the security, performance and stability of the server and,
therefore cannot be changed. The following settings are the only ones that
can be changed in your site’s web.config file(s):
browserCaps, clientTarget, pages, customErrors, globalization, authorization,
authentication, webControls, webServices
188. Are CodeBehind pages supported on the shared hosting platform?
Ans:-Yes, CodeBehind pages are supported in shared web hosting
189. Is there any change to the global.asax file?
Ans:-No, it is the same as the global.asa found today. .NET does,
however, introduce a new file called "web.config" to set parameters for
your site.
190. What will be the role of ATL and COM in the new .NET
technologies? What about emerging technologies such as WTL?
Ans:-ATL will have no role whatsoever in writing Microsoft .NET applications. COM
won’t be a player there either, although it’s interesting to note that .NET
began its life as COM+ 2.0. Microsoft .NET is a logical evolution of COM, but
to describe it that way hardly does it justice. .NET is much broader in scope
than COM ever was.
WTL won’t rise to prominence unless Microsoft wants it to. And all indications
are that it doesn’t. Microsoft’s energies right now are being directed toward
helping us write better Internet apps, not better desktop apps. WTL was an
interesting experiment and would probably foreshadow what MFC would look
like if it were rewritten to use templates. But it’s unikely that will that MFC will
be rewritten or that WTL will be further developed.
191. In your opinion, what is the future of MFC?
Ans:-If you’re writing traditional desktop-style Windows applications, MFC is still
a fine way to go about it—and probably will be for some time to come. But do
I think developers will be writing a lot of new MFC code five years from now?
No. We’ll be using better tools (hopefully) to write a more diverse assortment
of apps (particularly Web apps) that target platforms like .NET and, of course,
that leverage the Internet. Microsoft has demonstrated no interest in giving
MFC the radical retooling it would need to adapt to this new world order.
192. Do you have any idea how MS will protect intellectual property in
the new .NET runtime—especially since we are provided with a
Ans:-Like Java byte code, IL is rather easy to reverse engineer. As far as I know,
Microsoft has no plans to protect the IL code that a compiler generates.
Microsoft apparently will provide a “pre-JITter” which would enable you to

compile IL to machine code. You’d lose platform independence, but you’d be
able to hide your code.
193. Windows dominates the software industry today, but do you think
its perceived flaws (cost, constant upgrades, stability) will make
Linux more popular in the future. What is your opinion on the
future of operating systems?
Ans:-I think people tend to overemphasize Windows’ instability and
underemphasize Linux’s weaknesses. IMHO, Windows NT/2000 is a well-
designed operating system that is extraordinarily stable given the broad range
of tasks it’s asked to perform and the wide variety of hardware that it runs
on. I have nothing against Linux, but I’ve met people who are religious in
their hatred of Windows. Go figure.
On the future of operating systems, it seems we’ll be moving towards
environments such as .NET and Java that layer run-times on top of operating
systems. The underlying OSes will be abstracted away more and more as run-
times (and the class libraries that we use to program them) become the
target of the code that we write.
194. Will we be able to write apps in .NET (ie using managed code etc)
that will run outside of .NET - say, on Windows 98?
Ans:-Microsoft plans to make the .NET run-time available on down-level
operating systems, including Windows 95 and Windows 98. So yes, you’ll be
able to run it on Win9x. But no, you won’t be running it “outside of .NET.”
195. Why shouldn't I rely on VB runtime regarding objects release?
Ans:-VB takes care to release the memory used by any variable when it goes out
of scope, nevertheless it's better to Set explicitely your objects to Nothing for
the following reasons:
It's a good programming techinique, this habitude could turn usefull if it
happens you to program in C++.
It's better to release resources when you don't need them anymore, without
waiting they go out of scope, this is expecially true if the objects keep DB
connections open.
There are (yet ?) some ADO bugs that gives some problems (loss of
information in the Err object) if you don't have set ADO objects explicitely
to Nothing before raising an error.
Close Recordsets and Connections objects before setting them to Nothing, or
connection pooling won't work correctly.
196. Basic IDL syntax and mapping to VB class-module settings
Ans:-Although COM is "just" a binary layout definition, IDL has become the "C-
like" lingua franca of COM interface and class definition. IDL is processed by
MIDL.EXE to produce marshaling code (necessary for non automation
compliant interfaces), header definition (for C++) and type library (for VB).
Here is an IDL example
import "oaidl.idl";
import "ocidl.idl";
helpstring("IMYClass Interface"),
interface IMYClass : IDispatch
[id(1), helpstring("method MyMethod")]
[in] BSTR MYString, [in,out] long* MyLong,[out,retval] VARIANT_BOOL*


helpstring("MyCOMServer 1.0 Type Library")

helpstring("MYClass Class")
coclass MYClass
[default] interface IMYClass;

Note that only what is inside the library block (or is referenced in the library
block) is brought into the type-library.
In this sample the library decribes a COM Object named MYClass ([coclass])
that implements the IMYClass interface. In VB you map such "standard" COM
definition declaring a Class module as Multiuse. PrivateNotCreatable classes
are mapped to IDL tagging the [coclass] with the NonCreatable keyword. To
get a pointer to such interfaces there must be another Multiuse in the same
component (so that it knows how to create the COM object) that creates the
PublicNotCreatable object, asks for one of its interface and passes it out of
the component via a method parameter. When you mark a class as Public not
Creatable VB do more then this: it removes the InprocServer entry in the
registry under the class CLSID; in this way the COM runtime has no way to
create the class, even from languages like C++ that ignores the coclass
section of IDL. I just recently realized that the whole coclass section are just
for documentation purpouses and for VB clients.Not creatable is an example,
another example is the source tag to let VB know what is the default (actually
the only VB can access) sink interface of the object (the default sink interface
contains the events you define for the class in VB).
Private classes does not appear in IDL at all.
GlobalMultiuse classes: such classes have the appobject tag in the [coclass]
definition. Such tag is just for VB use. A GlobalMultiuse class is a class
whose methods you can invoke directly without creating the object
explicitely. You can do this cause VB silently creates the object on your
behalf the first time you invoke a method of such class. GlobalMultiuse
classes are highly un-reccomended in MTS. For ActiveX EXE only:
SingleUse: This has nothing to do with Object definition (that it, this setting
does not map to any IDL setting). The effect of this setting is to run a
different new process hosting the COM object for each requested instance
of the object. In other words, as the MSDN states, for such classes once
an application is connected to the class object with CoGetClassObject, the
class object is removed from public view so that no other applications can
connect to it.
197. A few words about COM threading models

Ans:-In COM objects live in apartments. There are at present 2 kinds of
apartments available:
Single Threaded Apartments (STA)- Multi Threaded Apartments (MTA)A third
one will be in W2k: Neutral Threading Apartment. VB 7 (SPx) maybe will
support it.
In an STA there is just 1 thread running, it loops in an hidden window
message pump waiting for dispatching method calls to objects living in
the STA. There is no limit in the number of objects that can be in an STA.
There is no limit in the number of STA that can be in a process. Since
there is only one thread for all the objects that live in a specific
STA, when an object is running into a method call all requests for other
objects are blocked (there is support for re-entrancy
(callbacks)anyway).Thus in this case there are no syncronization issues at
class level. However if you are developing in C++,you still have to protect
datas at module level. If you are developing in VB there is no such
problem since variables declared in .bas are not really at module level,
they are thread (thus apartment) specific since they are stored in TLS
(thread local storage).
In an MTA there is a pool of threads running, waiting to serve incoming calls.
In this case Syncronization is an issue. You have to deal with OS
syncronization primitives such Mutexes, Semaphore, Critical Sections, etc
There can be just one MTA per process.
A COM object declares to the COM runtime its apartment requirements via the
ThreadingModel key under the object's CLSID in the registry. These are
the possible entries for this key:
no ThreadingModel entry : The object will be put in the Main STA (a
"special" STA, the first one created in the process)
Apartment : The object will be put in an STA. The same one of the caller if
the caller is in an STA yet, if not (that is the caller is in an MTA) a new
STA will be created (or it will be put in an existing one).
Free : the object will be put in an MTA
Both : the COM run-time will put the object in an MTA or STA, depending on
what type of apartment the caller is.
198. How do I overcome VB's limits of the binary compatibility
settings ?
Ans:-Among the different COM details that VB hides to the programmers, one of
the most problematic one is that it doesn't let you take control on the
interface GUIDs. Via the binary compatibility settings VB tries to force you
follow COM rules (as a fact breaking such rules with the interface foward
mechanism it silently implements when you add a method to a class). In any
case VB support in Interface definition and maintenance is definetely lacking
when you have to design and implement large COM based systems.
199. A few words about Byref / ByVal - Standard marshaling / Custom
Marshaling By Value
Ans:-There is quite a lot of misunderstanding in the VB-COM "newbie" comunity,
about what happens underneath when a COM interfaces is passed as method
parameters. As in most of the cases VB programmers are hidden/protected
about a lot of details on the COM run-time, but you do have to know such
details if you want to assemble something that perform decently in a
distributed environment.
Basic automation types (double,long,string) are passed by value if the
method signature is declared byval. They are passed by reference if the
method signature is declared byref. The behviour you experience is the
same if the method call takes place in-Apartment or cross-Apartment.

COM Interfaces: The first thing to stress here is that in VB (or in any COM
aware language) you never get in touch with a Class (the client doesn't
have to know the class binary layout ! ), you get in touch with interfaces.
So when 'you' think to pass an "object" you are actually passing an
interface. The 'state' of underlying COM object that is behind the interface
is not copied (e.g. as a struct (type) is).
Now, coming to the point: COM Interfaces are passed
a) by reference if the method signature is declared byval
b) by a reference to a reference if the method signature is declared
to see this i show here the mapping between a VB method signature and the
underlying IDL
public sub test(byval a1 as IMyInterface1,byref a2 as IMyinterface2)
->HRESULT test([in] IMyInterface* a1,[in,out] IMyInterface2** a2);
This means that, even if you pass an interface byval, you don't have to be
surprised that, on returning from the method call, one of its properties
have been changed. Someone may ask where byref makes the difference:
Passing an interface byref let the callee replace the object behind the
interface with another object that implements the same interface.
CFastAnimal and CSlowAnimal both implement the interface IRun
CSomething implements IPrepareToRun. IprepareToRun has to methods :
preparebyref and preparebyval, where, as you may guess,
the former is
public sub preparebyref(byref a1 as IRun)
set a1 = Createobject("CSlowAnimal") = "AAA"
end sub
the latter is
public sub preparebyval(byval a1 as IRun)
set a1 = Createobject("CSlowAnimal") = "AAA"
end sub
sub a()
dim x as IRun
set x = createobject("CFastAnimal") ="BBB"
dim y as IPrepareToRun
set y =createobject("CSomething")
y.preparebyref(x) ''RUNS SLOW
debug.print 'PRINT "AA"
end sub
sub b()
dim x as IRun
set x = createobject("CFastAnimal") ="BBB"
dim y as IPrepareToRun
set y =createobject("CSomething")
y.preparebyval(x) 'RUNS FAST
debug.print 'PRINT "AA"
end sub

You experience the same behaviour described above if you pass Interfaces in-
Apartment / or cross-Apartment (Cross Process / Cross Host) if such interface
are standard marshaled (Type-Library marshaling).I should stress however
that passing interfaces across apartment boundaries is very bad design
(expecially across hosts): reading or setting a property involves a network
roundtrip. There are somecases where you may need to pass an interface for
a callback, but NEVER use an interface as a method to pass/return data
among two objects if you are not sure the 2 objects AND the interface in
question will always be in the same apartment. OK, i said never, now i correct
myself, there is an execption: you can do it if the interface implements MBV
(Marshaling by value), and , yes, ADO disconnected Recordsets do implement
marshaling by value: This means that when the _Recordset interface cross
apartment boundaries the data behind the recordset are copied in the new
apartment. If the parameter is declared byref, then the data are copied
back. BUT rememeber this happens only if the recordset cross apartment
boundaries, if it's not the case you get the standard COM behaviour.

200. Can I store Interface pointers in the SPM ?

Ans:-No, you can't !! the SPM is unaware of Apartment marshaling issues.If you
ask the SPM for an interface pointer while running in an aprtment that is
different from the one where the interface pointer resides the SPM will blindly
pass you the rough interface pointer without marshaling it, thus violating COM
rules (and your app will randomly fail). Park the interface pointer in the GIT
and park the GIT cookie in the SPM.
201. Binary Compatibility of components
Ans:-When you decide to issue a new version of an MTS component you should
take care of its compatibility with the previous version. There are three types
of changes you could make:
1) You change only internal code of a component, keeping the interface that
the component provides untouched.
2) You only add a member(s) (method, property, enum etc.) to the interface,
but leave declaration of previously declared members quite the same.
3) You decided to revise the interface members and some of them are
changed or even removed.
Thus, if you're building a component in VB it's strongly recommended to set
Version Compatibility of the project to Binary Compatibility mode. In this
case VB will track the changes of the interface(s) and will notify you if you
make changes of type (3), but not 2 ! To install a new version into MTS
you should do the following: For changes of type (1) you can simply
overwrite the older DLL with the newer one. The remote clients that had
the client export registered need no intervention, but with both (2) and
(3) types of changes you should completely reinstall the component (i.e.
remove it from MTS and then install it back), you then need to re-export
the package and have the remote clients run the client installation again
(remove the old one before from Control Panel/Install remove
applications).Don't forget to shut the component's package down to
unlock components' DLLs. It's possible to shut a package down remotely
and perform other administration operations "programmatically" (see
MTS2.0 Admin Type Library)
202. Why is dangerous the use of the New keyword in VB to create COM
objects registrered under MTS ?
Ans:-The New keyword is the only way to go when you want to create objects
that are defined as PublicnotCreatable or Private (CreateObject doesn't work).
As you know VB lets you use New to create Multiuse classes as well.
Unfortunately the New keyword has a couple of drawbacks:

In the situation where the caller and the callee are in the same EXE/DLL COM
component VB perform an internal creation of the COM object bypassing
the COM run-time (and the MTS run-time if the object is registered under
While this fact is not a problem under out-of-MTS development, the situation
gets very dangerous under MTS. What happens is that, since MTS is not
notified of the object creation, the newly created object gets access to the
ObjectContext of the father and MTS sees the code running inside method
calls of the child object as "inline-code" of the father. I leave as an
excercise to the reader what can happen if the child object calls
SetComplete (against the ObjectContext of the father).
When you declare an object (Interface) with the syntax
Dim x as new xx
VB checks every time the object is referenced in the code. If it is Nothing VB
silently (re)creates it (This means you'll never get a "object variable or
with block not set" error). If you are not aware of this your code could
follow unxexpected execution paths.
Consider the following code:
Public sub DoWork()
dim x as new XX XX is registered as requires transaction
x.dosomemorework Vb creates it, the component ball start spinning in the
MTS explorer, the transaction start
set x = nothing The ball stop spinning
if x is nothing then VB recreates it, the ball start spinning again, the
transaction start again
Format Drive C this code will never be executed
end if
From here to when x goes out of scope x is activated (and probably you don't
know this).
End Sub
203. What's difference between a MTS transaction and an MTS activity ?
Ans:-An activity is a logical thread of execution. An activity spawns across
threads, processes (packages) and machines. An object shares the same
activity with its father object (provided it's not the root of the activity) if the
father used CreateInstance to create it. This is true no matter the father and
child transaction settings are. The concept of activity is used by MTS to
handle concurrent access and re-entrancy.
The objects involved in an MTS transaction are all part of the same activity.
The objects involved in an MTS transaction are a subset (that can match with
the whole) of the objects that share the same activity, this because there
could be some objects that are declared as "Does Not Support Transaction".
204. When do I have to use CreateObject and when CreateInstance?
Ans:-CreateInstance if You are in a component running under MTS AND the
object you want to create is registered under MTS AND you want that the
transaction flows from the father object to the child object.
CreateObject if The caller hasn't got a TransactionContext, that is, you want
to instantiate the root object of a transaction from the base-client OR The
caller has got a TransactionContext but you want that the child object lives in
a new different transaction (read activity in the most general case). Note that
you would have achieved the same effect if you had used CreateInstance but
the child object had been declared under MTS as "Requires New Transaction".
205. What is the best setting of the "Run as" option in a server
package ?
Ans:-When you deploy COM objects in dlls no security issues arise since dlls run
in the process of the caller. On the contrary, when you deploy your COM

objects into an .EXE, you have to deal with such issues. (D)COM needs to
know under what security principal (read identity) the process, where your
COM objects lives in, has to be associated with. (D)COM wants to know other
details as well, like who has the rights to launch and to access the COM
objects and what's the lowest level of security your COM objects must accept
when it negotiates a connection from a caller.These options can be set at run-
time (but you have to deal with DCOM APIs) or can be configured at
deployment time using the Dcomfig utility. If there are no security settings
defined for your Component then (D)COM uses default access permission.
The settings you have available in (D)COM for the Run as setting are:
As interactive user: The process run under the identity of the user currently
logged in the system. This settings is OK only during the development
phase. If none is logged in the system the object creation will fail.
As the launching User: The process run under the identity of the caller
process. This is not an advisable setting to set up a manageable security
As This User: In this case you have to specify a local or domain user. This is
the best setting to go under a production environment.
If what is described above is clear, there is just one more thing to
know when you come to MTS: Each MTS server package is a separate
surrogate process where your dlls run in. If you decide to deploy your dlls into
an MTS Server package you have to remember that every access to the COM
objects implemented in such dlls will have to deal with (D)COM security if the
caller is outside the same MTS package.
206. Should I use Createinstance or CreateObject for ADO objects ?
Ans:-Use CreateObject or the New keyword to create ADO objects. They are not
COM objects registered under MTS.
207. MTS Internal flags, that is how MTS tracks transaction outcome ?

The Above figure shows a diagram of the root object, its context wrapper, and
the MTS transaction in which they are running. It also shows some important
internal flags maintained by MTS. These variables aren’t directly exposed to
you, but you should understand how they influence the MTS runtime’s
decision to commit or abort the transaction.
The transaction as a whole maintains a Boolean value that indicates whether
the transaction should be aborted. I’ll call this the doomed flag. This value is
initially set to False when the MTS transaction is created. When this flag is set
to True, the MTS runtime knows to abort the transaction.
Now, when does the MTS runtime inspect the doomed flag? And how can you
change the value of the doomed flag?
To answer these questions you must understand that the root object plays a
very important role in every MTS transaction. There are two cases when the
MTS runtime inspects the doomed flag: when the root objects returns control
to its caller and when the root object is deactivated. Let’s look at these two
cases and see what the MTS runtime does after inspecting the doomed flag.
The first case is when the root object returns control to its caller. The flow of
execution always passes through the context wrapper first. When control
passes through the context wrapper, the MTS runtime inspects the doomed

flag. If the doomed flag is False, the MTS runtime doesn’t do anything. If the
MTS runtime finds that the doomed flag has been set to True by one of the
objects inside the transaction, it aborts the transaction and deactivates all of
its objects except for the root object. As you will see, this situation is
undesirable. The transaction has been aborted, but the root object remains
activated in a futile state. You can avoid this by following the rules I’ll outline
The second case when the MTS runtime inspects the doomed flag is when the
root object is deactivated. When the root object is deactivated during an
active transaction, the MTS runtime inspects the doomed flag and releases
the transaction by calling either Commit or Abort. If the doomed flag is set to
False, the MTS runtime calls Commit; if the flag is set to True, the MTS
runtime calls Abort.
There are two flags maintained inside the context wrapper for every MTS
transactional object. The first one is the happy flag. It has an initial value of
True when the context wrapper is created. When an object running inside an
MTS transaction is deactivated, the MTS runtime examines its happy flag. If
the happy flag is set to False, the MTS runtime sets the transaction’s doomed
flag to True. Once the transaction’s doomed flag is set to True, it can’t be
reversed. This has a powerful implication: if the root object or any other
object inside a transaction is deactivated in an unhappy state, the transaction
is doomed to failure....
In addition to DisableCommit and EnableCommit (I omitted the description of
DisableCommit and EnableCommit cause they are generally not really usefull
in MTS components design), two other important methods let you control
your transaction: SetComplete and SetAbort. Like the other two methods,
these cast a vote by modifying the happy flag. SetComplete sets the happy
flag to True, while SetAbort sets it to False. SetComplete and SetAbort are
different from the other two methods because they set the done flag to True.
As you’ll see, the done flag has a dramatic effect.
If the done flag is set to True, the MTS runtime deactivates the object.
Therefore, when an MTS object calls SetComplete or SetAbort, the MTS
runtime deactivates it upon return of the method call.
It’s important to use SetComplete and SetAbort at the appropriate times.
When you cast your vote by calling DisableCommit or EnableCommit, the
transaction and all its locks are held until the base client releases the root
object. Calling SetComplete or SetAbort is much better because the root
object forces the MTS runtime to release the transaction.
In other words - (mine)- calling SetAbort/SetComplete at the proper time
guarantee you that your component will scale, it's no longer responsability
of the client to release server objects as soon as possible. Even if the
clients using the server component are not designed with distribution and
scalability in mind they will not overload the server. Suppose hundreds of
MTS objects instances spinning while the users are out having a coffe (cause
the UI programmer will sure have declared your MTS objects as instances
variables and created them in the OnLoad event of the MDI form, didn't he ?
;) )
208. What are the security extension features MTS adds to standard
Ans:-MTS security model is based on Roles. Roles are entities under which you
gather together a number of NT users that are logically equivalent regarding
the security requirements of your component.
This means that the MTS security model is based on the assumption that the
original caller identity is available when you hit the package boundary.
In a distributed environment this security model seems to be clashing with
the way COM passes identity principals across processes and hosts.
Suppose Alice in the host A makes a call to a COM object in hosts B running

as BOB. BOB authenticates Alice, enter a new thead and calls
CoImpersonateClient using Alice identity token. Now within this thread there
is an outgoing call to a COM object running as Charlie in host C.
Since COM knows that NTLM (the WNT 4.0 built-in authentication protocol)
doesn't support cross-host delegation, it calls into Charlie using the Process
token, not thread token.
MTS role based security model seems then to turn completely unusefull (think
about components accessed from IIS where the process token is
IWAM_MACHINE for all the users that surf into your App from the Web).
Clearly there is a way out from this. It turns out that MTS has an interesting
feaure that uses to fix this problem. If your process token is included include
into the "MTS Impersonator" alias (added as a local group by the Option Pack
setup) or if you are running under the system account, MTS makes some
interesting out-of-band work to propagate via the objectcontext the thread
token to the process of the callee. This is the identity token MTS uses to
perform its declarative and programmatic (IsCallerInRole) security checking.
In this situation COM and MTS will disagree on the identity of the caller but
since you have developed your Application security policy using roles this is of
no concern for you.
209. What about syncronization issues in MTS ?
Ans:-MTS keeps under the same Activity ID calls that flow through the same
logical thread of execution. Thus the Activity ID flows correctly through
process and host boundaries. Unfortunately MTS cannot guarantee more
syncronization features than the ones that are provided by the STA threading
model, that is, it guarantees that all the objects within the same process
(package) running in the same Activity (that is STA) will not be accessed
concurrently. BUT when your activity flows cross process and host boundaries
MTS doesn't guarantee you that metod calls within the same activity will be
syncronized. Anyway such a fact is unlikely to be a problem if your client is
not a multithreaded one (like standard VB client App). (thank to Doctor
Richard Grimes' book about MTS programming for this explanation)
210. Can i administer the MTS Catalog in a programmatic way ?
Ans:-The MTS Catalog can be admnistered in a programmatic way via the MTS
2.0 Admin Type Library implemented in the MTXADMIN.DLL. There is a lower-
level access interface exposed by the MTS 2.0 Catalog Server Type Library
(mtxcatex.dll) but you can't fully access its funcionalities from VB cause it
exposes some non-Automation compatible method signatues ([out]
The hierarchical object model exposed by the Admin Type Library to map the
catalog structure is kinda unusual, different from the ones you are used to
work with.
The whole MTS catalog is exposed using only three classes (that implement a
single interface):
To connect to an MTS catalog you use the Connect method specifing the
server name. To get an item (a CatalogObject) from a CatalogCollection
you use the Item(n) method. The Item method accepts only numeric
values and is zero based. To get the child CatalogCollections of an Item
you have to call the GetCollection method on the CatalogCollection the
Item comes from (this is the unusual stuff i was talking about before).
The GetCollection method needs to parameters:
The Name of the requested collection type (Packages,Roles, etc.)
The key of the father item

The GetCollection method doesn't populate the collection. You have to call the
Populate method to do this.
To persist changes to the Catalog you have to call SaveChanges
I know it's kinda complicated so i drop some lines of code.
Dim Cat as New Catalog
Dim CatCollRoot as CatalogCollection
Dim CatCollPackages as CatalogCollection
Dim CatCollComponents as CatalogCollection
Dim CatObjPackage as CatalogCollection
set CatCollRoot = Cat.Connect("MyServer")
'Pass an empty string to connect to local catalog
set CatCollPackages = CatCollRoot.GetCollection("Packages","")
Set CatObjPackage = CatCollPackages.Item(0)
Set CatCollComponents = CatCollPackages.GetCollection _
As you can see, in the case of the root collection the second parameter of the
GetCollection method is blank. This happens when the requested collection is
hierarchicaly a child of another collection and not of an item. This applies for:

- The Root collection you get from Catalog.Connect

- The RelatedCollectionInfo collection (see below)
- The RelatedPropertyInfo collection (see below)
- The ErrorInfo collection (not mentioned here)

To facilitate the navigation in to this "poored typed" object model there are
two helper CatalogCollections available:
RelatedCollectionInfo: Gives you the name of all the child
CatalogCollections available
RelatedPropertyInfo: Gives you the name of all the properties that the
items that are part of the collection expose.
Using these two helper classes you can reconstruct the Catalog structure
at run-time.

CatalogCollections let you navigate, enumerate,remove and, in some cases,
add objects in the catalog. To perform a number of tasks that need more
info to be accomplished you need to use some Utility objects. You get
access to such objects invoking the GetUtilInterface on the appropriate
The Utility objects are:
PackageUtil (GetUtilInterface on the Packages collection)
- ComponentUtil (GetUtilInterface on the ComponentsInPackage
- RemoteComponentUtil (GetUtilInterface on the RemoteComponents
- RoleAssociationUtil (GetUtilInterface on the
RolesForPackageComponent or RolesForPackageComponentInterface
211. I want to use MTS only for its component deployment facilities. Is
there any issue I should be warned about ?
Ans:-Let's suppose you have a bunch of COM DLLs that have not been written
with MTS in mind. Now you want to deploy these dlls into an MTS server
package just to easy the pain of
- turning them into EXE COM objects
- use Dcomfig.exe
to have them accessible via DCOM remotely.
This means that your COM objects will be registered as "Does not Support
Transaction" and they will never call any MTS API method.
Probably this is not a good choice from an architectural point of view. If your
interfaces have not been designed with distribution in mind, they will perform
very poorly over the network, but this is not the point i want to stress out
here, cause i want to answer to the following question here: will my COM
objects will work "as before" after i deployed them under MTS ? The answer is
generally yes, they will work as before but with much less performance. Each
call to Createobject starts a new activity when the created object is registered
under MTS. A new activity means the creation of a new STA where the
created object is placed. I suppose there are a lot of cross activations & calls
among these dlls you have deployed under MTS. It turns out that what was
running under the same thread/STA before the deployment, now spans plenty
of activities (threads); so that the code flow is slowed down by lot of cross
apartment comunication. Unfortunately there is one situation where things
gets even worst: when you use disconnected recordsets (that marshal by
value) in your dlls. When disconnected recordsets are passed among
components they change their behaviour depending on the fact that they are
marshaled or not (check out the visible number of records in a filtered
recordset before and after being marshaled, as you have suspected, the filter
property is lost after the marshaling, all records are visible again). In such
situation, then, you Application can behave differently, not only performance
more poorly.
Conclusion: quick and dirty deployment under MTS is most of the time not a
good choice.
Changing CreateObject with GetObjectContext.CreateInstance at the proper
places is a must to have things working in an acceptable way.
212. Why is it a bad idea to use "Global" variables, that is Public
variables at module level ?
Ans:-Public variables at module level are thread specific. Each new thread starts
get a new fresh & uninitialized copy of such variables. I've found out that all
the activities that are born from the same object context always run in the
same apartment (I checked the thread id) as if the object context had some
kind of thread affinity. What i mean is this: suppose you have an mts object

that has a method that returns the thread id and then calls set complete.
Each call to the method starts a new activity but the thread id returned is
always the same. This could sound tempting to store some state across
activity boundaries but since the number of thread available for a package is
limited (100 by default) you would end up having, under heavy stress,
different activities sharing the same apartment and then the same public .bas
variables. with unpredictable results.
213. Problems exporting Packages with classes that implements
interfaces defined in "external" Type Libraries
Ans:-MTS Packages are exported for two reasons:
Clone the package on another server
Produce a setup program that you run on the client computers to configure in
a way they can access the server components via DCOM
This procedure is generally a "one click" one, but there are some problems
when your classes implements interfaces that are defined in external Type
Libraries. When you export the package these Type Libraries are not included
in the export directory. This makes unusable the export files for both uses i
described above.
There is a simple workaround if you want to exported the package for use #2:
just copy manually the type libraries in the export directory, the tlb files will
be copied and registered on the client machine.
This tecnique doesn't work for case #1: you cannot successfully import a
package on another server even if you have copied the tlbs in the export
directory (you got an error). I don't know any workaround for this at present,
you have to recreate the package on the server. To easy this problem you can
develop a VB program that programmatically register dlls and type libraries
on the target computer and then programmatically create the package using
the MTS 2.0 Admin Type Library. I've developed such a VB program; it's not
an 'All purpouse' one but it's a good starting point you can customize, write
me if you want the source code.
214. When to call SetComplete ?
Ans:-SetComplete does NOT inform MTS that the object is ready for deactivation.
SetComplete informs MTS that *when control returns to the client* (i.e.
control returns to the Context Wrapper on its way back to the client) MTS
should deactivate the object.
The practical implication of this is that, if you are coding an object which
contains a suite of non-transactional stateless methods, you can enforce JIT
activation by coding a single SetComplete in the ObjectControl_Activate
event. (In a non-transactional context, there is no effective difference
between SetComplete and SetAbort, so you can 'pre-call' SetComplete with
215. Why do I get an Access Denied Error when I try to raise an event
from my MTS component to my client ?
Ans:-The client executable doesn't have the proper DCOM security settings to let
the server call it back. In order to have it working you have two solutions:
Open wide DCOM security settings on the client side
Add the proper DCOM security settings for the client executable in the registry
(you cannot call CoInitializeSecurity in a VB client).
Add a new key with the name of the client executable under the AppId key
Generate a GUID with guidgen.exe
Add a key with such value under the AppId key
Add a string value under the key created in step a whose name is AppID and
the value is the generated GUID vaue
Add the proper security settings under the GUID key.

216. Connection Pooling
Ans:-Connection pooling is an essential feature for distributed scalable
applications. Note that database connection pooling is provided by the ODBC
or OLEDB drivers not by MTS/COM+, still it's in MTS or COM+ that connection
pooling shows its greatest benefits. Connection pooling reduces overall
overhead that appears due to rather often open/close operations on database
connections. But, to ensure that an application (read - component) is "pooling
compliant", design and implementation of the application should consider
following restrictions:

1) Connections should be opened using the same identity

A connection opened with one identity cannot be reused for a request with
another identity. Opening connections with different identities increases pool
size and makes its usage worthless.
2) Connection can not be reused across processes. Hence each MTS package
holds it own pool of connections.
3) Underlying database should be "MTS compatible".
4) ODBC driver(s) or OLE DB Provider(s) being used should support MTS.

MDAC versions related issues:

1) MDAC 1.5. Provides only (?) ODBC pooling

2) MDAC 2.0. OLE DB pooling is disabled by default for OLE DB Provider for
ODBC. ODBC pooling is being used
3) MDAC 2.1. OLE DB pooling is being used for all providers by default. OLE
DB connection pooling timeout has a fixed value - 60 seconds.
For ODBC sources you can get back to ODBC pooling by deleting
OLEDB_SERVICES registry entry. To do it - run REGEDIT utility, choose
Edit/Find, type "Microsoft OLE DB Provider for ODBC Drivers" (omit quotes).
Find will show
entries under the provider's CLSID. Click on the CLSID and delete
OLEDB_SERVICES value (not just set to zero).
4) MDAC 2.5. In beta stage, not released yet. Overall performance will be
increased (at least Microsoft says so). OLE DB connection pooling timeout will
be changeable.
217. MTS compatibility of databases
Ans:-The phrase "a database is MTS compatible" generally means that the
database supports distributed transactions (XA or OLE DB protocol) and there
is an ODBC driver or/and OLE DB provider that could be used by a component
in MTS environment. The main requirement for an MTS compliant ODBC
driver is to be thread-safe.
If a database doesn't support MTS, one won't get advantages of MTS
transaction management architecture. Though it's still possible to perform any
operations on the database and use "traditional" BeginTrans/Commit/Rollback.
Current list of databases that support MTS:
Microsoft SQL Server 6.5
Oracle 7.3.3 and later releases

Sybase Adaptive Server Enterprise
Very often developers mistakenly are trying to use MS Access as an
underlying database. MS Access does not support MTS.
218. Load balancing in MTS
Ans:-MTS2.0 does not provide load balancing (LB). Microsoft suggests us to
implement custom LB. For example, by dividing users into the groups and
referring those groups to different MTS nodes. Or, in case of usage of IIS,
implement "smart redirecting" among different IISs (like it's done on
COM+ has built-in LB. It is realized as a component wich receives client
requests and redirects them to a less loaded server. This component may be
replaced by a custom component which provides more complicated custom
rules of LB.
219. What is security context delegation and how to set it up
Ans:-Delegate is the new impersonation level available in COM+. Delegation is
available on COM+ since now is supported by the underlying Security Support
Provider (SSP) available on windows 2000: Kerberos.
The delegate impersonation level means that the client credentials can be
hopped from server to server during the call chain to be used by the server
process to perform work using the client credentials.
Due to the limitations of the NTLM SSP used on NT4, delagation was not
supported on NT4, a less powerfull setting was available: impersonate. In this
case client credentials could be used only by server A invoked directly by the
client, but they couldn't be hopped to another server B invoked by server A.
Remeber that the impersonation level is determined exclusively by the client
(unlike authentication level, where the level applied is the common lowest
watermark choosed among the preferences expressed by the client AND the
BTW: The impersonation level cannot be set on a per application basis
declaratively using DCOMCNFG, hence (since you cannot call the COM API
CoInitializeSecurity in VB to set this level programmaticaly) you have to
modifiy the machine wide impersonation level setting on DCOMCNFG to set up
an impersonation level for a VB application (but in this way you influence all
client applications that do not call explicitely CoInitializeSecurity).
Ok, so it seems simple to set up delegation; every entity in the call chain
must call CoInitialize security requiring delegation. Unfortunately it's not that
simple; let's see what's the extra work required:
Call CoInitiliazeSecurity with a proper flag () EOAC_STATIC_CLOACKING or
EOAC_DYNAMIC_CLOACKING) to require Cloacking. If you require Cloacking
COM+ will use the thread identity and not the process identity when
performing calls to a proxy. It may sound weird to require such a thing; the
reason why this is not the default behaviour in COM+ is not to break existing
apps developed on NT4 when they are ported on W2K, since no-cloacking was
the only available behaviour in COM on NT4.
All actors taking part in the delegation scenario must have been granted
proper permissions on Active Directory:
Server Identity :Account is Sensitive And Cannot Be Delegated disabled
Client identity : trusted for delegation Enabled
Computers: trusted for delegation
220. Is GetObjectContext.CreateInstance obsolete in COM+ ?
Ans:-Yes. Createinstance was necessary in COM to provide a COM object
activation mechanism that could be hooked by the MTS runtime before the
activation request reached the COM runtime. So that MTS could apply some
pre and post activation magic to put a wrapper around the real object and
return this wrapper to the client.
This was due to the fact that MTS was not integrated with COM but ws built

on top of COM.
COM+ has now embodied within its runtime the required interceptions
mechanism, so there GetObjectContext.CreateInstance is no more necessary,
still this syntax is still supported for backward compatibilities.
Nevertheless I suggest you to make conditional builds that use
GetObjectContext.CreateInstance or Createobject according to your target
221. What is Fallback Authentication(that is, how do i set up
authentication among computers NOT running in the same
domain) ?
Ans:-COM doesn't have a built in security mechanism, but relies on Windows
authentication services (Security Service Providers).
When you need to acces a resource or invoke a method in a remote Dcom
server (or MTS package / COM+ Application) security checks cannot be
performed in the standard way if the client is not running into the same
domain (or, of course, workstation, but in this case there would be no remote
communication) where the server is.
A principal that tries to launch/access a dcom server may be a local user
defined in the client workstation account database or a user defined in a
domain. If the client identity is a user defined in the same domain where the
server is (or in a domain that is trusted by that domain) then everything is
fine. If it's not the case (this applies in the situation where the server is not in
a domain as well), then the server doesn't know who to ask to authenticate
the user identity (match the password).
To let resource access and DCOM communication possible in this case,
Windows implements the so-called Fallback authentication:
1) The server tries to see if there is a user that matches the client identity in
the domain or workstation account database he belongs to .
2) If step one succeded then windows check if this user password match the
password of the client identity.
If both steps succeeded then the client is "indirectly" authenticated and then,
form this point, all access control is performed using this "matching" user.
Fallback autientication is not easy to maintain, since two accounts must be
kept in synch, but in some situation this mechanism may turn usefull.
222. How do I impersonate the client in my COM+ Application (MTS
package) ?
Ans:-During a client Server conversation it's ONLY the client that decides
what impersonation is allowed; playing with the impersonation level of the
COM+ App has no effect, changing this setting you are declaring what is the
impersonation level that your COM+ lets to use when will make a call to
another process (read com+ application, thus acting as a client).
If the client process choosed a Impersonate or Delegate impersonation level,
then your server can call successfully CoImpersonateclient(); from this point
to a subsequent call to CoRevertToSelf() all the code will be executed in the
security context of the client (SQL integrated authentication included).
VB can't call successfully call CoInitialize security, A "VB created client
process" get the system wide impersoantion level, so situation is not really
If the calling process is IIS, then everything works OK, and you can run in
the context of the caller, whose identity depends on IIS authentication
223. What the major changes in the role based security model in
COM+ ?
Ans:-There are basically two major changes in the role based security model in

You can set role based security on Library packages (in MTS you could set role
based security on server packages only. This can be very usefull in web based
applications, since you can set up security policies on web users access
avoiding the cross process overhead involved in using server packages (you
might have already gone once through such overhead defining your IIS
application as running in medium or high isolation mode).
You can set role based security at method level (in MTS you could set role
based security at class and interface level only). I personally try to avoid this
feature, since i think it's a good design practice to set up security at interface
level to force interface semantic.
224. How do I make COM objects deployed into a COM+ Application
availalable to clients ?
Ans:-What I describe for COM+, applies to MTS with some slight differences as
Registering COM objects remotely has been quite a pain before MTS showed
up (rememeber the VBR file?).
In COM+ it's very easy to do.
Right click on the COM+ application and choose export Choose application
proxy, choose the export package file name (.msi file)
2) Go to the client, run the .msi, (make it accessible to the server creating a
proper share), you are done.
Watch out there is a bug in W2K SP2 that produces a bad .msi file that don't
register the component corrrectly. Get the the proper post SP2 fix from MS
before SP3 will be released.
The other export option you have in W2K is conceived to deploy an exact copy
of the COM+ App to another server. In MTS you do not have these two
options separately. The export option in MTS produces both kind of exports.
The export for the client is the exe file in the client subdirectory.
225. What is COM+ 1.5 ?
Ans:-COM+ 1.5 is an evolution of COM+ 1.0. COM+ 1.0 was released with
windows 2000. COM+ 1.5 has been released with Windows XP / .NET Servers.
COM+ 1.5 provides some new features like application recycling and COM+
partitions, running COM+ applications as services and more (I'll likely cover
these new features in a coming FAQ).
COM+ 1.5 WILL NOT be available as an upgrade in the windows 2000
operating system. To get COM+ 1.5 you've to upgrade to WIndows XP / .NET
226. Can the same component be registered in different COM+
Applications /MTS Packages ?
Ans:-NO, this is not possible in MTS or COM+ 1.0 (W2K). It is possible in COM+
1.5 using COM+ partitions.
227. How do you register a component?
Ans:-Compiling the component, running REGSVR32 MyDLL.dll
228. Name and explain the different compatibility types when creating a
COM component.
Ans:-No Compatibility ? New GUID created, references from other components
will not work
Project Compatibility ? Default for a new component <Not as critical to
mention this one>
Binary Compatibility ? GUID does not change, references from other
components will work
229. Why is it important to use source control software for source code?
Ans:-Modification history.
Code ownership: Multiple people can not modify the same code at the same

230. What two methods are called from the ObjectContext object to
inform MTS that the transaction was successful or unsuccessful?
Ans:-SetComplete and SetAbort.
231. What does Option Explicit refer to?
Ans:-All variables must be declared before use. Their type is not required.
232. Name the four different cursor types in ADO and describe them
Ans:-The cursor types are listed from least to most resource intensive.
Forward Only ? Fastest, can only move forward in recordset
Static ? Can move to any record in the recordset. Data is static and never
KeySet ? Changes are detectable, records that are deleted by other users are
unavailable, and records created by other users are not detected
Dynamic ? All changes are visible.
233. Name the four different locking type in ADO and describe them
Ans:-LockPessimistic ? Locks the row once after any edits occur.
LockOptimistic ? Locks the row only when Update is called.
LockBatchOptimistic ? Allows Batch Updates.
LockReadOnly ? Read only. Can not alter the data.
234. What are the ADO objects? Explain them. Provide a scenario using
three of them to return data from a database.
Ans:-Connection ? Connects to a data source; contains the Errors collection
Command ? Executes commands to the data source. Is the only object that
can accept parameters for a stored procedure.
Recordset ? The set of data returned from the database.
Scenario: There are many possibilities. The most likely is as follows:
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Cmd As ADODB.Command
conn.ConnectionString = ?CONNECTION STRING?
Set Cmd.ActiveConnection = conn
Cmd.CommandText = ?SQL STATEMENT?
Set rs = Cmd.Execute
Set rs.ActiveConnection = Nothing
235. Under the ADO Command Object, what collection is responsible for
input to stored procedures?
Ans:-The Parameters collection.
236. What are some benefits of using MTS?
Ans:-Database Pooling, Transactional operations, Deployment, Security, Remote
237. What is the benefit of wrapping database calls into MTS
Ans:-If database calls are made within the context of a transaction, aborting the
transaction will undo and changes that occur within that transaction. This
removes the possibility of stranded, or partial data.
238. Describe and In Process vs. Out of Process component. Which is
Ans:-An in-process component is implemented as a DLL, and runs in the same
process space as its client app, enabling the most efficient communication
between client and component.Each client app that uses the component starts
a new instance of it.

An out of process component is implemented as an EXE, and unlike a dll, runs
in its own process space. As a result, exe’s are slower then dll’s because
communications between client and component must be marshalled across
process boundaries. A single instance of an out of process component can
service many clients.
239. What are Serviced Components ?
Ans:-Serviced Components is the term that Microsoft has decided to use to
identify .NET classes that use COM+ Services. sometime the term Enteprise
services is also used to identify the use of COM+ within the .NET framework.
240. Do I need to resort to COM+ to use functionalities like distributed
transaction management or object pooling ?
Ans:-Yes, the .NET runtime doesn't support natively the equivalent of COM+
services. They will be probably released in a future (looks like that the code
name for such project is Indigo).
Fortunately, at present, the .NET runtime provide a mechanism to let .NET
managed code to make COM+ services avaialbale to .NET code.
To hook into COM+ services a .NET class must derive from
241. How do I associate COM+ settings to my .NET class and assembly ?
Ans:-The .NET framework lets you declare COM+ related settings for a .NET class
via the standard .NET attribute based approach. This approach is something
that has been long awaited for COM components but was never made
available before.
Almost all the COM+ related settings available via the Component Services
management console snap-in (or the COM+ catalog administration
component) can be configured tagging with proper attributes assemblies,
classes and methods. Only a few properties like the process identity of a
server package can't be must be declared in a latter phase when the .NET
component has been registered into the COM+ catalog. This is quite
reasonable since you do not want to hardcode the username password into
the code (as you may known, .NET IL is quite easy to reverse engineer).
Here is a sample code. MyClass requires object pooling, and MyMethod is
declared as autocomplete (SetComplete is implicitly called unless an
exception is thrown)
<JustInTimeActivation, _
ObjectPooling(MinPoolSize=5, MaxPoolSize=5, Enabled=true)> _
Public class MYclass
<AutoComplete()> _
Public Function MyMethod
242. How do i register a .NET component into the COM+ catalog ?
Ans:-Assembly containing serviced classes must go through a registration
process to insert the required info into the COM+ catalog and in the registry
in order to make them visible to the COM+ runtime. Assemblies are
registered using the Regsvcs.exe utility whose basic command line syntax is:
Regsvcs C:\myassembly.dll
In order to provide XCOPY deployment features for serviced components,
Microsoft has tried to automate this operation: while binding to a serviced
component, the .NET runtime registers the assembly transparently if the
registration info can’t be found. Unfortunately this process, that requires
Administrator rights, is run under the identity of the caller; hence it will likely
fail in a real world scenario.
243. Do I need to register my .NET Serviced component into the GAC ?
Ans:-It depends. The point to rememeber is that .NET binding policies applyes to
Serviced components as well. Having the assembly registered in a COM+
application is not what a com developer tends to think. From a COM+

perspective all registered serviced components are implemented in
If the component is declared to reside in a lIbrary COM+ application then it
will be loaded into the client process. If the assembly is not registered into
the GAC, the assembly must be placed in a directory where the CLR, applying
local probing can locate it. This works exactly as any "standard" .NET
If the component is declared to reside in a Server COM+ application, the
there are two processes that must be able to locate the assembly:
The client process to bind to the assembly types
The dllhost.exe process to load the assembly in order to execute it
Regarding the client the same as for the library COM+ applications applies.
What about the dllhost process ? it comes out that during the registration
phase regsvcs add the a CodeBase entry into the registry under the
InProcServer (that's under the Component CLSID).
As a side note: you can define an entry in an application config file to
explicitly declare the location of an assembly, bypassing local probng and the
Note that the default entry that's usually used to identify the location of a
COM component is "taken" by mscoree.dll; as a fact, as far as COM is
concerned all serviced compoennts are implemented by this dll.
The CLR (specifically mscoree.dll) uses the codebase entry to locate the
assembly. This means that, as long as the dllhost process you are not
required to register the componetn into the GAC.ù
Said that, the quickest way to make sure to have the assembly succesfully
loaded by both the client and the COM+ surrogate process is to register it into
the GAC.
244. Do I need to strongly sign a Serviced Component ?
Ans:-Any Serviced component must be hosted into a strongly signed assembly;
to do this you must first run the sn.exe utility with the -k switch to generate a
file containing the public/private key pair. You then sign the assembly with the
key pair adding the following line in the assemblyinfo.vb file
<assembly: AssemblyKeyFile("mykey.snk")>
245. How do I implement correctly Object Pooling in the .NET
Ans:-You've basically 2 options:
Require Just in Time Activation and declare each method as autocomplete, or
call SetComplete/SetAbort/ DEactivateOnReturn. In this way the CLR has
all the info to automagically return the object to the pool.
Have the client call dispose when done
Note that there are at present (VS 1, SP!) some problems when the object is
invoked via .NET Remoting.
Calling Dispose on the object on the client side (the transparent proxy
actually) has no effect, you have to resort to the first option mentioned
In case the object is declared into a Library application it is not not returned
into the pool.
246. How many number of concurrent serviced components instances
can run in a COM+ application ?
Ans:-"old" VB6 COM+ components had to run in an STA. In a COM+ application
the maximum size that the STA thread pool can reach is 10 multiplied by the
number of processors. On the contrary, .NET serviced components, no matter
what language you use, are marked as BOTH, that is, they run in the COM+
Application MTA (Multi Threaded Apartment). The COM+ runtime do not pose
any limit on the thread pool size of the MTA apartment.

This means that there is no built-in limit on the number of concurrent serviced
components instances which can run in a COM+ application. Nevertheless, it's
better you monitor the context switch in a COM+ application process. If this
gets too high it means that the processor spends more time in thread
switching than doing any real job.
247. Can I mix Serviced components and Remoting ?
Ans:-Yes you can. Serviced Components derive from MarshalByRefObject, so they
can be accessed remotely using .NET Remoting instead of DCOM.
To do so deploy your serviced components in a COM+ library application (so
that you get all COM+ benefits such as Object pooling or Declarative
Transactions), then create an hosting process for your Serviced component to
make it available remotely as you would do with any standard remotable
The pros are that you can develop specific application configuration files.
The cons are that there is no transaction flow across remoting calls, nor any
built - in security support.
248. Can I use Application configuration files when hosting Serviced
components in Server COM+ Applications ?
Ans:-In W2K you can't. All Server COM+ Applications are hosted by different
instances of the same executable: DLLHOST.EXE. Since .NET configuration
files are based on the process name, you would end up mixing the
configuration info of all the COM+ Server Applications hosted in the Server
Just resort to something else (such as Construction strings).
On the contrary, in Windows Server 2003 (that is COM+ 1.5 and .NET 1.1)
you can specify the path to a configuration file for each COM+ server
249. Why my .NET Serviced component ball is not spinning in the COM+
Explorer ?
Ans:-You just need to add the EventTrackingEnabled attribute to the class.
class myclass
250. My client is trying to resolve server side assemblies referenced by
the Serviced Component I'm accessing. How is that ?
Ans:-In a classic layered application, you have the Business Layer and the Data
Layer residing on the server side . Fat clients (windows form based) interact
with the remote Business Layer which must then be accessible remotely.
One option to do that in .NET is to define the Business Objects as
ServicedComponents, deploy them in Server COM+ Application and then
produce a proxy export from the COM+ Application. The Proxy Export is just
an MSI file which, when run on the client machine, copies all required
assemblies and set the appropriate registry entries to let the client create and
invoke methods on the the remote object.
The assemblies containing the Business objects must be present on the client
machine because the CLR on the client side need to resolve the definition of
the type of the remote object. There is nothing such .NET Remoting SAO
which can allow you not to deploy the server assembly on the client.
As I said, in a tipical distributed architecture, Business Objects call into Data
Access Components. Such objects are not ment to be called directly by the
client and, since the client is unaware of them, there is no reason why they
should be deploied on the client as well.
I'm pretty sure you agree with me, but unfortunately the CLR does not :( .. if
you call Serviced Component B in Assembly B1, which in turns calls class D in

Assembly D1 then you have to deploy Assembly D1 on the client side, if you
fail to do so, the CLR on the client side will complain about the fact that it
can't find Assembly D1 ?!
Note that this happens even if you make sure that
no types of Assembly D1 are exposed through public methods of classes in
Assembly B1
no Assembly D1 types are used in Assembly B1 classes static constructor
(if it was the case then this behaviour would make sense).
I cannot provide a reason why. This must be well deep inside the Enterprise
Services Runtime. Using Reflector I've seen that there is some code in the
ServicedComponent's static and instance constructor, still I've also noticed
that the Assembly D1 is not loaded when the class in Assembly B1 is newed,
but when the method using the class in Assembly D1 is called; thus this must
have something to do with JIT compilation.
However it is, this fact poses some deployment problems (to say the least)
when deploying .NET components in a COM+ Server Application. I strongly
suggest you to use an alternative approach : deploy your .NET components in
a library application and make them available remotely using .NET Remoting.
As a fact, this odd beahviour doesn't shown up in this case.
251. I am constantly writing the drawing procedures with
System.Drawing.Graphics, but having to use the try and dispose
blocks is too time-consuming with Graphics objects. Can I
automate this?
Ans:-Yes, the code
System.Drawing.Graphics canvas = new System.Drawing.Graphics();
//some code
is functionally equivalent to
using (System.Drawing.Graphics canvas = new System.Drawing.Graphics())
//some code
} //canvas.Dispose() gets called automatically
252. How do you trigger the Paint event in System.Drawing?
Ans:-Invalidate() the current form, the OS will take care of repainting. The
Update method forces the repaint.
253. With these events, why wouldn’t Microsoft combine Invalidate and
Paint, so that you wouldn’t have to tell it to repaint, and then to
force it to repaint?
Ans:-Painting is the slowest thing the OS does, so usually telling it to repaint, but
not forcing it allows for the process to take place in the background.
254. How can you assign an RGB color to a System.Drawing.Color
Ans:-Call the static method FromArgb of this class and pass it the RGB values.
255. What class does Icon derive from? Isn’t it just a Bitmap with a
wrapper name around it?
Ans:-No, Icon lives in System.Drawing namespace. It’s not a Bitmap by default,
and is treated separately by .NET. However, you can use ToBitmap method to
get a valid Bitmap object from a valid Icon object.
256. Before in my VB app I would just load the icons from DLL. How can
I load the icons provided by .NET dynamically?

Ans:-By using System.Drawing.SystemIcons class, for example
System.Drawing.SystemIcons.Warning produces an Icon with a warning sign
in it.
257. When displaying fonts, what’s the difference between pixels,
points and ems?
Ans:-A pixel is the lowest-resolution dot the computer monitor supports. Its size
depends on user’s settings and monitor size. A point is always 1/72 of an
inch. An em is the number of pixels that it takes to display the letter M.
258. What’s a Windows process?
Ans:-It’s an application that’s running and had been allocated memory.
259. What’s typical about a Windows process in regards to memory
Ans:-Each process is allocated its own block of available RAM space, no process
can access another process’ code or data. If the process crashes, it dies alone
without taking the entire OS or a bunch of other applications down.
260. Why do you call it a process? What’s different between process
and application in .NET, not common computer usage,
Ans:-A process is an instance of a running application. An application is an
executable on the hard drive or network. There can be numerous processes
launched of the same application (5 copies of Word running), but 1 process
can run just 1 application.
261. What distributed process frameworks outside .NET do you know?
Ans:-Distributed Computing Environment/Remote Procedure Calls (DEC/RPC),
Microsoft Distributed Component Object Model (DCOM), Common Object
Request Broker Architecture (CORBA), and Java Remote Method Invocation
262. What are possible implementations of distributed applications in
Ans:-.NET Remoting and ASP.NET Web Services. If we talk about the Framework
Class Library, noteworthy classes are in System.Runtime.Remoting and
263. What’s a proxy of the server object in .NET Remoting?
Ans:-It’s a fake copy of the server object that resides on the client side and
behaves as if it was the server. It handles the communication between real
server object and the client object. This process is also known as
264. What are remotable objects in .NET Remoting?
Ans:-emotable objects are the objects that can be marshaled across the
application domains. You can marshal by value, where a deep copy of the
object is created and then passed to the receiver. You can also marshal by
reference, where just a reference to an existing object is passed.
265. What are channels in .NET Remoting?
Ans:-Channels represent the objects that transfer the other serialized objects
from one application domain to another and from one computer to another, as
well as one process to another on the same box. A channel must exist before
an object can be transferred.
266. What security measures exist for .NET Remoting in
Ans:-None. Security should be taken care of at the application level.
Cryptography and other security techniques can be applied at application or
server level.
267. What is a formatter?

Ans:-A formatter is an object that is responsible for encoding and serializing data
into messages on one end, and deserializing and decoding messages into data
on the other end.
268. Choosing between HTTP and TCP for protocols and Binary and
SOAP for formatters, what are the trade-offs?
Ans:-Binary over TCP is the most effiecient, SOAP over HTTP is the most
269. What’s SingleCall activation mode used for?
Ans:-If the server object is instantiated for responding to just one single request,
the request should be made in SingleCall mode.
270. What’s Singleton activation mode?
Ans:-A single object is instantiated regardless of the number of clients accessing
it. Lifetime of this object is determined by lifetime lease.
271. How do you define the lease of the object?
Ans:-By implementing ILease interface when writing the class code.
272. True or False: To test a Web service you must create a windows
application or Web application to consume this service?
273. Can you configure a .NET Remoting object via XML file?
Ans:-Yes, via machine.config and application level .config file (or web.config in
ASP.NET). Application-level XML settings take precedence over
274. How can you automatically generate interface for the remotable
object in .NET with Microsoft tools?
Ans:-Use the Soapsuds tool.
275. Write a simple Windows Forms MessageBox statement.
276. Can you write a class without specifying namespace? Which
namespace does it belong to by default??
Ans:-Yes, you can, then the class belongs to global namespace which has
no name. For commercial products, naturally, you wouldn’t want global
277. You are designing a GUI application with a windows and several
widgets on it. The user then resizes the app window and sees a lot
of grey space, while the widgets stay in place. What’s the problem?
Ans:-One should use anchoring for correct resizing. Otherwise the default
property of a widget on a form is top-left, so it stays at the same location
when resized.
278. How can you save the desired properties of Windows Forms
Ans:-.config files in .NET are supported through the API to allow storing and
retrieving information. They are nothing more than simple XML files, sort of
like what .ini files were before for Win32 apps.
279. So how do you retrieve the customized properties of a .NET
application from XML .config file?
Ans:-Initialize an instance of AppSettingsReader class. Call the GetValue method
of AppSettingsReader class, passing in the name of the property and the type
expected. Assign the result to the appropriate variable.
280. Can you automate this process?
Ans:-In Visual Studio yes, use Dynamic Properties for automatic .config creation,
storage and retrieval.
281. My progress bar freezes up and dialog window shows blank, when
an intensive background process takes over.

Ans:-Yes, you should’ve multi-threaded your GUI, with taskbar and main form
being one thread, and the background process being the other.
282. What’s the safest way to deploy a Windows Forms app?
Ans:-Web deployment: the user always downloads the latest version of the code,
the program runs within security sandbox, properly written app will not
require additional security privileges.
283. Why is it not a good idea to insert code into InitializeComponent
method when working with Visual Studio?
Ans:-The designer will likely through it away, most of the code inside
InitializeComponent is auto-generated.
284. What’s the difference between WindowsDefaultLocation and
Ans:-WindowsDefaultLocation tells the form to start up at a location selected by
OS, but with internally specified size. WindowsDefaultBounds delegates both
size and starting position choices to the OS.
285. What’s the difference between Move and LocationChanged? Resize
and SizeChanged?
Ans:-Both methods do the same, Move and Resize are the names adopted from
VB to ease migration to C#.
286. How would you create a non-rectangular window, let’s say an
Ans:-Create a rectangular form, set the TransparencyKey property to the same
value as BackColor, which will effectively make the background of the form
transparent. Then set the FormBorderStyle to FormBorderStyle.None, which
will remove the contour and contents of the form.
287. How do you create a separator in the Menu Designer?
Ans:-A hyphen ‘-’ would do it. Also, an ampersand ‘&\’ would underline the next
288. How’s anchoring different from docking?
Ans:-Anchoring treats the component as having the absolute size and adjusts its
location relative to the parent form. Docking treats the component location as
absolute and disregards the component size. So if a status bar must always
be at the bottom no matter what, use docking. If a button should be on the
top right, but change its position with the form being resized, use anchoring.
289. What’s the advantage of using System.Text.StringBuilder over
Ans:-StringBuilder is more efficient in the cases, where a lot of manipulation is
done to the text. Strings are immutable, so each time it’s being operated on,
a new instance is created.
290. Can you store multiple data types in System.Array?
291. What’s the difference between the System.Array.CopyTo() and
Ans:-The first one performs a deep copy of the array, the second one is shallow.
292. How can you sort the elements of the array in descending order?
Ans:-By calling Sort() and then Reverse() methods.
293. What’s the .NET datatype that allows the retrieval of data by a
unique key?
294. What’s class SortedList underneath?
Ans:-A sorted HashTable.
295. Will finally block get executed if the exception had not occurred?

296. What’s the C# equivalent of C++ catch (…), which was a catch-all
statement for any possible exception?
Ans:-A catch block that catches the exception of type System.Exception. You can
also omit the parameter data type in this case and just write catch {}.
297. Can multiple catch blocks be executed?
Ans:-No, once the proper catch code fires off, the control is transferred to the
finally block (if there are any), and then whatever follows the finally block.
298. Why is it a bad idea to throw your own exceptions?
Ans:-Well, if at that point you know that an error has occurred, then why not
write the proper code to handle that error instead of passing a new Exception
object to the catch block? Throwing your own exceptions signifies some
design flaws in the project.
299. What’s a multicast delegate?
Ans:-It’s a delegate that points to and eventually fires off several methods.
300. How’s the DLL Hell problem solved in .NET?
Ans:-Assembly versioning allows the application to specify not only the library it
needs to run (which was available under Win32), but also the version of the
301. What are the ways to deploy an assembly?
Ans:-An MSI installer, a CAB archive, and XCOPY command.
302. What namespaces are necessary to create a localized application?
Ans:-System.Globalization, System.Resources.
303. What’s the difference between // comments, /* */ comments and
/// comments?
Ans:-Single-line, multi-line and XML documentation comments.
304. How do you generate documentation from the C# file commented
properly with a command-line compiler?
Ans:-Compile it with a /doc switch.
305. What’s the difference between <c> and <code> XML
documentation tag?
Ans:-Single line code example and multiple-line code example.
306. Is XML case-sensitive?
Ans:-Yes, so <Student> and <student> are different elements.
307. What debugging tools come with the .NET SDK?
Ans:-CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual
Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original
C# file using the /debug switch.
308. What does the This window show in the debugger?
Ans:-It points to the object that’s pointed to by this reference. Object’s instance
data is shown.
309. What does assert() do?
Ans:-In debug compilation, assert takes in a Boolean condition as a parameter,
and shows the error dialog if the condition is false. The program proceeds
without any interruption if the condition is true.
310. What’s the difference between the Debug class and Trace class?
Documentation looks the same.
Ans:-Use Debug class for debug builds, use Trace class for both debug and
release builds.
311. Why are there five tracing levels in
Ans:-The tracing dumps can be quite verbose and for some applications that are
constantly running you run the risk of overloading the machine and the hard
drive there. Five levels range from None to Verbose, allowing to fine-tune the
tracing activities.

312. Where is the output of TextWriterTraceListener redirected?
Ans:-To the Console or a text file depending on the parameter passed to the
313. How do you debug an ASP.NET Web application?
Ans:-Attach the aspnet_wp.exe process to the DbgClr debugger.
314. What are three test cases you should go through in unit testing?
Ans:-Positive test cases (correct data, correct output),
negative test cases (broken or missing data, proper handling),
exception test cases (exceptions are thrown and caught properly).
315. Can you change the value of a variable while debugging a C#
Ans:-Yes, if you are debugging via Visual Studio.NET, just go to Immediate
316. Explain the three services model (three-tier application).
Ans:-Presentation (UI), business (logic and underlying code) and data (from
storage or other sources).
317. What are advantages and disadvantages of Microsoft-provided
data provider classes in ADO.NET?
Ans:-SQLServer.NET data provider is high-speed and robust, but requires SQL
Server license purchased from Microsoft. OLE-DB.NET is universal for
accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but
it’s a .NET layer on top of OLE layer, so not the fastest thing in the world.
ODBC.NET is a deprecated layer provided for backward compatibility to ODBC
318. What is the wildcard character in SQL? Let’s say you want to query
database with LIKE for all employees whose name starts with La.
Ans:-The wildcard character is %, the proper query with LIKE would involve
319. Explain ACID rule of thumb for transactions.
Ans:-Transaction must be Atomic (it is one unit of work and does not dependent
on previous and following transactions), Consistent (data is either committed
or roll back, no “in-between” case where something has been updated and
something hasn’t), Isolated (no transaction sees the intermediate results of
the current transaction), Durable (the values persist if the data had been
committed even if the system crashes right after).
320. What connections does Microsoft SQL Server support?
Ans:-Windows Authentication (via Active Directory) and SQL Server
authentication (via Microsoft SQL Server username and passwords).
321. Which one is trusted and which one is untrusted?
Ans:-Windows Authentication is trusted because the username and password are
checked with the Active Directory, the SQL Server authentication is untrusted,
since SQL Server is the only verifier participating in the transaction.
322. Why would you use untrusted verificaion?
Ans:-Web Services might use it, as well as non-Windows applications.
323. What does the parameter Initial Catalog define inside Connection
Ans:-The database name to connect to.
324. What’s the data provider name to connect to Access database?
325. What does Dispose method do with the connection object?
Ans:-Deletes it from the memory.
326. What is a pre-requisite for connection pooling?
Ans:-Multiple processes must agree that they will share the same connection,
where every parameter is the same, including the security settings.

327. How big is the datatype int in .NET?
Ans:-32 bits.
328. How big is the char?
Ans:-16 bits (Unicode).
329. How do you initiate a string without escaping each backslash?
Ans:-Put an @ sign in front of the double-quoted string.
330. What are valid signatures for the Main function?
Ans:-public static void Main()
public static int Main()
public static void Main( string[] args )
public static int Main(string[] args )
331. How do you initialize a two-dimensional array that you don’t know
the dimensions of?
Ans:-int [, ] myArray; //declaration
myArray= new int [5, 8]; //actualinitialization
332. What’s the access level of the visibility type internal?
Ans:-Current assembly.
333. What’s the difference between struct and class in C#?
Ans:-Structs cannot be inherited.
Structsare passed by value, not by reference.
Structis stored on the stack, not the heap.
334. What data type should you use if you want an 8-bit value that’s
335. Speaking of Boolean data types, what’s different between C# and
Ans:-There’s no conversion between 0 and false, as well as any other number
and true, like in C/C++.
336. Where are the value-type variables allocated in the computer
337. Where do the reference-type variables go in the RAM?
Ans:-The references go on the stack, while the objects themselves go on the
338. What is the difference between the value-type variables and
reference-type variables in terms of garbage collection?
Ans:-The value-type variables are not garbage-collected, they just fall off the
stack when they fall out of scope, the reference-type objects are picked up by
GC when their references go null.
339. How do you convert a string into an integer in .NET?
340. How do you box a primitive data type variable?
Ans:-Assign it to the object, pass an object.
341. Why do you need to box a primitive variable?
Ans:-To pass it by reference.
342. What’s the difference between Java and .NET garbage collectors?
Ans:-Sun left the implementation of a specific garbage collector up to the JRE
developer, so their performance varies widely, depending on whose JRE you’re
using. Microsoft standardized on their garbage collection.
343. How do you enforce garbage collection in .NET?
344. Can you declare a C++ type destructor in C# like ~MyClass()?

Ans:-Yes, but what’s the point, since it will call Finalize(), and Finalize() has no
guarantees when the memory will be cleaned up, plus, it introduces additional
load on the garbage collector.
345. What’s different about namespace declaration when comparing
that to package declaration in Java?
Ans:-No semicolon.
346. What’s the difference between const and readonly?
Ans:-You can initialize readonly variables to some runtime values. Let’s say your
program uses current date and time as one of the values that won’t change.
This way you declare public readonly string DateT = new
347. What does \a character do?
Ans:-On most systems, produces a rather annoying beep.
348. Can you create enumerated data types in C#?
349. What’s different about switch statements in C#?
Ans:-No fall-throughs allowed.
350. What happens when you encounter a continue statement inside
the for loop?
Ans:-The code for the rest of the loop is ignored, the control is transferred back
to the beginning of the loop.
351. Is goto statement supported in C#? How about Java?
Ans:-Gotos are supported in C#to the fullest. In Java goto is a reserved keyword
that provides absolutely no functionality.
352. What’s the implicit name of the parameter that gets passed into
the class’ set method?
Ans:-Value, and it’s datatype depends on whatever variable we’re changing.
353. How do you inherit from a class in C#?
Ans:-Place a colon and then the name of the base class. Notice that it’s double
colon in C++.
354. Does C# support multiple inheritance?
Ans:-No, use interfaces instead.
355. When you inherit a protected class-level variable, who is it
available to?
Ans:-Classes in the same namespace.
356. Are private class-level variables inherited?
Ans:-Yes, but they are not accessible, so looking at it you can honestly say that
they are not inherited. But they are.
357. Describe the accessibility modifier protected internal.
Ans:-It’s available to derived classes and classes within the same Assembly (and
naturally from the base class it’s declared in).
358. C# provides a default constructor for me. I write a constructor that
takes a string as a parameter, but want to keep the no parameter
one. How many constructors should I write?
Ans:-Two. Once you write at least one constructor, C# cancels the freebie
constructor, and now you have to write one yourself, even if there’s no
implementation in it.
359. What’s the top .NET class that everything is derived from?
360. Can you declare the override method static while the original
method is non-static?
Ans:-No, you can’t, the signature of the virtual method must remain the same,
only the keyword virtual is changed to keyword override.
361. Can you override private virtual methods?

Ans:-No, moreover, you cannot access private methods in inherited classes, have
to be protected in the base class to allow any sort of access.
362. Can you prevent your class from being inherited and becoming a
base class for some other classes?
Ans:-Yes, that’s what keyword sealed in the class definition is for. The developer
trying to derive from your class will get a message: cannot inherit from
Sealed class WhateverBaseClassName. It’s the same concept as final class in
363. Can you allow class to be inherited, but prevent the method from
being over-ridden?
Ans:-Yes, just leave the class public and make the method sealed.
364. When do you absolutely have to declare a class as abstract (as
opposed to free-willed educated choice or decision based on UML
Ans:-When at least one of the methods in the class is abstract. When the class
itself is inherited from an abstract class, but not all base abstract methods
have been over-ridden.
365. What’s an interface class?
Ans:-It’s an abstract class with public abstract methods all of which must be
implemented in the inherited classes.
366. Why can’t you specify the accessibility modifier for methods inside
the interface?
Ans:-They all must be public. Therefore, to prevent you from getting the false
impression that you have any freedom of choice, you are not allowed to
specify any accessibility, it’s public by default.
367. Can you inherit multiple interfaces?
Ans:-Yes, why not.
368. And if they have conflicting method names?
Ans:-It’s up to you to implement the method inside your own class, so
implementation is left entirely up to you. This might cause a problem on a
higher-level scale if similarly named methods from different interfaces expect
different data, but as far as compiler cares you’re okay.
369. What’s the difference between an interface and abstract class?
Ans:-In the interface all methods must be abstract, in the abstract class some
methods can be concrete. In the interface no accessibility modifiers are
allowed, which is ok in abstract classes.
370. How can you overload a method?
Ans:-Different parameter data types, different number of parameters, different
order of parameters.
371. If a base class has a bunch of overloaded constructors, and an
inherited class has another bunch of overloaded constructors, can
you enforce a call from an inherited constructor to an arbitrary
base constructor?
Ans:-Yes, just place a colon, and then keyword base (parameter list to invoke the
appropriate constructor) in the overloaded constructor definition inside the
inherited class.
372. What’s the difference between System.String and
System.StringBuilder classes?
Ans:-System.String is immutable, System.StringBuilder was designed with the
purpose of having a mutable string where a variety of operations can be
373. What is the difference between a component and a container?
Ans:-A component is an object, like a button or a sroll bar, that has a visual
representation in a sreen window. A container is a window-like component

that can contain other components.Every component has a unique container
that directly contains it.
374. What is the difference between a constructor and a method?
Ans:-A constructor is a member function of a class that is used to create objects
of that class. It has the same name as the class itself, has no return type, and
is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a
return type (which may be void), and is invoked using the dot operator.
375. What are the advantages and disadvantages of using an AVL tree?
Ans:-The advantage of an AVL tree is that it is always balanced, guaranteeing the
O(lgn) speed of the Binary Search algorithm.
The disadvantages the complex rotations used by the insertion and removal
algorithms needed to maintain the tree’s balance.
376. Describe the role of inetinfo.exe, aspnet_isapi.dll and
aspnet_wp.exe in the page loading process.
Ans:-inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests
among other things.When an ASP.NET request is received (usually a file with
.aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing
the request tothe actual worker process aspnet_wp.exe.
377. What’s the difference between Response.Write()
Ans:-The latter one allows you to write formattedoutput.
378. What methods are fired during the page load?
Ans:-Init() - when the pageis instantiated, Load() - when the page is loaded into
server memory,PreRender() - the brief moment before the page is displayed
to the user asHTML, Unload() - when page finishes loading.
379. Where does the Web page belong in the .NET Framework class
380. Where do you store the information about the user’s locale?
381. What’s the difference between Codebehind="MyCode.aspx.cs"
Ans:-CodeBehind is relevant to Visual Studio.NET only.
382. What’s a bubbled event?
Ans:-When you have a complex control, likeDataGrid, writing an event processing
routine for each object (cell, button,row, etc.) is quite tedious. The controls
can bubble up their eventhandlers, allowing the main DataGrid event handler
to take care of itsconstituents.
383. Suppose you want a certain ASP.NET function executed on
MouseOver overa certain button. Where do you add an event
Ans:-It’s the Attributesproperty, the Add function inside that property. So
384. What data type does the RangeValidator control support?
Ans:-Integer,String and Date.
385. What is normalization? Explain different levels of normalization?
Ans:-Normalization is the bottom-up approach for reducing redundancy. It is step
bystep decomposition ofcomplex records into simple records.
A table is said to be in1NF when each cell of the table contains precisely one
A table is said to be in 2NF when it is in 1NF and every attribute in the record
is functionally dependent on the whole key, and not just a part of the key.

A table is said to be in 3NF when it is in 2 NF and evey non-key attribute
isfunctonally dependent on just the primary key.
386. What is denormalization and when would you go for it?
Ans:-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.
387. How do you implement one-to-one, one-to-many and many-to-
many relationships while designing tables?
Ans:-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.
388. What’s the difference between a primary key and a unique key?
Ans:-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.
389. What are user defined datatypes and when you should go for
Ans:-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.
390. What is bit datatype and what’s the information that can be stored
inside a bit column?
Ans:-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.
391. Define candidate key, alternate key, composite key.
Ans:-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.
392. What are defaults? Is there a column to which a default can’t be
Ans:-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 DEFAULT in books online.
393. What’s the maximum size of a row?
Ans:-8060 bytes. Don’t be surprised with questions like ‘what is the maximum
number of columns per table’. 1024 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.
394. What is lock escalation?
Ans:-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.
395. What’s the difference between DELETE TABLE and TRUNCATE
TABLE commands?
Ans:-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. TRUNCATE TABLE is
functionally identical to DELETE statement with no WHERE clause: both
remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer
system and transaction log resources than DELETE. The DELETE statement
removes rows one at a time and records an entry in the transaction log for
each deleted row. TRUNCATE TABLE removes the data by deallocating the
data pages used to store the table’s data, and only the page deallocations are
recorded in the transaction log. TRUNCATE TABLE removes all rows from a
table, but the table structure and its columns, constraints, indexes and so on
remain. The counter used by an identity for new rows is reset to the seed for
the column. If you want to retain the identity counter, use DELETE instead. If
you want to remove table definition and its data, use the DROP TABLE
statement. You cannot use TRUNCATE TABLE on a table referenced by a
FOREIGN KEY constraint; instead, use DELETE statement without a WHERE
clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
TRUNCATE TABLE may not be used on tables participating in an indexed view
396. Explain the storage models of OLAP
Ans:-Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more
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
an explanation of these constraints see books online for the pages titled:
"Constraints" and "CREATE TABLE", "ALTER TABLE"

397. What 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?
Ans:-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 create 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
398. What is RAID and what are different types of RAID configurations?
Ans:-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
399. What are the steps you will take to improve performance of a poor
performing query?
Ans:-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
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
400. What are the steps you will take, if you are tasked with securing
an SQL Server?
Ans:-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
401. What is a deadlock and what is a live lock? How will you go about
resolving deadlocks?
Ans:-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.
402. What is blocking and how would you troubleshoot it?
Ans:-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
creating databases from the Enterprise Manager or by just issuing the
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.
403. How to restart SQL Server in single user mode? How to start SQL
Server in minimal configuration mode?
Ans:-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 configuration mode. Check out SQL
Server books online for more parameters and their explanations.
404. As a part of your job, what are the DBCC commands that you
commonly use for database maintenance?
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
405. What are statistics, under what circumstances they go out of date,
how do you update them?
Ans:-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
sp_createstats, sp_updatestats
406. What are the different ways of moving data/databases between
servers and databases in SQL Server?
Ans:-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.
Explain 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 Sever 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.
407. What is database replication? What are the different types of
replication you can set up in SQL Server?
Ans:-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.
408. How to determine the service pack currently installed on SQL
Ans:-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.
409. What are cursors? Explain different types of cursors. What are the
disadvantages of cursors? How can you avoid cursors?
Ans:-Cursors allow row-by-row processing 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 roundtrip, however large the resultset is. Cursors are also
costly because they require more resources and temporary storage (results in
more IO operations). Further, 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.
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".
410. Can you have a nested transaction?
Ans:-Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN
411. What is an extended stored procedure? Can you instantiate a COM
object by using T-SQL?
Ans:-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.
412. What is the system function to get the current user’s user id?
Ans:-USER_ID(). Also check out other system functions like USER_NAME(),
413. What are triggers? How many triggers you can have on a table?
How to invoke a trigger on demand?
Ans:-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
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
SELECT t1.empname [Employee], COALESCE(t2.empname, ‘No manager’)
[Manager] FROM emp t1 LEFT OUTER JOIN emp t2 ON t1.mgrid = t2.empid
414. What are some popular RDBMSs which support SQL?
Microsoft SQL server
Centura SQLBase (bundled with SQLWindows)
Sybase SQLAnywhere (bundled with PowerBuilder)
Pervasive.SQL (bundled with many accounting packages)
Borland Database Engine/InterBase (bundled with Delphi)
415. What are the different kinds of database management systems?
While hierarchical and network databases are older than relational
databases,object and object - relational databases are of relatively recent
416. What are the features of a hierarchical database?
Ans:-The main structures used by the hierarchical model are record types and
parent-child relationship between a parent record type and a child record
type. Access to lower level data elements must first access their parents.
Relationships are strictly hierarchical in that a record type can participate as
child in at most one parent-child relationship type. This restriction makes it
difficult to represent a database where numerous relationships exist. While
storage and retrieval are very fast, it is difficult to query a hierarchical
database, and impossible to build decision support systems based on it.
IMS is an example of a hierarchical database.
417. What are the features of a network database?
Ans:-The network model assumes a more complex interrelationship (many to
many) between data elements. Relationships and access paths are still
predetermined and usually fixed but less restrictive. A record type can
participate as owner or member in any number of set types. This is the main
distinction between the network model and the hierarchical model. So, the

network model has a better modeling capability than does the hierarchical
418. What are the features of a relational database?
Ans:-The relational model makes no presumptions about the interrelationships
between data elements. Relationships are represented by one table,
containing key data extracted from another table. Relations are dynamic and
determined as needed.
In a relational database, everything is stored in tables. Tables contain
columns and rows. In formal relational theory, first proposed by E.F.Codd,
tables are known as relations and that is why these came to be known as
relational databases. Creation of these tables and their columns is done using
SQL. Similarly storage and retrieval of data is also done using SQL.
419. What are the features of an object database?
Ans:-Object databases allow you to store complex data types or objects. Further
more, it supports inheritence, polymorphism, and encapsulation for full
object-oriented development.
420. What are the features of an object-relational database?
Ans:-This is a hybrid type of database. The relational database server is usually
extended to support objects as if they are new data types.
421. What is an Entity-Relationship(E-R) diagram?
Ans:-A useful technique in designing your database is to draw a picture of your
tables showing the relationship between tables. This graphical display of a
database is called an Entity-Relationship or an E-R diagram.
422. What is referential integrity?
Ans:-A feature provided by RDBMSs that prevents users or applications from
entering inconsistent data. Most RDBMSs have various referential integrity
rules that you can apply when you create a relationship between two tables.
These rules help in preserving the integrity of the data. In simple terms
referential integrity constraints make sure that there are no orphan records.
Let us say you have an 'employee' table that has a foreign key that points to
'department_id', which is a key in the 'department' table. Referential integrity
will prevent you from deleting a department that has employees assigned to
it. This is known as a restriction. If you are dealing with 'order' table and
multiple items contained in an order, it is possible for you set it up such a way
that all items in an order get deleted when you delete an order. This is known
as a cascading delete.
423. What is the primary key?
Ans:-The unique identifier for a row of data in a table is the primary key. This can
be a single column or a combination of more than one column, in which case
it is known as a composite key.
424. What is the foreign key?
Ans:-A key column in a table that identifies records in a different table is called a
foreign key.
Let us say that you have an 'order' table and an 'item' table. In the item
table, let us say that your primary key is the combination of 'order_id' and
'item_number'. In this case, the 'order_id' which is the primary key of the
'order' table is a foreign key in the 'item' table.
425. What is an alternate key?
Ans:-Some tables in your database may have other columns which can be used
as a key, which may or may not be unique. These are known as alternate
Let us say you have assigned each employee's Social Security Number as the
primary key. The employee's last name would be an alternate key.
426. What is a composite key?

Ans:-When the rows of a table can be uniquely identified only by a combination
of more than one column, it is said to have a composite key.
'course_id' and 'start_date' together may uniquely identify each row in a
'session' table. In this case, we will say that the 'course' table has a
composite key.
427. What is normalization?
Ans:-Normalization is a series of rules that we apply on the preliminary database
design to eliminate redundancy and incosistency. Simply stated, normalization
is the process of removing redundant data from relational tables by splitting a
relational table into smaller tables. The new tables can be recombined by a
natural join (using SQL) to recreate the original table without creating any
spurious or redundant data. Though there can be more stages to normalizing
a database, the basic process involves three stages.
428. What are the three normal forms?
Ans:-First normal form: Remove repeating groups.
If, in the employee table, you have a column name_of_children, this will have
more than one value for some of the employees.
Second normal form: Remove columns that do not depend on the whole key.
If, in the item table, you have some attributes of the order, then it will depend
on only part of the key (namely, the order_number).
Third normal form: Remove columns that do not depend only on the key.
If, in the order table, you have some attributes of the item, then it will not
depend only on the key (it will depend on order_number and
429. Columns must depend on the key, the whole key and nothing but
the key!
Ans:-What do you do with all those columns that you removed? Make them into
separate tables.
430. True or False: A Web service can only be written in .NET
431. Which event triggers when user moves to another form
432. call back ?
Ans:-A callback is a function, provided by a client to a subsystem, that allows
that subsystem to perform a specific operation in the context of the client

433. tell me some interfaces of COM

Ans:-IunKnown: Every Com component should inherit from this interface
Idispatch: for late binding, Dynamic Invocation
Iolecontrol: for controls
Ioleobject: Embeding objects in compound documents
Istorage,Istream: Structure Storage
Imoniker: Identifies objects and knows how to activate them
Itypeinfo: Type information can be accessed through this
Idataobject: Uniform Data Transfer,nClipboard, Drag & Drop or Compound
Iolelink:Documents that contain other objects
Ioleclient: Linking object to compound documents
Ioleinplaceobject: Editing an object with in a container
IEnumConnections: for implementing connection points
IspecifyPropertyPages:Client manipulation of property pages

434. which tag is used for creating activex control
Ans:-<Object> tag. If you create ActiveX using they are called to Static Objects
435. for language intorp what u will do
Ans:-Just maintaing the code CLS compliant
436. what Manifest Contains
Ans:-Manifest is table with info records.Manifest contains info about: Assembly
437. ,Version information, Strong name information, Culture information,
Processor and OS, Files that make up this assembly, References to types
and resources,Exported and local types
438. Give three examples of how an ASP.NET Web application is
different from a traditional Windows application.
Ans:-Web applications and traditional Windows applications have the following
Unmanaged Windows
Feature ASP.NET Web application
Architecture Client/server. Local user.
Runs under common language Runs under Windows using
runtime using managed code. unmanaged code.
User interface is displayed in an
User interface is displayed by the
User interface Internet browser using Web
application using the Win32 API.
439. How do you restore the default window settings in V S .NET?
Ans:-From the Tools menu, choose Options and then click Reset Window Layout.
440. Why doesn' t the Visual Studio .NET Code Editor automatically
complete the following partial line of code (Visual C# users only)?
int intX = system.math
Ans:-The namespace System.Math must be capitalized in Visual C# for
IntelliSense to recognize the namespace.
441. When can' t you use ASP.NET to create a Web application?
Ans:-When you are developing for non-Microsoft Windows Web servers, such as
442. Explain where Visual Studio .NET stores Web application projects.
Ans:-Web application projects are stored in a new virtual folder for each project.
The properties of that virtual folder determine where the files are physically
stored. These properties can be viewed in IIS.
443. List the four major differences between Web and Windows
Ans:-Web forms cannot use the standard Windows controls. Instead, they use
server controls, HTML controls, user controls, or custom controls created
specially for Web forms.
Web applications are displayed in a browser. Windows applications display
their own windows and have more control over how those windows are
Web forms are instantiated on the server, sent to the browser, and destroyed
immediately. Windows forms are instantiated, exist for as long as needed, and
are destroyed.
Web applications run on a server and are displayed remotely on clients.
Windows applications run on the same machine they are displayed on.
444. Describe the life cycle of a Web application: When are Web forms
instantiated and how long do they exist?
Ans:-A Web application starts with the first request for a resource within the
application' s boundaries. Web forms are instantiated when they are
requested. They are processed by the server and are abandoned immediately

after the server sends its response to the client. A Web application ends after
all client sessions end.
445. How do you preserve persistent data, such as simple variables, in a
Web application?
Ans:-You can preserve data in state variables, such as ApplicationState,
SessionState, or ViewState.
446. What determines the boundaries of a Web application?
Ans:-IIS determines Web application boundaries by the structure of the appli-
cation' s virtual folders. A Web application boundary starts in the folder
containing the start page of the application and it ends at the last subordinate
folder or when it encounters another start page in a subordinate folder.
447. How does the .NET Framework organize its classes?
Ans:-The .NET Framework uses namespaces to organize its classes.
448. In Visual Basic .NET, what is difference between a class module
and a code module?
Ans:-Class modules are instantiated at run time to create objects that provide
separate storage for variables and properties in each instance. Code modules
do not have instances, so any module-level variables they use are shared
among calls to the module' s procedures.
449. In Visual C#, how do you declare a method to make it available
without having to first instantiate an object from the class?
Ans:-To create a method that can be called without instantiating an object,
declare that method as static.
450. How do you call a member of a base class from within a derived
Ans:-To refer to a member of a base class in Visual Basic .NET, use the MyBase
keyword. To refer to a member of a base class in Visual C#, use the base
451. What are the four main objects used in Web application
Ans:-The four main objects in Web application programming are the Application,
Page, Request, and Response objects.
452. Where would you save the following data items so that they
persist between requests to a Web form?
Ans:-A control created at run time
Save controls created at run time in the Page object' s ViewState.
An object that provides services to all users
Save objects that provide services to all users in the Application state.
User preferences
Save user preferences in SessionState.
453. What is the main difference between the Button server control and
the Button HTML control?
Ans:-When clicked, the Button server control triggers an ASP.NET Click event
procedure on the server. The Button HTML control triggers the event
procedure indicated in the button' s onclick attribute, which runs on the client.
454. How do you get several RadioButton controls to interoperate on a
Web form so that only one of the RadioButtons can be selected at
Ans:-Set the GroupName property of each RadioButton to the same name.
455. Why does ASP.NET perform validation on both the client and the
Ans:-Client-side validation helps avoid round trips to the server. Validating on the
client makes sure that the data is valid before it is submitted, in most cases.
However, because validation might be turned off (or maliciously hacked) on
the client, data must be revalidated on the server side. This provides full

assurance that the data is valid while avoiding as many round trips as
456. What types of validation would you use to verify that a user
entered a valid customer number?
Ans:-You would use a RequiredFieldValidator and a RegularExpressionValidator. If
you have access to a list of expected customer numbers, you could replace
the RegularExpressionValidator with a CustomValidator that checked the list.
457. What is wrong with the following line of code?
Visual Basic .NET
Visual C#
Ans:-You can' t use the Transfer method with HTML pages. It works only with
.aspx pages.
458. Why can' t you open a new browser window from within server
Ans:-Server code executes on the server, whereas the new window is created on
the client. You need to use client-side code to do things that affect the client,
such as upload files, display new windows, or navigate back in history.
459. What steps would you follow and what objects would you use to
quickly find the number of records in a database table?
Ans:-There are two ways to accomplish this task:
Use a database connection and a command object to execute a SQL command
that returns the number of rows in the table.
Use a database connection and data adapter object to create a data set for
the table, and then get the number rows in the data set.
460. How do typed data sets differ from untyped data sets, and what
are the advantages of typed data sets?
Ans:-Typed data sets use explicit names and data types for their members,
whereas untyped data sets use collections to refer to their members. The
following examples show a typed reference vs. an untyped reference to a data
Visual Basic .NET
' Typed reference to the Contacts table's HomePhone column.
DataSet1.Contacts.HomePhoneColumn.Caption = "@Home"
' Untyped reference to the Contacts table's HomePhone column.
DataSet1.Tables("Contacts").Columns("HomePhone").Caption = "@Home"
Visual C#
// Typed reference to the Contacts table's HomePhone column.
DataSet1.Contacts.HomePhoneColumn.Caption = "@Home";
// Untyped reference to the Contacts table's HomePhone column.
DataSet1.Tables["Contacts"].Columns["HomePhone"].Caption = "@Home";
Typed data sets do error checking at design time. This error checking helps
catch typos and type mismatch errors, which would be detected only at
run time with untyped data sets.
461. How do you reuse a database connection component throughout a
Web application?
Ans:-Add the database connection component to the Global.asax file, then create
a state variable in the Application_Start or Session_Start event procedures to
share the connection with the Web forms in the application.
462. Explain the difference between handling transactions at the data
set level and at the database level.
Ans:-Data sets provide implicit transactions, since changes to the data set aren' t
made permanent in the database until you call the Update method. To handle

transactions in a data set, process the Update method and check for errors. If
errors occur during Update, none of the changes from the data set is made in
the database. You can try to correct the error and resubmit the update, or
you can roll back the changes to the data set using the RejectChanges
Databases provide explicit transactions through the Transaction object. You
create a Transaction object from a database connection, and then assign that
Transaction object to the commands you want to include in the transaction
through the command object' s Transaction property. As you perform the
commands on the database, you check for errors. If errors occur, you can
either try to correct them and resubmit the command, or you can restore the
state of the database using the Transaction object' s RollBack method. If no
errors occur, you can make the changes permanent by calling the transaction
object' s Commit method.
463. Explain why exception handling is important to a completed
Ans:-When an unhandled exception occurs in an application, the application stops
—the user can' t proceed, and any work he or she did immediately prior to
the exception is lost. Exception handling provides a way to intercept and
correct unusual occurrences that would otherwise cause these problems.
464. List two different exception-handling approaches in ASP.NET Web -
Ans:-Exceptions can be handled in exception-handling blocks using the Try,
Catch, and Finally keywords in Visual Basic .NET or the try, catch, and finally
keywords in Visual C#. They can also be handled using Error event
procedures at the Global, Application, or Page levels using the Server object' s
GetLastError and ClearError methods.
465. Describe the purpose of error pages and why they are needed.
Ans:-Because Web applications run over the Internet, some exceptions occur
outside the scope of the application. This means that your application cannot
respond directly to these exceptions. These types of exceptions are identified
by HTTP response codes, which IIS can respond to by displaying custom error
pages listed in your application' s Web.config file.
466. Explain why tracing helps with exception handling.
Ans:-Tracing allows you to record unusual events while your application is
running, without users being aware of it. If an unanticipated exception occurs,
your application can write a message to the trace log, which helps you
diagnose problems during testing and after deployment.
467. Write the HTML for a hyperlink that will send mail when the user
clicks the link.
Ans:-<a href=" from a client&BOD
message text.">Send mail</a>
Show the code that writes a cookie containing the user name “Rob Young”
and the current date to the user' s computer. Set the cookie to remain on
the user' s computer for 30 days.
Visual Basic .NET
Dim cookUserInfo As New HttpCookie("UserInfo")
cookUserInfo("Name") = "Rob Young"
cookUserInfo("Time") = DateTime.Now.ToString()
cookUserInfo.Expires = DateTime.Now.AddDays(30)
Visual C#
HttpCookie cookUserInfo = new HttpCookie("UserInfo")
CookUserInfo["Name"] = "Rob Young"

CookUserInfo["Time"] = DateTime.Now.ToString()
cookUserInfo.Expires = DateTime.Now.AddDays(30)
468. Why can' t you open a new browser window using server-side
code? How would you display a page in a new window with a
client-side script?
Ans:-Server-side code can execute tasks only on the server. To perform a task on
the client' s computer, such as opening a new browser window, the code
needs to run on the client.
You can open a new window using the DOM window object. For example, the
following HTML Button control opens a Help page in a new window:
<button id="butHelp"
onclick="'help.aspx', 'help', 'height=200,width=300')">Help</
469. How do you display a page in one frame from a hyperlink in
another frame?
Ans:-Use the <a> element' s target attribute to specify the frame to display the
page. For example, the following hyperlink displays a page in the main frame
of a frameset:
<a href="AllTheAnswers.aspx" target="main">Show the answers!</a>
470. Which ASP.NET authentication mode is best suited to identifying
and authorizing users who belong to a corporate network?
Ans:-Windows integrated authentication is best suited to authenticating users of
a corporate network because it uses the accounts and permissions that
already exist for network users.
471. What is the difference between Windows and Forms authentication
users lists in Web.config?
Ans:-Users lists for Windows authentication are included in the <authorization>
element of Web.config.
472. Users lists for Forms authentications are included in the
<credentials> element of Web.config or as part of an external
users database or file.
Ans:-How do you require authentication using the Web.config file? (The answer is
the same for all ASP.NET authentication modes.)
Include the following <authorization> element to require authentication:
<deny users="?" />
473. How does the Secure Sockets Layer (SSL) provide security in a
Web application?
Ans:-SSL protects data exchanged between a client and a Web application by
encrypting the data before it is sent across the Internet.
474. How do you begin and end secure communication via SSL?
Ans:-To begin secure communication, specify the https protocol in an address.
For example:
<a href="">Secure page.</a>
To end secure communication, specify the http protocol. For example:
<a href="">Not secure.</a>
475. What permissions do Web applications run under by default?
Ans:-By default, Web applications run as the ASPNET user, which has limited
permissions equivalent to the Users group.
476. Why is the Machine.config file important to deployed Web

Ans:-The Machine.config file controls many aspects of how Web applications run,
including how processes are recycled, what types of request queue limits are
imposed, and what interval is used when checking if users are still connected.
477. How do you set cache options for a Web application?
Ans:-Use the FrontPage Server Extensions in IIS to set the page caching options
for a Web application.
478. How does deploying to a Web farm or a Web garden affect Session
state in a Web application?
Ans:-Web applications that are deployed to a Web farm or a Web garden need to
identify a Session state provider in their Web.config file. This is because a
single client' s requests can be directed to different processes over the course
of his or her session. The Session state provider allows each different process
to access the client' s Session state.
479. How do unit, integration, and regression testing relate to each
Ans:-Unit testing is the foundation that ensures that each piece of code works
correctly. Integration testing extends this concept by verifying that pieces
work together without errors. Regression tests are made up of the existing
unit and integration tests, which are run on a regular schedule to assure that
new code did not break previously working code.
480. Why is load testing likely to be more important for a Web
application than for a stand-alone Windows application?
Ans:-Because Web applications can be public on the Internet, they can have
hundreds, thousands, or even millions of users. Load tests let you simulate
the expected demand to locate resource conflicts, performance bottlenecks,
and other problems that aren' t apparent in single-user tests.
481. What is the difference between the Debug and Trace classes?
Ans:-Under the default environment settings, code using the Debug class is
stripped out of release builds, while code using the Trace class is left in. The
classes are otherwise equivalent.
482. What are the two special steps you need to take to ensure that a
COM component can use a component from a .NET assembly?
Ans:-You must register the .NET assembly in the system registry using
You must make sure that the COM component can find the .NET assembly,
either by placing the .NET assembly in the global assembly cache, by placing
the two components in the same folder, or by following the other assembly-
probing rules.
483. Briefly describe the best uses for each of the three types of Web
controls by completing the following sentences:
Create a user control when you want to…
…quickly create a group of controls that can be reused throughout a project to
perform some logical unit of work.
Create a composite custom control when you want to…
…combine one or more existing controls into a compiled assembly that can be
easily reused in many different projects.
Create a rendered control when you want to…
…build an entirely new control that can be compiled into an assembly for use
in multiple projects.
484. How is deriving important to creating custom Web controls?
Ans:-Both composite and rendered custom controls are derived from the
WebControl base class. That class provides the methods that you override to
create the appearance of the custom control.
485. What is the most important method to override when creating a
composite custom control?

Ans:-You override the CreateChildControls method to add existing controls to a
composite custom control.
486. What is the most important method to override when creating a
rendered control?
Ans:-You override the Render method when creating a rendered custom control.
487. How is raising a post-back event in a composite control different
from raising a post-back event in a rendered control?
Ans:-In a composite control, you can use one of the contained controls to raise a
post-back event. In a rendered control, you must implement the
IPostBackEventHandler interface and write a client-side script to raise a post-
back event.
488. Why do you usually control multimedia from client-side scripts,
rather than from server-side code?
Ans:-Intercepting events on the server requires the page to be redisplayed.
Redisplaying a page restarts most media, such as sounds and video.
489. Which HTML sound and video elements are supported by most
Ans:-Most browsers support these HTML elements: bgsound, img, and embed.
490. How do you support Netscape Navigator users within an ActiveX
object element?
Ans:-Nest an HTML embed element containing an equivalent Netscape plug-in
within the ActiveX HTML object element. You will also need to modify or
disable client-side code that controls the ActiveX object if the user' s browser
is Netscape Navigator.
491. What central feature does HTML+TIME provide that is not available
with other animation techniques?
Ans:-HTML+TIME allows you to synchronize timed events on a page.
492. List two ways to create a new timeline using HTML+TIME.
Ans:-Use one of the timeline elements, such as t:SEQ, t:EXCL, or t:PAR.
Add a TIMECONTAINER attribute to a standard HTML element.
493. What is the advantage of using CSS rather than in-line styles for
formatting a Web application?
Ans:-Using CSS allows you to maintain formatting separately from the content of
your Web forms, so changes are easier to make and consistency is easier to
494. Why would you create a style for a class rather than for an HTML
Ans:-You create style classes when you want to apply the same formatting to
different types of elements within an application. For example, you might
want to create an emphasis style class that applies the same formatting to
any text, control, heading, or image that you want to draw the user' s
attention to.
495. How do CSS and XSL relate to each other when it comes to
formatting a Web application?
Ans:-CSS and XSL are complementary techniques for formatting. CSS determines
the font, color, size, background, and other appearance aspects of HTML
elements on a Web page. XSL is used to transform XML files into HTML
output. In this way, XSL controls the position and appearance of items based
on their content. Used together, XSL performs the high-level tasks of
composition and layout while CSS performs the low-level tasks of applying
fonts, colors, and other appearance features.
496. What are the differences between HTML and XML?
Ans:-HTML uses predefined element names, such as <p> and <br>. In XML, you
create your own element names to identify hierarchical nodes of data.

XML syntax is much stricter than HTML: elements must always have end-tags,
element names are case sensitive, attribute values must always be enclosed
in quotation marks, and nested elements must be terminated within their
parent elements.
XML identifies data conceptually based on the data' s content, rather than
based on the type of formatting to apply.
497. Which HTML attribute does the server control' s Tooltip property
map to in the HTML rendered by ASP.NET?
Ans:-The Tooltip property is rendered as the title attribute at run time.
498. How does displaying HTML Help using the window object' s
showHelp method differ from displaying HTML Help using a
browser window?
Ans:-The showHelp method cannot open compiled HTML Help from a network
address; the compiled file must first be downloaded to the user' s machine.
You can display HTML Help from a network address within a browser window,
provided you use the ms-its: protocol. However, the HTML Help Contents,
Index, and Search features are not automatically available from a browser
499. How do you add index keywords to a Help topic?
Ans:-Insert an object element in the Help topic using the HTML Help ActiveX
control. For example, the following object element adds the "numbers" index
<Object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-
<param name="Keyword" value="numbers">
500. What is the difference between the CurrentCulture property and
the CurrentUICulture property?
Ans:-The CurrentCulture property affects how the .NET Framework handles
dates, currencies, sorting, and formatting issues. The CurrentUICulture
property determines which satellite assembly is used when loading resources.
501. How do you detect the user' s culture?
Ans:-Use the Request object' s UserLanguages array. The value at element 0
corresponds to one of the culture codes used by the CultureInfo class. For
SLang = Request.UserLanguages(0)
What is a neutral culture?
Neutral cultures represent general languages without region-specific
differences, such as currency. For example, the “es” culture code represents
502. Briefly describe the major components of the .NET Framework and
describe what each component does.
Ans:-The .NET Framework consists of two primary parts: the common language
runtime, which manages application execution, enforces type safety, and
manages memory reclamation, and the .NET base class library, which consists
of thousands of predeveloped classes that can be used to build applications.
503. Briefly explain what is meant by a reference type and a value type.
Ans:-A value type holds all of the data represented by the variable within the
variable itself. A reference type contains a reference to a memory address
that holds the data instead of the actual data itself.
504. How do you enable your application to use .NET base class library
members without referencing their fully qualified names?
Ans:-Use the Imports keyword (Visual Basic .NET) or the using keyword (Visual
C#) to make a .NET Framework namespace visible to your application.

505. Briefly describe how garbage collection works.
Ans:-The garbage collector is a thread that runs in the background of managed
.NET applications. It constantly traces the reference tree and attempts to find
objects that are no longer referenced. When a nonreferenced object is found,
its memory is reclaimed for later use.
506. Briefly describe what members are, and list the four types of
Ans:-Members are the parts of a class or a structure that hold data or implement
functionality. The primary member types are fields, properties, methods, and
507. Explain what constructors and destructors are and describe what
they are used for.
Ans:-The constructor is the method that initializes a class or structure and is run
when a type is first instantiated. It is used to set default values and perform
other tasks required by the class. A destructor is the method that is run as
the object is being reclaimed by garbage collection. It contains any code that
is required for cleanup of the object.
508. Briefly explain the difference between Public (public), Friend
(internal), and Private (private) access levels as they apply to
user-defined types and members.
Ans:-In user-defined types, Public (public) classes can be instantiated by any
element of the application. Friend (internal) classes can be instantiated only
by members of the same assembly, and Private (private) classes can be
instantiated only by themselves or types they are nested in. Likewise, a Public
(public) member can be accessed by any client in the applica-tion, a Friend
(internal) member can be accessed only from members of the same
assembly, and Private (private) members can be accessed only from within
the type.
509. Do you need to instantiate a class before accessing a Shared
(static) member? Why or why not?
Ans:-Because a Shared (static) member belongs to the type rather than to any
instance of the type, you can access the member without first creating an
instance of the type.
510. You are creating an application for a major bank. The application
should integrate seamlessly with Microsoft Office XP, be easy to
learn, and instill a sense of corporate pride in the users. Name two
ways you might approach these goals in the user interface.
Ans:-Design the user interface to mimic the look and feel of Microsoft Office XP,
which will allow users of Office XP to immediately feel comfortable with the
new application. Integration of the corporate logo and other visual elements
associated with the company will aid in identification of the program with the
511. You are writing an application that needs to display a common set
of controls on several different forms. What is the fastest way to
approach this problem?
Ans:-Create a single form that incorporates the common controls, and use visual
inheritance to create derived forms.
512. If you wanted to prompt a user for input every time a form
received the focus, what would be the best strategy for
implementing this functionality?
Ans:-Write an event handler for the Activated event that implements the relevant
513. Describe two ways to set the tab order of controls on your form.
Ans:-You can set the tab order in Visual Studio by choosing Tab Index from the
View menu and clicking each control in the order you desire. Alternatively,
you can set the TabIndex property either in code or in the Properties window.

514. What is an extender provider, and what does one do?
Ans:-Extender providers are components that provide additional properties to
controls on a form. Examples include the ErrorProvider, HelpProvider, and
ToolTip components. They can be used to provide additional information about
particular controls to the user in the user interface.
515. Explain when you might implement a shortcut menu instead of a
main menu.
Ans:-If every possible option is exposed on a main menu, the menu can become
busy and hard to use. Shortcut menus allow less frequently used options to
be exposed only in situations where they are likely to be used.
516. Describe what is meant by field-level validation and form-level
Ans:-Field-level validation is the process of validating each individual field as it is
entered into a form. Form-level validation describes the process of validating
all of the data on a form before submitting the form.
517. Explain when a type conversion will undergo an implicit cast and
when you must perform an explicit cast. What are the dangers
associated with explicit casts?
Ans:-Types can be implicitly converted when the conversion can always take
place without any potential loss of data. When a potential loss of data is
possible, an explicit cast is required. If an explicit cast is improperly
performed, a loss of data precision can result, or an exception can be thrown.
518. Explain why you might use enums and constants instead of their
associated literal values.
Ans:-Enums and constants make code easier to read and maintain by
substituting human-legible tokens for frequently used constant values.
519. Briefly summarize the similarities and differences between arrays
and collections.
Ans:-Arrays and collections allow you to manage groups of objects. You can
access a particular object by index in both arrays and collections, and you can
use For Each...Next (foreach) syntax to iterate through the members of
arrays and most collections. Arrays are fixed in length, and members must be
initialized before use. Members of collections must be declared and initialized
outside of the collection, and then added to the collection. Collections
provided in the System.Collections namespace can grow or shrink
dynamically, and items can be added or removed at run time.
520. Explain how properties differ from fields. Why would you expose
public data through properties instead of fields?
Ans:-Properties allow validation code to execute when values are accessed or
changed. This allows you to impose some measure of control over when and
how values are read or changed. Fields cannot perform validation when being
read or set.
521. You need to create several classes that provide a core set of
functionality but each must be able to interact with a different set
of objects. Outline a strategy for developing these classes with the
least development time.
Ans:-Create a single class that implements all of the common functionality
required by these classes. Then, use inheritance to create derived classes that
are specific for each individual case.
522. Describe Break mode and some of the available methods for
navigating in Break mode.
Ans:-Break mode allows you to observe program execution on a line-by-line
basis. You can navigate program execution in Break mode by using Step Into,
Step Over, Step Out, Run To Cursor, and Set Next Statement.
523. When would you use the Watch window?

Ans:-You would use the Watch window to observe the values of application
variables while in Break mode.
524. You are deploying a beta version of a large application and want to
collect performance data in text files while the application is in
use. Briefly describe a strategy for enabling this scenario.
Ans:-Place Trace statements that report the data of interest throughout the
application. Create a TextWriterTraceListener and add it to the Listeners
collection. Create Trace switches that control when Trace statements are
executed. Configure the TextWriterTraceListener to write output to a text file.
Then, compile and deploy the application with Trace defined, and enable the
Trace switches in the application .config file.
525. When testing a method, should you test data that is known to be
outside of the bounds of normal operation? Why or why not?
Ans:-Yes. In addition to testing normal data operation, you must test known bad
input to ensure that your application can recover from input errors without a
catastrophic application failure.
526. Briefly explain what each segment of a Try...Catch...Finally
(try...catch...finally) block does.
Ans:-The Try (try) block encloses code that is to be executed. If an exception is
thrown, it can be caught in an appropriate Catch (catch) block where code
that will allow the application to handle the execution will be executed. The
Finally (finally) block contains any code that must be executed whether or not
the exception is handled.
527. What are the major components of a Data Provider, and what
function does each fulfill?
Ans:-An ADO.NET Data Provider is a suite of components designed to facilitate
data access. Every Data Provider minimally includes a Connection object that
provides the actual connection to the data source, a Command object that
represents a direct command to the data source, a DataReader object that
provides connected, forward-only, read-only access to a database, and a
DataAdapter that facilitates disconnected data access.
528. Briefly contrast connected and disconnected data access in
Ans:-In ADO.NET, connected data access is available through the DataReader,
which is a lightweight class designed to provide very fast and efficient data
access. It is severely limited, however, in that it can only provide forward-only
data access, it does not allow editing, and it requires the exclusive use of a
Connection object. In contrast, disconnected data access is facilitated by a
DataAdapter, which manages the commands required for selecting and
updating data. The DataAdapter executes a SELECT command against a
database, opening a data connection just long enough to retrieve the data,
and loads the data into a DataSet, which is an in-memory copy of the data.
When the data is ready to be updated, the Data Provider manages the
updates in the same way, generating the appropriate commands to update
the database and keeping the connection open just long enough to execute
those commands.
529. What are the three possible settings for the CommandType
property of a SqlCommand object or an OleDbCommand object,
and what does each mean?
Ans:-A Command object can have a CommandType property setting of Text,
StoredProcedure, or TableDirect. When set to Text, the command executes
the SQL string that is stored in the Command object's CommandText
property. When set to StoredProcedure, the command accesses a procedure
stored on the database and returns the results. A CommandText setting of
TableDirect indicates that the command should return the entire contents of
the table indicated by the CommandText property.

530. How could you execute DDL commands, such as ALTER or CREATE
TABLE, against a database with ADO.NET?
Ans:-You must use a Command object to execute DDL commands. You can set
the CommandType property to Text and enter the appropriate DDL command
in the CommandText property. Then call Command.ExecuteNonQuery to
execute the command.
531. Briefly discuss the advantages and disadvantages of using typed
DataSet objects.
Ans:-Typed DataSet objects allow you to work with data that is represented as
members of the .NET common type system. This allows your applications to
be aware of the types of data returned in a DataSet and serves to eliminate
errors resulting from invalid casts, as any type mismatches are caught at
compile time. Untyped DataSet objects, however, are useful if you do not
know the structure of your data, and can be used with any data source.
532. How can you manage data currency on a form with several bound
Ans:-Every data source on a form has an associated CurrencyManager object that
keeps that of the "current" record with respect to bound controls. For
convenience, all of the CurrencyManager objects represented on a form are
exposed through the form's BindingContext property. The Position of the
CurrencyManager can be changed, allowing navigation through the records.
533. Describe how to use a DataView to filter or sort data.
Ans:-You can apply sort criteria to a DataView by setting the Sort property to the
name of a column or columns to be sorted by. The data represented in a
DataView object can be filtered by setting the RowFilter property to a valid
filter expression.
534. Briefly describe an XmlDataDocument and how it relates to a
Ans:-An XmlDataDocument is an in-memory representation of data in a
hierarchical Xml format. Each XmlDataDocument is synchronized with a
DataSet. Whenever changes are made to one object, the other is instantly
updated. Thus, you can use the XmlDataDocument to perform XML
manipulations on a DataSet.
535. Briefly describe the three types of user-developed controls and
how they differ.
Ans:-The three types of user-developed controls are inherited controls, user
controls, and custom controls. An inherited control derives from a standard
Windows Forms control and inherits the look, feel, and functionality of that
control. User controls allow you to combine standard Windows Forms controls
and bind them together with common functionality. Custom controls inherit
from Control and are the most development-intensive kind of control. Custom
controls must implement all their own code for painting and inherit only
generic control functionality. All specific functionality must be implemented by
the developer.
536. Describe the roles of Graphics, Brush, Pen, and GraphicsPath
objects in graphics rendering.
Ans:-The Graphics object represents a drawing surface and encapsulates
methods that allow graphics to be rendered to that surface. A Brush is an
object that is used to fill solid shapes, and a Pen is used to render lines. A
GraphicsPath object represents a complex shape that can be rendered by a
Graphics object.
537. Describe the general procedure for rendering text to a drawing
Ans:-You must first obtain a reference to a Graphics object. Next, create an
instance of a GraphicsPath object. Use the GraphicsPath.AddString method to

add text to the GraphicsPath. Then, call the Graphics.DrawPath or
Graphics.FillPath to render the text.
538. Describe the role of the LicenseProvider in control licensing.
Ans:-The LicenseProvider controls license validation and grants run-time licenses
to validly licensed components. The LicenseManager.Validate method checks
for an available license file and checks against the validation logic provided by
the specific implementation of LicenseProvider. You specify which
LicenseProvider to use by applying the LicenseProviderAttribute.
539. Describe how to create a form or control with a nonrectangular
Ans:-Set the Region property of the form or control to a Region object that
contains the irregular shape. You can create a Region object from a
GraphicsPath object.
540. Briefly describe how to use the PrintDocument component to print
a document. Discuss maintaining correct line spacing and
multipage documents.
Ans:-The PrintDocument class exposes the Print method, which raises the
PrintPage event. Code to render printed items to the printer should be placed
in the PrintPage event handler. The PrintPage event handler provides the
objects required to render to the printer in an instance of the
PagePrintEventArgs class. Content is rendered to the printer using the
Graphics object provided by PagePrintEventArgs. You can calculate correct line
spacing by dividing the height of the MarginBounds property by the height of
the font you are rendering. If your document has multiple pages, you must
set the PagePrintEventArgs.HasMorePages property to true, which causes the
PrintPage event to fire again. Because the PrintPage event handler retains no
inherent memory of how many pages have been printed, you must
incorporate all logic for printing multiple pages into your event handler.
541. Explain how to use the Begin and End methods on a Web Service to
make an asynchronous method call.
Ans:-Every public Web method on a Web Service can be called either
synchronously or asynchronously. To make an asynchronous call to a Web
method, you call the method named Begin<webmethod>, where
<webmethod> is the name of the method. This method requires a delegate to
an appropriate callback method and returns a value of IAsyncResult. This
value is returned as a parameter in the callback method. To retrieve the data
returned by the Web method, call End<webmethod>, supplying a reference to
the IAsyncResult returned by Begin<webmethod>. This will allow you to
retrieve the actual data returned by the Web method.
542. Briefly describe the five accessibility requirements of the Certified
for Windows logo program.
Ans:-The five requirements are
Support standard system settings. This requires your application to be able to
conform to system settings for colors, fonts, and other UI elements.
Be compatible with High Contrast mode. This requirement can be met by
using only the System palette for UI colors.
Provide documented keyboard access for all UI features. Key points in this
requirement are shortcut keys and accessible documentation.
Provide notification of the focus location. This requirement is handled
primarily by the .NET Framework.
Convey no information by sound alone. This requirement can be met by
providing redundant means of conveying information.
543. Explain how to use the HelpProvider component to provide help for
UI elements.
Ans:-You can provide either a HelpString or a help topic for UI elements with the
HelpProvider. The HelpProvider provides HelpString, HelpKeyWord, and

HelpNavigator properties for each control on the form. If no value for the
HelpProvider.HelpNameSpace is set, the HelpString will be provided as help. If
the HelpNameSpace is set, the HelpProvider will display the appropriate help
topic as configured by the HelpKeyWord and HelpNavigator properties. Help
for a particular element is displayed when the element has the focus and the
F1 key is pressed.
544. Describe how to create localized versions of a form.
Ans:-To create a localized version of a form, set the Localizable property to true.
Then set the Language property to the language/region for which you want to
create the localized form. Make any localization-related changes in the UI.
The changed property values will automatically be stored in resource files and
loaded when the CurrentUICulture is set to the appropriate CultureInfo.
545. Explain how to convert data in legacy code page formats to the
Unicode format.
Ans:-You can use the Encoding.Convert method to convert data between
encoding types. This method requires instances of both encoding types and
an array of bytes that represents the data to be converted. It returns an array
of bytes in the target format. You can convert a string or array of chars to an
array of bytes with the Encoding.GetBytes method and can convert an array
of bytes back to chars with the Encoding.GetChars method.
546. Explain the difference between Globalization and Localization.
Ans:-Globalization refers to the application of culture-specific format to existing
data. Localization refers to providing new culture-specific resources and
retrieving the appropriate resources based on the culture setting.
547. Describe how to use code to retrieve resources at run time.
Ans:-You must first create an instance of the ResourceManager class that is
associated with the assembly that contains the desired resource. You can then
use the GetString method to retrieve string resources or the GetObject
method to retrieve object resources.
548. Explain how to retrieve information from the configuration file at
run time. How would you store information in the configuration file
at design time?
Ans:-You must first create an instance of AppSettingsReader to read the
configuration file. You can then call the GetValue method to read values
represented in the configuration file. To add configuration file entries, you
should create <add> elements in the <appSettings> node of the
configuration file. In the <add> element, you should specify a value for the
entry and a key that can be used to retrieve the entry. The value can be
changed between executions of the application.
549. You are creating a solution that must be accessed by members of a
group called Developers and Administrators on the local machine.
Describe a plan to implement this security scheme.
Ans:-Create one PrincipalPermission that represents the Developers group and
another PrincipalPermission that represents the BUILTIN\Administrators
group. Then, create a third permission that represents the union of the two by
calling the Union method and demand that permission.
550. Briefly highlight the differences between imperative and
declarative security as they pertain to code access security.
Ans:-Imperative security is implemented by calling methods of Permission
objects in code at run time. Declarative security is configured by attaching
attributes representing permissions to classes and methods. Imperative
security allows a finer control over the point in execution where permissions
are demanded, but declarative security is emitted into metadata, and required
permissions can be discovered through the classes in the System.Reflection
namespace. Additionally, you can request assembly-wide permissions using
the Assembly (assembly) directive with declarative security.

551. Describe XCOPY deployment. Under what conditions is it useful?
When can it not be used?
Ans:-XCOPY deployment is a simple method of deployment where the DOS
command XCOPY is used to copy the application directory and any
subdirectories to the target machine. You can use XCOPY deployment if your
application has no dependency on shared files and requires no special actions
to be taken upon deployment. If an application requires a more complex
deployment or references shared assemblies, you cannot use XCOPY.
552. You have created an application for a client who wants to
distribute your application to his workforce via a network share.
He wants to ensure that everyone who downloads the application
will download it to the same folder. Describe a plan that would
accomplish this goal.
Ans:-Create a setup project for the application. Using the User Interface Editor,
provide a dialog box that allows the file directory to be set during
administrative installation, but removes this box from regular installation. Use
administrative installation to install the application to the network share.
553. You have written documentation for your application and have
provided it in the form of several HTML files. Describe two ways
you could include this content in your setup project.
Ans:-You can include loose HTML files along with your application by either
including them when you create the setup project with the Setup wizard or by
adding them to the project after creation with the File System Editor.
554. What base class do all Web Forms inherit from?
555. What is a native image? How do you create one?
Ans:-A native image is a precompiled version of a .NET assembly. You can create
a native image of your application by using the Ngen.exe utility.
556. What is the purpose of a bootstrapper application? When do you
not need to create one?
Ans:-A bootstrapper application automatically detects if Windows Installer is
installed on the target machine. If Windows Installer is not present, it installs
Windows Installer before proceeding with the rest of the installation. You
should create a bootstrapper application unless all of your target machines
are running Windows XP (which has Microsoft Windows Installer 1.5 already
installed) or have had Microsoft Installer 1.5 installed previously.
557. Can you edit data in the Repeater control?
558. write a select statement to retrive eno,ename,managername for
the following table
559. How does character encoding affect file formats?
Ans:-When using non-ASCII characters in a Web form, you must save the file
with a specific character encoding, such as UTF-8. ASP.NET can automatically
detect UTF-8 file encoding if the file is saved with a signature; otherwise, you
need to specify the file encoding used in the fileEncoding attribute of the
globalization element in Web.config.
560. Converting Excel Worksheets and CSV files to a DataSet
Ans:-I’ve been working on a bunch of cool new code that I’ll be releasing soon,
but here’s an odd ball code snippet that I recently had to create:
I needed to open an Excel spreadsheet and then load the data into a
database. I found some good examples using OLEDB’s extended properties
to open both Excel file and CSV files, but the Excel solution required that you

needed to know the WorkSheet name. With a little searching I found out that
you can pull the all the WorkSheet names by using the OLEDB GetSchema
method. With a little bit of corrections for ADO.Net the code turned out to be
relatively easy:
private DataSet GetExcelWorkSheet(string pathName,string fileName,int
OleDbConnection ExcelConnection = new
Source="+pathName+@"\"+fileName+";Extended Properties=Excel 8.0;");
OleDbCommand ExcelCommand = new OleDbCommand();
ExcelCommand.Connection = ExcelConnection;
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
DataTable ExcelSheets =
d.Tables,new object[] {null, null, null, "TABLE"});
string SpreadSheetName =
DataSet ExcelDataSet = new DataSet();
ExcelCommand.CommandText = @"SELECT * FROM "+SpreadSheetName;

return ExcelDataSet;
Here’s the same thing, but opening a CSV file:
private DataSet GetCVSFile(string pathName,string fileName)
OleDbConnection ExcelConnection = new
Source="+pathName+";Extended Properties=Text;");
OleDbCommand ExcelCommand = new OleDbCommand(@"SELECT * FROM
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);

DataSet ExcelDataSet = new DataSet();

return ExcelDataSet;
561. I am trying to import a CSV file into a dataset for an ASP.NET
application, and I am stumped. I tried doing it through code using
the Jet provider with extended properties, but received the error
"could not find installable ISAM". Apparently ADO.NET cannot
handle extended properties. I then tried creating a connection to
the CSV file using the connection wizard and the OLEDB Provider
for ODBC. This worked (I could view the contents of my CSV file in
a Visual Studio window), however when I tried to drag the
connection on to my web form, I received the message "You
cannot use an OLEDB provider for ODBC drivers." Can anyone tell
me how I can connect to a CSV file and import into a dataset
(using VB)?

Ans:-The following works with the Jet OLEDB provider:

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

Handles ConnectToText.Click

'Establish a connection to the data source.

Dim sConnectionString As String

sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _

"Data Source=d:\My Documents\TextFiles;Extended Properties=Text;"
Dim objConn As New

Dim da As New System.Data.OleDb.OleDbDataAdapter("Select * from

People.txt", objConn)

Dim ds As New DataSet("PeopleFile")

'da.FillSchema(ds, SchemaType.Source, "People.txt")

da.Fill(ds, "People.txt")

Dim dt As DataTable
dt = ds.Tables("People.txt")

Dim drCurrent As DataRow

For Each drCurrent In dt.Rows
Console.WriteLine("{0} {1}", _
drCurrent("0").ToString, _


End Sub

Paul ~~~

Microsoft MVP (Visual Basic)
562. How do keys work in XSLT?
Keys in XSLT are similar to IDs in Document Type Definitions (DTDs). If you
define an attribute of type ID in a DTD, the attribute value must be unique in
the document. You can also define attributes of type IDREF. In this case, the
attribute value must refer to a unique ID value somewhere else in the
document. With this type of DTD information in place, you can then use
XPath's id function in order to resolve IDs and IDREF relationships in a
document at run time. For example, let's consider an XML document with an
internal DTD (see Figure 1).
The following XPath expression identifies the element with an ID of e104,
which in this particular case is an employee element with the name of Scott
The following XPath expression identifies the elements with ID values of e101,
e102, and e104, which in this case happens to be the employee elements
that have the names of Aaron Skonnard, Dan Sullivan, and Scott Bloom:
id('e101 e103 e104')

And finally, the following XPath expression identifies the employees who teach
the "GWS.NET" course (specifically Aaron Skonnard, Simon Horrell, and
Bob Beauchemin) through the instructors IDREF attribute:
As you can see, this technique makes it possible to establish relationships
between different elements based on their ID values. The problem with
the ID/IDREF technique is that it requires DTD information to be present
at run time and it's limited to attributes. To help alleviate these
restrictions, XSLT introduced a new concept, called keys, which provides
the same basic functionality but with more flexibility. You use the key
element to define a key in an XSLT document. It has the following
<xsl:key name="qname" match="pattern" use="expression"/>
You give the key a qualified name so that you can refer to it later from the
key function (which behaves like the XPath id function described earlier).
You also specify a pattern, which identifies the nodes to which the key
applies. Finally, you use the "use" attribute to specify an XPath expression
that is evaluated (relative to the nodes identified by the match
expression) to produce the actual key value. For example, consider the
XML document in Figure 2.
In this case, you probably want to create a key based on the employee
element's id attribute, as illustrated here:
<xsl:key name="employeeId" match="employee" use="@id"/>
This creates a key for all employee elements within the document; the key
value is evaluated from the employee element's id attribute. With the key
defined, you can then use the key function to retrieve nodes with a given
key. For example, the following XSLT fragment illustrates how to retrieve
the instructors who teach a given course:
<xsl:template match="course">
<h2><xsl:value-of select="name"/></h2>
<xsl:for-each select="key('employeeId', ./instructors/*)">
<li><xsl:value-of select="."/></li>
The previous fragment will emit the following HTML, assuming the input
document shown in Figure 2:
<li>Aaron Skonnard </li>
<li>Aaron Skonnard</li>
<li>Simon Horrell</li>
<li>Dan Sullivan</li>
As you can see, keys don't require DTD information to be used and they're
not limited to attributes as with ID/IDREF. The fact that keys can be assigned
to nodes that match an arbitrary pattern also gives you an extra degree of

562. What's the difference between the match and select attributes in
XSLT? What do they do, exactly?
In XSLT, there are various elements that come with a match attribute
(such as template and key) and others that come with select attribute
(value-of, for-each, apply-templates, and so on). At first glance, both
seem to take XPath expressions, but in fact they're quite different.
Select does indeed expect an XPath expression, which is used to select a
nodeset for further processing. In the following example, the for-each
expression identifies a set of nodes to be iterated over while the nested
value-of expression writes the value of each node to the output tree:
<xsl:for-each select="//item">
<xsl:value-of select="."/>

The match attribute, on the other hand, takes what's called a pattern. A
pattern looks like an XPath expression because it shares the same syntax,
but it's treated differently by the XSLT processor. A pattern is used for
matching nodes in the tree against the specified criteria. For example, the
following template matches any element node that has a grandparent
named foo:
<xsl:template match="foo/*/*">
In other words, a pattern describes an "is a" relationship with the nodes in
question (that is, is this node an element that has a grandparent named
foo?). Here's a more sophisticated example:
<xsl:template match="f:foo[@id > 323]//text()">
In this case, the pattern identifies all text nodes that have an ancestor
element named foo from the namespace identified by f, and with an id
attribute with a numeric value greater than 323.
563. Why does SelectNodes always return the nodes in document order
irrespective of the axis direction (forward/reverse) that was used
in the query?
Ans:-Consider the following XML document, which I'll call foo.xml:
<foo depth='1'>
<foo depth='2'>
<foo depth='3'>
Now consider the following code that evaluates slightly different XPath
expressions against the loaded foo.xml document:
XmlDocument doc = new XmlDocument();

XmlElement b, f1, f2;

b = (XmlElement)doc.SelectSingleNode("//bar");
f1 = (XmlElement)b.SelectSingleNode("ancestor::foo[1]");
f2 = (XmlElement)b.SelectNodes("ancestor::foo")[0];


You might expect the console output to be the same in both cases, but it's
actually different. The first Console.WriteLine outputs "3" while the second
outputs "1". The reason it works this way is that axis direction, as defined by
the XPath specification, is only significant within XPath predicates. In fact,
XPath nodesets are by definition unordered so it's up to the XPath
implementation to determine in what order to deliver nodesets.
In the call to SelectSingleNode, however, I asked for the first node in the
ancestor axis within a predicate. This guarantees that I'll get the first ancestor
node (in reverse document order) starting from the bar element (the foo
element with depth='3'). In the call to SelectNodes, on the other hand, I
asked for all ancestor foo elements and the implementation returned an
XmlNodeList collection with the nodes in document order (completely legal
according to the specification). Then, my code asked for the first item in the
collection, which happens to be the foo element where depth='1'. Since XPath
doesn't specify the order in which nodes are returned, languages that build on
XPath often define additional semantics of their own. For example, in the case
of XSLT, nodesets are always processed in document order.
564. How do you query a paragraph of text to determine whether it
contains a <SCRIPT> element?
Ans:-The answer to this question depends on what you mean when you ask if
the paragraph contains a <SCRIPT> element. Consider the following
<desc>This is a description that contains a <SCRIPT
language="Javascript" src="script.js"/> element.</desc>
If the document looks like this, you would use a normal XPath expression that
queries against the document's logical data model. For example, the
following XPath expression identifies all element nodes in the document
tree that contain a child SCRIPT element (in this case, the <desc>
Now, consider the following document, which uses special entity references
for the less-than (<) and greater-than (>) characters within the <desc>
<desc>This is a description that contains a &lt;SCRIPT
language="Javascript" src="script.js"/&gt; element.</desc>
When an XML processor parses this document, it replaces "&lt;" with the <
character and replaces "&gt;" with the > character. Hence, the <desc>
element contains the following text when you query it using XPath:
This is a description that contains a <SCRIPT
language="Javascript" src="script.js"/> element.
So you would use the following XPath expression
in order to search this document for all elements that contain "<SCRIPT".
565. When multiple XSLT patterns match a given node, how does the
processor decide which to use?
Ans:-When a node matches more than one pattern found in your XSLT

templates (also known as rules), the processor follows the conflict
resolution guidelines outlined by the XSLT specification to determine which
one to use. These guidelines state that the template with the highest
priority will be called when conflicts occur. The algorithm for determining
the actual priority of a template, however, requires some additional
To determine which node has the highest priority, the processor first
eliminates all templates that were imported (using the xsl:import
element); imported templates automatically have a lower priority than the
templates in the importing transformation. The processor then determines
the priority values of the remaining templates.
Priorities can be explicitly assigned to a template through the priority
attribute. For example, the following template has been assigned a priority
of 1:
<xsl:template match="/foo/bar" priority="1">
<!-- do something interesting -->

If a priority has been assigned to a template, then that's the value used by
the processor to determine which template has the highest priority. If a
priority has not been explicitly assigned, the processor calculates a default for
the template. The default priorities assigned by the processor can range from
-0.5 to +0.5. Basically, more specific patterns receive higher default priorities.
Since the range is -0.5 to +0.5, assigning an explicit priority of 1 to a
template will always win over a default priority.
Figure 3 outlines exactly how the default priorities are assigned for the
different types of patterns that exist. Patterns that only contain node tests by
type (such as *, node, comment, text, and so forth) are the most generic, so
they receive a default priority of -0.5. Patterns that only contain namespace
wildcards (ns:*) are a bit more specific, so they receive a default priority of
-0.25. Patterns that only contain a qualified name test or a literal processing
instruction test (such as foo, ns:foo, @bar, processing-instruction('foo'), and
so on) receive a default priority of 0. Every other pattern that's more specific
than these receives a default priority of 0.5. This means that any pattern with
more than one location step, or with a predicate, automatically receives a
default priority of 0.5.
Once the default priorities for all templates have been evaluated, the
processor chooses the one with the highest priority. For example, in the
following XSLT fragment there are two templates that may match a given bar
element (assuming it has a parent foo element). When this occurs, the
processor will automatically choose the second template because it has a
higher default priority:
<xsl:template match='bar' >
<!-- default priority = 0 -->

<xsl:template match='foo/bar' >

<!-- default priority = .5 -->

There are still situations in which there may be multiple templates with the
same priority that match a given node. When this occurs, the processor may
either signal an error or choose to use the last template in the document. This
is the usual choice. For example, the following XSLT fragment contains two
templates that could match the same foo element (one that has both a child
bar element and a parent bar element). Since both templates have a default

priority of 0.5, the XSLT processor will either signal an error or choose the last
template in the document, in this case the one matching bar/foo elements:
<xsl:template match='foo[bar]' >
<!-- default priority = .5 -->

<xsl:template match='bar/foo'>
<!-- default priority = .5 -->

Of course, you're better off avoiding these situations altogether. If you want
the processor to always use the first template when these conflicts occur, you
simply need to set its priority to 1, as illustrated in the following code:
<xsl:template match='foo[bar]' priority='1'>
<!-- would have a default priority = .5 -->

<xsl:template match='foo/bar' >

<!-- default priority = .5 -->
As you can see, XSLT has an extensive process for determining which
templates to call in the case of conflicts. Understanding these rules is crucial
when making copious use of XSLT's declarative programming model.
566. What happens when there isn't a template matching a node that is
being processed?
Ans:-A XSLT defines several templates that are built into every
transformation by default, whether you provide them explicitly or not.
These are referred to as XSLT's built-in templates. There is a built-in
template for every type of node that might be processed in an XML
document (elements, attributes, processing instructions, comments, and
so on). These built-in templates, however, have the lowest priority
possible, so they'll never be used before a user-provided template that
also matches the same node (see the previous question on conflict
resolution). They're only used when no other template matching a specific
node is present.
The functionality of the built-in templates can be expressed with the
following template definitions:
<!-- built-in templates -->
<xsl:template match="*|/">
<xsl:apply-templates select="node()"/>
<xsl:template match="text()|@*">
<xsl:value-of select="."/>
<xsl:template match="processing-instruction()|comment()"/>
In the case of the root node or element nodes, the processor automatically
applies templates to the current node's children (but not its attributes since
the call uses child::node()). In the case of text or attribute nodes, the
processor automatically outputs the node's value to the result tree. In the
case of processing instructions or comments, the processor does nothing—it
simply ignores them.
This default functionality turns out to be quite useful with the declarative
programming model offered by XSLT. It basically allows you to walk
recursively through the tree until a node is matched against one of the
provided templates. When the processor encounters a text or attribute node,

it prints the node's value to the result tree at the right place.
To illustrate this process, try running the following transformation against
any XML input document:
<xsl:transform version="1.0"
xmlns:xsl="" />
This transformation doesn't contain any user-provided templates, so the built-in
templates will be used instead. For example, try it against the following
<foo bar="hi">
In this case, the XSLT processor will output "helloworld". It recursively walks the
tree and outputs the text node values, thanks to the built-in templates. The
attribute node is never encountered due to the way xsl:apply-templates is
called by the built-in template for elements. If your transformation ever
outputs more text than you want it to, it's probably because the processor is
recursively walking the tree and hitting text nodes unintentionally. In order to
avoid this, you can always override the built-in template for text nodes. For
example, the following is a new version of the last transformation with a new
template for text nodes:
<xsl:transform version="1.0"
xmlns:xsl="" >
<!-- override built-in template to do nothing -->
<xsl:template match="text()|@*" />
With this in modification, text nodes will never be output unless you explicitly do
so through xsl:value-of. Try running the sample document through this
transformation and you'll see that it doesn't output anything. In addition, if
you don't want the processor to even walk the tree, you could override the
built-in template for elements to do nothing, as shown here:
<xsl:transform version="1.0"
xmlns:xsl="" >
<!-- override built-in template to do nothing -->
<xsl:template match="*" />
With this in place, the processor won't walk the tree, so it never makes it to
the text nodes. If you run the sample document through this transformation,
you'll see that it doesn't output anything either. If you override this template,
it means that you must be more precise about which nodes you want to
process when calling xsl:apply-templates.
567. What's the difference between xsl:include and xsl:import?
Ans:-A The xsl:include element makes it possible to include templates
from one transformation into another. When you use xsl:include, it has to
be a top-level element or, in other words, an immediate child of
xsl:transform. Then you simply specify the location of the transformation
you'd like to include using the href attribute, as illustrated here:
<xsl:transform version="1.0"
<!-- include templates from foo.xsl here -->
<xsl:include href="foo.xsl"/>

Using xsl:include has no effect on the priority of the included templates. The
templates included into the new transformation are treated as if they
were defined inline. This is where xsl:import is different.
The xsl:import element also allows you to include templates from one
transformation into another. But when doing so, the imported templates
automatically receive a lower precedence
568. Does XSLT provide an if/else statement?
Ans:-A XSLT provides an if statement (xsl:if), but an else clause doesn't
come with it. The xsl:if statement takes a Boolean expression in its test
attribute, as shown here:
<xsl:if test="spouse and count(child) > 0">
Married with children
If the test expression evaluates to true, the content within the xsl:if element
is instantiated and processed. If you need an else clause, you have to use a
different construct called xsl:choose, which is similar to a switch statement.
The xsl:choose statement allows you to specify multiple test expressions, and
the first one that evaluates to true (starting from the top) is instantiated and
<xsl:when test="spouse and count(child) = 0">
Just married
<xsl:when test="not(spouse) and count(child) > 0">
Just kids
<xsl:when test="spouse and count(child) > 0">
Married with children
The xsl:choose also allows you to have an xsl:otherwise statement, which is
instantiated if none of the test expressions evaluate to true. This is what
you'd use to implement a traditional if/else statement, as illustrated here:
<xsl:when test="spouse and count(child) > 0">
Married with children
You must have plenty of free time
I can't count the number of times I've started writing an xsl:if statement only to
realize that I also needed an else clause, which forces me to start over using
xsl:choose. So every time you start using xsl:if, ask yourself if you also need
an else.
569. Does XSLT provide a way to control how the output of a
transformation is serialized? If so, what options does it provide?
Ans:-Yes, XSLT provides the xsl:output element for exactly this purpose.
It's a top-level element that should be an immediate child of
xsl:transformation. The xsl:output element provides a wide range of
options that control how the result tree is serialized. The following shows
the syntax for xsl:output:

<xsl:output method = "xml" | "html" | "text" | qname version = nmtoken
encoding = string omit-xml-declaration = "yes" | "no"
standalone = "yes" | "no" doctype-public = string doctype-system = string cdata-
section-elements = qnames indent = "yes" | "no"
media-type = string />
570. Can I manipulate XML from Stored procedures
Ans:-Why not u can
571. What u will consider when u review
Ans:-Memory Leaks, Bad Coding Techniques
572. Which will be faster ASP or ASP.Net
573. What are the disadvantages of view state/what are the benefits?
Ans:-Disadvantage is it expects high system resources and bandwidth Benefits
574. True or False: A Web service can only be written in .NET
575. If I have one table with two columns with id and number. Write a
select statement for selecting third highest number
Ans:-Select number from table where id in (select top 3 from table order by table
576. Can you store the negative values in Primary Key column
577. What method do you use to explicitly kill a user s session?
578. How many null values u can store in Unique Column
Ans:-One value
579. Can u call web services from windows application? If yes how?
Ans:-Yes you can call. By using WSDL file
580. What will make assembly unique
Ans:-Key, Culture
581. How would ASP and ASP.NET apps run at the same time on the
same server?
582. Can you edit data in the Repeater control?
583. How many classes can a single .NET DLL contain?
Ans:-There is no real limit
584. Let’s say I have an existing application written using Visual Studio
(VB InterDev and this application utilizes Windows COM+
transaction services. How would you approach migrating this
application to .NET?
Ans:-We can migrate COM+ components into managed components by using
585. Code Reviews?
Ans:-There are two basic types of reviews: walk-throughs and formal
inspections. In a walk-through, the author takes one or more colleagues on a
tour of the document under review. In my experience, about 80% of the
errors found in a walk-through are actually found by the author in the process
of explaining the document. In a formal inspection, one or more people are
given a document design or program to review. Oftentimes each person
concentrates on different things: adherence to style or programming
standards, logical errors, completeness of documentation, etc. It is common

practice to make checklists of what each person is to look for, such as coding
style rules, common mistakes, potential security holes, etc.
There is no problem with someone finding an error that they weren't
concentrating on. For example, if the person checking for compliance to
coding standards notices an AND operator being used in place of an OR, they
should definitely note it. But not every person is trying to make sure all
aspects of the document are correct. When a reviewer finds a problem, they
note its location and its severity. Priorties range from ``something you might
consider thinking about changing if you find yourself with absolutely nothing
to do and the boss is in a bad mood'', to ``if this error is not fixed
immediately it will set in motion a chain of events leading to the end of
civilization as we know it''.
Once everyone has reviewed the document, a meeting is held to discuss the
errors found. The errors can be discussed in just about any logical order: by
page of the document, by severity of errors or each reviewer can list all of the
issues they found. This meeting is usually run by the author of the document,
but it could be run by anyone. As each issue is mentioned, the people at the
meeting come to a consensus as to the severity of the issue. Often, the
reviewer may not be able to assess the severity of an issue but may just have
a hunch that something is not as it should be and will ask the other attendees
their opinions. It is crucial to remember that the point of the meeting is not to
solve the problems but merely to log them. I know full well how hard it can be
to keep a room full of engineers from immediately trying to solve an
interesting problem, but the facilitator must remember to keep the meeting
on track, or it will go on for weeks and will cost more than it saves.
Check List
Code meets team guidelines in terms of which language features to avoid,
and which to use.
Indentation rules are standardised and consistently applied.
Each class provides a 'unit test' method which can be called.
The unit tests calls every function which it is possible to do, and provides data
for high code coverage.
The unit test data and sequence is intended to 'break' the class, rather than
demonstrate it works.
Critical Sections and Mutexes are used to secure access to data when such
accesses need to be serialised
Event objects: verify where they are created as auto reset or not, and that the
mode is what the design needs.
Interface is named sensibly,
Interface uses a numbering scheme to denote versions, not Ex, ExEx at the end
Methods are named meaningfully for understanding and so that they can be
mixed in to a single implementation.
Interface marshalls data for efficient network transport
Distributed applications use interfaces which have higher 'value' methods so that
the number of remote calls needed can be kept down
New errors/hresults have been documented.
Thread safety is applied to all methods which can be called across threads
Internal methods which omit safety wrappers are kept private.
Class and methods are all documented
Variables are all initialised during construction.
Pointers are freed during destruction
App tests for network not being present/too slow
Socket code handles a broken connection at any point.

Socket code understands that port addresses are given in network order
Software is designed to cope with both firewalled corporate networks and pure
Internet access.
Everything includes timeouts and/or can be cancelled by the user. This includes
simple functions like name lookup -use non-blocking WSA calls or a second
thread in preference to things like gethostbyname.
Listening ports do not introduce new security holes. Consider a 'no listen' option,
and a log of failed attempts to connect.
Brackets are used to set order of tests, sums correctly.
Any mix of arithmetic and logic should be bracketed, as should any complex
Any function which has a result of a 'larger' data type than some of the starting
parameters (int to double, int to int64, ...) forces the arguments to the final
data type as early as possible (ensures highest accuracy)
Code does not make a mess of sign extension when switching between signed
and unsigned datatypes.
Tests don't get confused about when '0' indicates success.
Code works in time zones other than GMT
App doesn't contain hard coded assumptions about maximum users, records, etc.
Consider scalable datastructures
App doesn't contain soft scalability limits which result from using dumb algorithms
Consider unicode for text storage -or a 'unicode' flag in the header at least.
Code is laid out into separate files, accompanied by documentation
Code is not reused though copy, paste and edit reuse. yes, this is the easiest but
makes maintenance a nightmare.
Massively complex algorithms and speed tricks are not used without quantitive
evidence that there is a performance issue in these sections.
Advantages of doing code and design reviews:
The earlier bugs are found in the life cycle of a product, the cheaper and easier
they are to fix.
If someone else looks at your code or design, they are likely to find mistakes you
When you know that someone else is going to be looking at your code, you are a
lot more likely to tidy it up and make sure there is accurate and up-to-date
You can learn a lot by reading other people's code.
More than one person who is familiar with a program is the best insurance against
``Mack Truck Syndrome'', which is when the only person who understands
the software gets hit by a truck, leaves the company or is for some reason
not available for consultation.
It can be a means of establishing quality metrics, so one can measure the
effectiveness of different quality processes.
The process of explaining your software to someone else can help you actually
review your own program, rather than just looking at and seeing what you
expect or want to see.
When done right, code and design reviews can save time and improve quality
over the entire project life cycle.
The disadvantage of code reviews is that they take time, not only of the
person actively working on the project, but also for other people who are
usually under deadline pressure themselves. Despite the fact that there are
numerous studies showing that the overall number of human-hours spent on
a project is lower when reviews are properly done, there is the constant

temptation to bet that there really aren't any problems. That means waiting
until the code is written and being debugged to try to find problems.
I'm nearly done preaching about why peer reviews are a good thing. I will say
that the most important thing about reviews is that they actually get done. A
quick and dirty review that finds only a third of the bugs is more effective
than a thorough, exhaustive review that no one actually performs.
586. Does GC Maintains any counters/Pointers?
Ans:-No. GC Doesn’t maintain any pointers
587. Interface Vs Abstract Class

Feature Interface Abstract class

A class may implement A class may extend only

Multiple inheritance
several interfaces. one abstract class.

An abstract class can

An interface cannot provide complete code,
provide any code at all, default code, and/or just
much less default code. stubs that have to be

Static final constants

only, can use them
without qualification in
classes that implement
Both instance and static
the interface. On the
constants are possible.
other paw, these
Both static and instance
Constants unqualified names
intialiser code are also
pollute the namespace.
possible to compute the
You can use them and it
is not obvious where
they are coming from
since the qualification is

An interface
A third party class must be
Third party implementation may be
rewritten to extend only
convenience added to any existing
from the abstract class.
third party class.

An abstract class defines

Interfaces are often used
the core identity of its
to describe the
descendants. If you
peripheral abilities of a
defined a Dog abstract
class, not its central
class then Damamation
identity, e.g. an
descendants are Dogs,
is-a vs -able or can-do Automobile class might
they are not merely
implement the
dogable. Implemented
Recyclable interface,
interfaces enumerate the
which could apply to
general things a class can
many otherwise totally
do, not the things a class
unrelated objects.

Plug-in You can write a new You must use the abstract
replacement module for class as-is for the code

base, with all its attendant
baggage, good or bad. The
abstract class author has
imposed structure on you.
Depending on the
cleverness of the author of
an interface that the abstract class, this may
contains not one stick of be good or bad. Another
code in common with issue that's important is
the existing what I call "heterogeneous
implementations. When vs. homogeneous." If
you implement the implementors/subclasses
interface, you start from are homogeneous, tend
scratch without any towards an abstract base
default implementation. class. If they are
You have to obtain your heterogeneous, use an
tools from other interface. (Now all I have
classes; nothing comes to do is come up with a
with the interface other good definition of
than a few constants. hetero/homo-geneous in
This gives you freedom this context.) If the various
to implement a radically objects are all of-a-kind,
different internal design. and share a common state
and behavior, then tend
towards a common base
class. If all they share is a
set of method signatures,
then tend towards an

If the various
If all the various
implementations are all of
implementations share
a kind and share a
Homogeneity is the method
common status and
signatures, then an
behavior, usually an
interface works best.
abstract class works best.

If your client code talks Just like an interface, if

only in terms of an your client code talks only
interface, you can easily in terms of an abstract
Maintenance change the concrete class, you can easily
implementation behind change the concrete
it, using a factory implementation behind it,
method. using a factory method.

Slow, requires extra

indirection to find the
corresponding method
in the actual class.
Speed Fast
Modern JVMs are
discovering ways to
reduce this speed

Terseness The constant You can put shared code

into an abstract class,
declarations in an
where you cannot into an
interface are all
interface. If interfaces
presumed public static
want to share code, you
final, so you may leave
will have to write other
that part out. You can't
bubblegum to arrange
call any methods to
that. You may use methods
compute the initial
to compute the initial
values of your
values of your constants
constants. You need not
and variables, both
declare individual
instance and static. You
methods of an interface
must declare all the
abstract. They are all
individual methods of an
presumed so.
abstract class abstract.

If you add a new method

to an interface, you If you add a new method to
must track down all an abstract class, you have
implementations of that the option of providing a
Adding functionality interface in the universe default implementation of
and provide them with a it. Then all existing code
concrete will continue to work
implementation of that without change.