Saturday, July 11, 2009

DOTNET Interview Questions


Interview Questions



DOTNET

1. When was ASP.NET released?

ASP.NET is a part of the .NET framework which was released as a software platform in 2002.

2. Explain Namespace.

Namespaces are logical groupings of names used within a program. There may be multiple namespaces in
a single application code, grouped based on the identifiers use. The name of any given identifier must appear only
once in its namespace.

3. List the types of Authentication supported by ASP.NET.

Windows (default) ,Forms ,Passport ,None (Security disabled)

4. What is CLR?

Common Language Runtime (CLR) is a run-time environment that manages the execution of .NET code
and provides services like memory management, debugging, security, etc. The CLR is also known as Virtual
Execution System (VES).

5. What is CLI?

The CLI is a set of specifications for a runtime environment, including a common type system, base class
library, and a machine-independent intermediate code known as the Common Intermediate Language (CIL).
(Source: Wikipedia.)

6. List the various stages of Page-Load lifecycle.

Init() ,Load() ,PreRender() ,Unload()

7. Explain Assembly and Manifest.

An assembly is a collection of one or more files and one of them (DLL or EXE) contains a special metadata
called Assembly Manifest. The manifest is stored as binary data and contains details like versioning requirements
for the assembly, the author, security permissions, and list of files forming the assembly. An assembly is created
whenever a DLL is built. The manifest can be viewed programmatically by making use of classes from the
System.Reflection namespace. The tool Intermediate Language Disassembler (ILDASM) can be used for this
purpose. It can be launched from the command prompt or via Start> Run.

8. What is Shadow Copy?

In order to replace a COM component on a live web server, it was necessary to stop the entire website,
copy the new files and then restart the website. This is not feasible for the web servers that need to be always
running. .NET components are different. They can be overwritten at any time using a mechanism called Shadow
Copy. It prevents the Portable Executable (PE) files like DLLs and EXEs from being locked. Whenever new versions
of the PEs are released, they are automatically detected by the CLR and the changed components will be
automatically loaded. They will be used to process all new requests not currently executing, while the older version
still runs the currently executing requests. By bleeding out the older version, the update is completed.

9. What is DLL Hell?

DLL hell is the problem that occurs when an installation of a newer application might break or hinder other
applications as newer DLLs are copied into the system and the older applications do not support or are not
compatible with them. .NET overcomes this problem by supporting multiple versions of an assembly at any given
time. This is also called side-by-side component versioning.





10. Explain Web Services.

Web services are programmable business logic components that provide access to functionality through
the Internet. Standard protocols like HTTP can be used to access them. Web services are based on the Simple
Object Access Protocol (SOAP), which is an application of XML. Web services are given the .asmx extension.

11. Explain Windows Forms.

Windows Forms is employed for developing Windows GUI applications. It is a class library that gives
developers access to Windows Common Controls with rich functionality. It is a common GUI library for all the
languages supported by the .NET Framework.

12. What is Postback?

When an action occurs (like button click), the page containing all the controls within the tag
performs an HTTP POST, while having itself as the target URL. This is called Postback.

13. Explain the differences between server-side and client-side code?

Server side scripting means that all the script will be executed by the server and interpreted as needed.
Client side scripting means that the script will be executed immediately in the browser such as form field
validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Since the
code is included in the HTML page, anyone can see the code by viewing the page source. It also poses as a
possible security hazard for the client computer.

15. Enumerate the types of Directives.

@ Page directive ,@ Import directive ,@ Implements directive ,@ Register directive , @Assembly directive
,@ OutputCache directive ,@ Reference directive

16. What is Code-Behind?

Code-Behind is a concept where the contents of a page are in one file and the server-side code is in
another. This allows different people to work on the same page at the same time and also allows either part of the
page to be easily redesigned, with no changes required in the other. An Inherits attribute is added to the @ Page
directive to specify the location of the Code-Behind file to the ASP.NET page.

17. Describe the difference between inline and code behind.

Inline code is written along side the HTML in a page. There is no separate distinction between design code
and logic code. Code-behind is code written in a separate file and referenced by the .aspx page.

18. List the ASP.NET validation controls?

RequiredFieldValidator ,RangeValidator ,CompareValidator ,RegularExpressionValidator CustomValidator
,ValidationSummary

19. What is Data Binding?

Data binding is a way used to connect values from a collection of data (e.g. DataSet) to the controls on a
web form. The values from the dataset are automatically displayed in the controls without having to write separate
code to display them.

20. Describe Paging in ASP.NET.

The DataGrid control in ASP.NET enables easy paging of the data. The AllowPaging property of the
DataGrid can be set to True to perform paging. ASP.NET automatically performs paging and provides the
hyperlinks to the other pages in different styles, based on the property that has been set for PagerStyle.Mode.





21. Should user input data validation occur server-side or client-side? Why?

All user input data validation should occur on the server and minimally on the client-side, though it is a
good way to reduce server load and network traffic because we can ensure that only data of the appropriate type
is submitted from the form. It is totally insecure. The user can view the code used for validation and create a
workaround for it. Secondly, the URL of the page that handles the data is freely visible in the original form page.
This will allow unscrupulous users to send data from their own forms to your application. Client-side validation can
sometimes be performed where deemed appropriate and feasible to provide a richer, more responsive experience
for the user.

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

Response.Redirect: This tells the browser that the requested page can be found at a new location. The
browser then initiates another request to the new page loading its contents in the browser. This results in two
requests by the browser.

Server.Transfer: It transfers execution from the first page to the second page on the server. As far as
the browser client is concerned, it made one request and the initial page is the one responding with content. The
benefit of this approach is one less round trip to the server from the client browser. Also, any posted form
variables and query string parameters are available to the second page as well.

23. Is it necessary to lock application state before accessing it?


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

24. Define Boxing and UnBoxing

C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference
types are stored on the heap. The conversion of value type to reference type is known as boxing and converting
reference type back to the value type is known as unboxing.

25. Define Value Types and Reference Types

Value Types Value types are primitive types that are mapped directly to the FCL. Like Int32 maps to
System.Int32, double maps to System.double. All value types are stored on stack and all the value types are
derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are
created on stack, hence known as ValueType.

Reference TypesReference Types are different from value types in such a way that memory is allocated to them
from the heap. All the classes are of reference type. C# new operator returns the memory address of the object.

26. How do I send e-mail from an ASP.NET application?

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 (127.0.0.1) to relay messages through the local SMTP service.

27. What are VSDISCO files?

VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following VSDISCO
file in a directory on your Web server, for example, it returns references to all ASMX and DISCO files in the host
directory and any subdirectories not noted in elements:




xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">













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

29. Is it possible to prevent a browser from caching an ASPX page?

Just call SetNoStore on the HttpCachePolicy object exposed through the Response object's Cache property, as
demonstrated here:

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







<%

Response.Cache.SetNoStore ();

Response.Write (DateTime.Now.ToLongTimeString ());

%>





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

30. What does AspCompat="true" mean and when should I use it?

AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but should be set to true
in any ASPX file that creates apartment-threaded COM objects--that is, COM objects registered
ThreadingModel=Apartment. That includes all COM objects written with Visual Basic 6.0. AspCompat should also
be set to true (regardless of threading model) if the page creates COM objects that access intrinsic ASP objects
such as Request and Response. The following directive sets AspCompat to true:<%@ Page AspCompat="true" %>
Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available to the COM
components by placing unmanaged wrappers around the equivalent ASP.NET objects. Second, it improves the
performance of calls that the page places to apartment- threaded COM objects by ensuring that the page (actually,
the thread that processes the request for the page) and the COM objects it creates share an apartment.
AspCompat="true" forces ASP.NET request threads into single-threaded apartments (STAs). If those threads
create COM objects marked ThreadingModel=Apartment, then the objects are created in the same STAs as the
threads that created them. Without AspCompat="true," request threads run in a multithreaded apartment (MTA)
and each call to an STA-based COM object incurs a performance hit when it's marshaled across apartment
boundaries.Do not set AspCompat to true if your page uses no COM objects or if it uses COM objects that don't
access ASP intrinsic objects and that are registered ThreadingModel=Free or ThreadingModel=Both.

31. Explain the differences between Server-side and Client-side code?

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

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

C#

33. Should validation (did the user enter a real date) occur server-side or client-side? Why?

Client-side validation because there is no need to request a server side date when you could obtain a date
from the client machine.

34. What are ASP.NET Web Forms? How is this technology different than what is available though ASP?

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



35. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one
over the other?

In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was
Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest
problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to
maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents
good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are
workarounds, but they're difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on
high-volume sites, causes scalability problems.

As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the
server without requiring a roundtrip to the client.

36. How can you provide an alternating color scheme in a Repeater control?

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

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

ItemTemplate

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

Application_Start,Application_End, Application_AcquireRequestState, Application_AuthenticateRequest,
Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed, Application_EndRequest,
Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute,

Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState,
Application_ResolveRequestCache, Application_UpdateRequestCache, Session_Start,Session_End

You can optionally include "On" in any of method names. For example, you can name a BeginRequest event
handler.Application_BeginRequest or Application_OnBeginRequest.You can also include event handlers in
Global.asax for events fired by custom HTTP modules.Note that not all of the event handlers make sense for Web
Services (they're designed for ASP.NET applications in general, whereas .NET XML Web Services are specialized
instances of an ASP.NET app). For example, the Application_AuthenticateRequest and
Application_AuthorizeRequest events are designed to be used with ASP.NET Forms authentication.

39. Do ASP.NET forms authentication cookies provide any protection against replay attacks? Do they,
for example, include the client's IP address or anything else that would distinguish the real client
from an attacker?

No. If an authentication cookie is stolen, it can be used by an attacker. It's up to you to prevent this
from happening by using an encrypted communications channel (HTTPS). Authentication cookies issued as session
cookies, do, however,include a time-out valid that limits their lifetime. So a stolen session cookie can only be
used in replay attacks as long as the ticket inside the cookie is valid. The default time-out interval is 30
minutes.You can change that by modifying the timeout attribute accompanying the element in
Machine.config or a local Web.config file. Persistent authentication cookies do not time-out and therefore are a
more serious security threat if stolen.

40. What is different b/w webconfig.xml & Machineconfig.xml

Web.config & machine.config both are configuration files.Web.config contains settings specific to an
application where as machine.config contains settings to a computer. The Configuration system first searches
settings in machine.config file & then looks in application configuration files.Web.config, can appear in multiple
directories on an ASP.NET Web application server. Each Web.config file applies configuration settings to its own
directory and all child directories below it. There is only Machine.config file on a web server.



If I'm developing an application that must accomodate multiple security levels though secure login and my
ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be
the best approach to maintain login-in state for the users?

Use the state server or store the state in the database. This can be easily done through simple setting change in
the web.config.


StateConnectionString="tcpip=127.0.0.1:42424"

sqlConnectionString="data source=127.0.0.1; user id=sa; password="

cookieless="false"

timeout="30"

/>

You can specify mode as stateserver or sqlserver.

Where would you use an iHTTPModule, and what are the limitations of any approach you might take in
implementing one

"One of ASP.NET's most useful features is the extensibility of the HTTP pipeline, the path that data takes between
client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to
each HTTP request coming into your application. For example, if you wanted custom authentication facilities for
your application, the best technique would be to intercept the request when it comes in and process the request in
a custom HTTP module.

41. How do you turn off cookies for one page in your site?

Since no Page Level directive is present, I am afraid that cant be done.

42. How do you create a permanent cookie?

Permanent cookies are available until a specified expiration date, and are stored on the hard disk.So Set the
'Expires' property any value greater than DataTime.MinValue with respect to the current datetime. If u want the
cookie which never expires set its Expires property equal to DateTime.maxValue.

43. Which method do you use to redirect the user to another page without performing a round trip to
the client?

Server.Transfer and Server.Execute

44. What property do you have to set to tell the grid which page to go to when using the Pager object?

CurrentPageIndex

45. Should validation (did the user enter a real date) occur server-side or client-side? Why?

It should occur both at client-side and Server side.By using expression validator control with the specified
expression ie.. the regular expression provides the facility of only validatating the date specified is in the correct
format or not. But for checking the date where it is the real data or not should be done at the server side, by
getting the system date ranges and checking the date whether it is in between that range or not.

46. What does the "EnableViewState" property do? Why would I want it on or off?



Enable ViewState turns on the automatic state management feature that enables server controls to re-
populate their values on a round trip without requiring you to write any code. This feature is not free however,
since the state of a control is passed to and from the server in a hidden form field. You should be aware of when
ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip,
then you do not need the control to maintain it's view state, since you will wipe out any re-populated data in any
case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the
control to false.

47. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one
over the other?

Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the
requested page. Data can be persist accros the pages using Context.Item collection, which is one of the best way
to transfer data from one page to another keeping the page state alive.

Response.Dedirect() :client know the physical location (page name and query string as well).
Context.Items loses the persisitance when nevigate to destination page. In earlier versions of IIS, if we wanted to
send a user to a new Web page, the only option we had was Response.Redirect. While this method does
accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each
page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity,
Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second,
you lose access to all of the properties in the Request object. Sure, there are workarounds, but they're difficult.
Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability
problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the
transfer on the server without requiring a roundtrip to the client.

48. Can you give an example of when it would be appropriate to use a web service as opposed to a
non-serviced .NET component?

Communicating through a Firewall When building a distributed application with 100s/1000s of users
spread over multiple locations, there is always the problem of communicating between client and server because
of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly
from a Windows UI is a very valid option.

Application Integration When integrating applications written in various languages and running on
disparate systems. Or even applications running on the same platform that have been written by separate
vendors.

Business-to-Business Integration This is an enabler for B2B intergtation which allows one to expose vital
business processes to authorized supplier and customers. An example would be exposing electronic ordering and
invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically.

Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary
componet-based resuse. The limiting factor here is that you can reuse the code but not the data behind it.
Webservice overcome this limitation. A scenario could be when you are building an app that aggregates the
functionality of serveral other Applicatons. Each of these functions could be performed by individual apps, but
there is value in perhaps combining the the multiple apps to present a unifiend view in a Portal or Intranet.

When not to use Web Services: Single machine Applicatons When the apps are running on the same
machine and need to communicate with each other use a native API. You also have the options of using
component technologies such as COM or .NET Componets as there is very little overhead.

Homogeneous Applications on a LAN If you have Win32 or Winforms apps that want to communicate to
their server counterpart. It is much more efficient to use DCOM in the case of Win32 apps and .NET Remoting in
the case of .NET Apps

49. Can you give an example of what might be best suited to place in the Application_Start and
Session_Start subroutines?

The Application_Start event is guaranteed to occur only once throughout the lifetime of the application.
It's a good place to initialize global variables. For example, you might want to retrieve a list of products from a
database table and place the list in application state or the Cache object. SessionStateModule exposes both
Session_Start and Session_End events.



50. What are the advantages and disadvantages of viewstate?

The primary advantages of the ViewState feature in ASP.NET are:

1. Simplicity. There is no need to write possibly complex code to store form data between page submissions.

2. Flexibility. It is possible to enable, configure, and disable ViewState on a control-by-control basis, choosing to
persist the values of some fields but not others.

There are, however a few disadvantages that are worth pointing out:

1. Does not track across pages. ViewState information does not automatically transfer from page to page. With the
session approach, values can be stored in the session and accessed from other pages. This is not possible with
ViewState, so storing data into the session must be done explicitly.

2. ViewState is not suitable for transferring data for back-end systems. That is, data still has to be transferred to
the back end using some form of data object.

51. Describe session handling in a webfarm, how does it work and what are the limits?

ASP.NET Session supports storing of session data in 3 ways, i] in In-Process ( in the same memory that ASP.NET
uses) , ii] out-of-process using Windows NT Service )in separate memory from ASP.NET ) or iii] in SQL Server
(persistent storage). Both the Windows Service and SQL Server solution support a webfarm scenario where all the
web-servers can be configured to share common session state store.

1. Windows Service : We can start this service by Start | Control Panel | Administrative Tools | Services | . In that
we service names ASP.NET State Service. We can start or stop service by manually or configure to start
automatically. Then we have to configure our web.config file






mode = StateServer

stateConnectionString = tcpip=127.0.0.1:42424

stateNetworkTimeout = 10

sqlConnectionString=data source = 127.0.0.1; uid=sa;pwd=

cookieless =Flase

timeout= 20 />







Here ASP.Net Session is directed to use Windows Service for state management on local server (address :
127.0.0.1 is TCP/IP loop-back address). The default port is 42424. we can configure to any port but for that we
have to manually edit the registry.

Follow these simple steps



- In a webfarm make sure you have the same config file in all your web servers.

- Also make sure your objects are serializable.

- For session state to be maintained across different web servers in the webfarm, the application path of the web-
site in the IIS Metabase should be identical in all the web-servers in the webfarm.

52. Whats the difference between Response.Write() and Response.Output. Write()?

The latter one allows you to write formattedoutput.

54. What methods are fired during the page load?

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.

55. Where does the Web page belong in the .NET Framework class hierarchy?

System.Web.UI.Page

56. Where do you store the information about the users locale? System.Web.UI.Page.Culture

57. Whats the difference between Codebehind="MyCode.aspx.cs" andSrc= "MyCode.aspx.cs"?

CodeBehind is relevant to Visual Studio.NET only.

58. Whats a bubbled event?

When you have a complex control, like DataGrid, writing an event processing routine for each object (cell,
button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid
event handler to take care of its constituents.

59. Suppose you want a certain ASP.NET function executed on MouseOver overa certain button.
Where do you add an event handler?

Its the Attributesproperty, the Add function inside that property. So
btnSubmit.Attributes.Add("onMouseOver","someClientCode();")

60. What data type does the RangeValidator control support?

Integer,String and Date.

61. Explain the differences between Server-side and Client-side code?

Server-side code runs on the server. Client-side code runs in the clients browser.

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

Server-side code.

63. Should validation (did the user enter a real date) occur server-side or client-side? Why?

Client-side. This reduces an additional request to the server to validate the users input.

64. What does the "EnableViewState" property do? Why would I want it on or off?

It enables the viewstate on the page. It allows the page to save the users input on a form.



65. What is the difference between Server.Transfer and Response.Redirect? Why would I choose
one over the other?

Server.Transfer is used to post a form to another page. Response.Redirect is used to redirect the user to
another page or site.

66. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

A DataSet can represent an entire relational database in memory, complete with tables, relations, and
views.

A DataSet is designed to work without any continuing connection to the original data source.

Data in a DataSet is bulk-loaded, rather than being loaded on demand.

There's no concept of cursor types in a DataSet.

DataSets have no current record pointer You can use For Each loops to move through the data.

You can store many edits in a DataSet, and write them to the original data source in a single operation.

Though the DataSet is universal, other objects in ADO.NET come in different versions for different data
sources.

67. Can you give an example of what might be best suited to place in the Application_Start and
Session_Start subroutines?

This is where you can set the specific variables for the Application and Session objects.

68. If Im developing an application that must accommodate multiple security levels though secure
login and my ASP.NET web application is spanned across three web-servers (using round-robin load
balancing) what would be the best approach to maintain login-in state for the users?

Maintain the login state security through a database.

69. Can you explain what inheritance is and an example of when you might use it?

When you want to inherit (use the functionality of) another class. Base Class Employee. A Manager class
could be derived from the Employee base class.

70. Whats an assembly?

Assemblies are the building blocks of the .NET framework

71. Describe the difference between inline and code behind.

Inline code written along side the html in a page. Code-behind is code written in a separate file and
referenced by the .aspx page.

72. Explain what a diffgram is, and a good use for one?

The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML.
For reading database data to an XML file to be sent to a Web Service.

73. Whats MSIL, and why should my developers need an appreciation of it if at all?

MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.



74. Which method do you invoke on the DataAdapter control to load your generated dataset with
data?

The .Fill() method

75. Can you edit data in the Repeater control?

No, it just reads the information from its data source

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

ItemTemplate

77. How can you provide an alternating color scheme in a Repeater control?

Use the AlternatingItemTemplate

78. What property must you set, and what method must you call in your code, in order to bind the
data from some data source to the Repeater control?

You must set the DataSource property and call the DataBind method.

79. What base class do all Web Forms inherit from?

The Page class.

80. Name two properties common in every validation control?

ControlToValidate property and Text property.

81. What tags do you need to add within the asp:datagrid tags to bind columns manually?

Set AutoGenerateColumns Property to false on the datagrid tag

82. What tag do you use to add a hyperlink column to the DataGrid?

83. What is the transport protocol you use to call a Web service?

SOAP is the preferred protocol.

84. True or False: A Web service can only be written in .NET?

False

85. What does WSDL stand for?

(Web Services Description Language)

86. Where on the Internet would you look for Web services?

(http://www.uddi.org)

87. Which property on a Combo Box do you set with a column name, prior to setting the
DataSource, to display data in the combo box?

DataTextField property



88. Which control would you use if you needed to make sure the values in two different controls
matched?

CompareValidator Control

89.True or False: To test a Web service you must create a windows application or Web application to
consume this service?

False, the webservice comes with a test page and it provides HTTP-GET method to test.

90. How many classes can a single .NET DLL contain?

It can contain many classes.

91. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.

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.

92. What is Microsoft .NET?

Microsoft .NET is the Microsoft strategy for connecting systems, information, and devices through Web
services so people can collaborate and communicate more effectively. .NET technology is integrated throughout
Microsoft products, providing the capability to quickly build, deploy, manage, and use connected, security-
enhanced solutions through the use of Web services.

93. What are Web Services?

Web services are small, reusable applications that help computers from many different operating system
platforms work together by exchanging messages. Web services are based on industry protocols that include XML
(Extensible Markup Language), SOAP (Simple Object Access Protocol), and WSDL (Web Services Description
Language). These protocols help computers work together across platforms and programming languages. From a
business perspective, Web services are used to reenable information technology so that it can change, move, and
adapt like other aspects of a business. They not only connect systems, they can help connect people with the
information they need, within the software applications they are used to using, and wherever they happen to be.
Microsoft offers a complete range of software that helps organizations and individuals benefit from Web service-
based connectivity. These include theMicrosoft Visual Studio .NET 2003 developer tools, the Windows Server
System that hosts Web services, and familiar desktop applications such as the Microsoft Office System that
"consume" Web services.



This illustration shows the relationship between the core technology components of .NET.



94. What are Service Oriented Architectures (SOA)?

SOA describes an information technology architecture that enables distributed computing environments
with many different types of computing platforms and applications. Web services are one of the technologies that
help make SOAs possible. As a concept, SOA has been around since the 1980s, but many early IT technologies
failed to achieve the goal of linking different types of applications and systems. By making early investments with
.NET, Microsoft has helped provide the building blocks that today are putting many enterprise customers on the
path to successfully implementing SOAs. With SOAs, companies can benefit from the unimpeded flow of
information that is the hallmark of connected systems.

95. What are Web Services Enhancements for Microsoft .NET (WSE)?

WSE is an add-on to Microsoft Visual Studio .NET and the Microsoft .NET Framework that helps developers
build greater security features into Web services using the latest Web services protocol specifications and
standards. With WSE 2.0 developers can create security-enhanced connected systems that help improve business
processes withinand beyondcorporate trust boundaries and create new revenue-generating opportunities.

96. What is a Smart Client?

Smart clients are client applications that consume Web services and reside on user hardware such as
desktop PCs, laptops, Pocket PCs, and Smartphones. They are easily deployed and managed and provide an
adaptive, responsive, and rich interactive experience by taking advantage of the computing resources on the
device and intelligently connecting to distributed data sources.

97. What is .NET Passport?

.NET Passport is a Web-based service that is designed to make signing in to Web sites fast and easy.
Passport enables participating sites to authenticate a user with a single set of sign-in credentials, alleviating the
need for users to remember numerous passwords and user names.

98. What are the Current Microsoft Products and Technologies That Use .NET?

Microsoft .NET provides everything that is needed to develop and deploy a Web service-based IT
architecture: servers to host Web services; development tools to create Web services; applications to use them;
and a network of more than 35,000 Microsoft partners to help organizations deploy and manage them. .NET
technologies are supported throughout the family of Microsoft products, including the Windows Server System, the
Windows XP desktop operating system, and the Microsoft Office System. And .NET technologies will play an even
larger role in future versions of Microsoft products.

99. Does C# support multiple inheritance?

No, use interfaces instead

100. Whats the implicit name of the parameter that gets passed into the class set method?

Value, and its datatype depends on whatever variable were changing

101. Whats the top .NET class that everything is derived from?

System.Object.

102. Hows method overriding different from overloading?

When overriding, you change the method behavior for a derived class. Overloading simply involves having
a method with the same name within the class.

103. What is CLR?

The .NET Framework provides a runtime environment called the Common Language Runtime or CLR
(similar to the Java Virtual Machine or JVM in Java), which handles the execution of code and provides useful



services for the implementation of the program. CLR takes care of code management at program execution and
provides various beneficial services such as memory management, thread management, security management,
code verification, compilation, and other system services. The managed code that targets CLR benefits from useful
features such as cross-language integration, cross-language exception handling, versioning, enhanced security,
deployment support, and debugging.

104. What is CTS?

Common Type System (CTS) describes how types are declared, used and managed in the runtime and
facilitates cross-language integration, type safety, and high performance code execution.

105. What is CLS?

The CLS is simply a specification that defines the rules to support language integration in such a way that
programs written in any language, yet can interoperate with one another, taking full advantage of inheritance,
polymorphism, exceptions, and other features. These rules and the specification are documented in the ECMA
proposed standard document, "Partition I Architecture"

106. What is strong name?

A name that consists of an assembly's identityits simple text name, version number, and culture
information (if provided)strengthened by a public key and a digital signature generated over the assembly.

107. What is Application Domain?

The primary purpose of the AppDomain is to isolate an application from other applications. Win32
processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and
doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all
memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not
access each other's memory. Objects in different application domains communicate either by transporting copies
of objects across application domain boundaries, or by using a proxy to exchange messages.

108. What is serialization in .NET? What are the ways to control serialization?

Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite
process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport
objects (e.g. during remoting), or to persist objects (e.g. to a file or database).Serialization can be defined as the
process of storing the state of an object to a storage medium. During this process, the public and private fields of
the object and the name of the class, including the assembly containing the class, are converted to a stream of
bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the
original object is created. Binary serialization preserves type fidelity, which is useful for preserving the state of an
object between different invocations of an application. For example, you can share an object between different
applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the
network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application
domain to another. XML serialization serializes only public properties and fields and does not preserve type fidelity.
This is useful when you want to provide or consume data without restricting the application that uses the data.
Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open
standard, which makes it an attractive choice. There are two separate mechanisms provided by the .NET class
library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and
uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

109. Whats an interface class?

Its an abstract class with public abstract methods all of which must be implemented in the inherited
classes

110. What is the transport protocol you use to call a Web service

SOAP is the preferred protocol





111. What are Satellite Assemblies?

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

112. What is Global Assembly Cache (GAC) and what is the purpose of it?

Each computer where the common language runtime is installed has a machine-wide code cache called
the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by
several applications on the computer. You should share assemblies by installing them into the global assembly
cache only when you need to.

113. What is Reflection in .NET?

All .NET compilers produce metadata about the types defined in the modules they produce. This metadata
is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by
a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate
the types for a module/assembly.

114. What is the managed and unmanaged code in .net?

The .NET Framework provides a run-time environment called the Common Language Runtime, which
manages the execution of code and provides services that make the development process easier. Compilers and
tools expose the runtime's functionality and enable you to write code that benefits from this managed execution
environment. Code that you develop with a language compiler that targets the runtime is called managed code; it
benefits from features such as cross-language integration, cross-language exception handling, enhanced security,
versioning and deployment support, a simplified model for component interaction, and debugging and profiling
services

115. What are Namespaces?

The namespace keyword is used to declare a scope. This namespace scope lets you organize code and
gives you a way to create globally-unique types. Even if you do not explicitly declare one, a default namespace is
created. This unnamed namespace, sometimes called the global namespace, is present in every file. Any identifier
in the global namespace is available for use in a named namespace. Namespaces implicitly have public access and
this is not modifiable.

116. What are the access-specifiers available in c#?

Private, Protected, Public, Internal, Protected Internal.

117. Advantage of ADO.Net?

ADO.NET Does Not Depend On Continuously Live Connections

Database Interactions Are Performed Using Data Commands

Data Can Be Cached in Datasets

Datasets Are Independent of Data Sources

Data Is Persisted as XML

Schemas Define Data Structures





118. Difference between OLEDB Provider and SqlClient ?

SQLClient .NET classes are highly optimized for the .net / sqlserver combination and achieve optimal
results. The SqlClient data provider is fast. It's faster than the Oracle provider, and faster than accessing database
via the OleDb layer. It's faster because it accesses the native library (which automatically gives you better
performance), and it was written with lots of help from the SQL Server team.

119. Differences between dataset.clone and dataset.copy?

Clone - Copies the structure of the DataSet, including all DataTable schemas, relations, and
constraints.Does not copy any data .Copy - Copies both the structure and data for this DataSet.

120. In a Webservice, need to display 10 rows from a table. So DataReader or DataSet is best choice?

WebService will support only DataSet.

121. What is Remoting?

The process of communication between different operating system processes, regardless of whether they
are on the same computer. The .NET remoting system is an architecture designed to simplify communication
between objects living in different application domains, whether on the same computer or not, and between
different contexts, whether in the same application domain or not.

122. Whats the difference between System.String and System.StringBuilder classes?

System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable
string where a variety of operations can be performed.

123. Whats a delegate?

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

124. Whats the implicit name of the parameter that gets passed into the class set method?

Value, and its datatype depends on whatever variable were changing.

125. How do you inherit from a class in C#?

Place a colon and then the name of the base class. Notice that its double colon in C++.

126. Does C# support multiple inheritance?

No, use interfaces instead.

127. When you inherit a protected class-level variable, who is it available to?

Classes in the same namespace.

128. Are private class-level variables inherited?

Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they
are.

129. Describe the accessibility modifier protected internal.

Its available to derived classes and classes within the same Assembly (and naturally from the base class
its declared in).



130. 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?

Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to
write one yourself, even if theres no implementation in it.

131. Whats the top .NET class that everything is derived from?

System.Object.

132. Hows method overriding different from overloading?

When overriding, you change the method behavior for a derived class. Overloading simply involves having
a method with the same name within the class.

133. What does the keyword virtual mean in the method definition?

The method can be over-ridden.

134. Can you declare the override method static while the original method is non-static?

No, you cant, the signature of the virtual method must remain the same, only the keyword virtual is
changed to keyword override.

135. Can you override private virtual methods?

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

136. Can you prevent your class from being inherited and becoming a base class for some other
classes?

Yes, thats 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. Its the same concept as final
class in Java.

137. Can you allow class to be inherited, but prevent the method from being over-ridden?

Yes, just leave the class public and make the method sealed.

138. Whats an abstract class?

A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be
inherited and have the methods over-ridden. Essentially, its a blueprint for a class without any implementation.

139. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated
choice or decision based on UML diagram)?

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.

140. Whats an interface class?

Its an abstract class with public abstract methods all of which must be implemented in the inherited
classes.

141. Why cant you specify the accessibility modifier for methods inside the interface?



They all must be public. Therefore, to prevent you from getting the false impression that you have any
freedom of choice, you are not allowed to specify any accessibility, its public by default.

142. Can you inherit multiple interfaces?

Yes, why not.

143. And if they have conflicting method names?

Its 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 youre okay.

144. Whats the difference between an interface and abstract class?

In the interface all methods must be abstract; in the abstract class some methods can be concrete. In the
interface no accessibility modifiers are allowed, which is ok in abstract classes.

145. How can you overload a method?

Different parameter data types, different number of parameters, different order of parameters.

146. If a base class has a bunch of overloaded constructors, and an inherited class has another
bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary
base constructor?

Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in
the overloaded constructor definition inside the inherited class.

147. Whats the difference between System.String and System.StringBuilder classes?

System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable
string where a variety of operations can be performed.

148. Whats the advantage of using System.Text.StringBuilder over System.String?

StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are
immutable, so each time its being operated on, a new instance is created.

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

150. Whats the difference between the System.Array.CopyTo() and System.Array. Clone()?

The first one performs a deep copy of the array, the second one is shallow.

151. How can you sort the elements of the array in descending order?

By calling Sort() and then Reverse() methods.

152. Whats the .NET datatype that allows the retrieval of data by a unique key?

HashTable.

153. Whats class SortedList underneath?

A sorted HashTable.

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



155. Whats the C# equivalent of C++ catch (), which was a catch-all statement for any possible
exception?

A catch block that catches the exception of type System.Exception. You can also omit the parameter data
type in this case and just write catch {}.

156. Can multiple catch blocks be executed?

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

157. Why is it a bad idea to throw your own exceptions?

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

158. Whats a delegate?

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

159. Whats a multicast delegate?

Its a delegate that points to and eventually fires off several methods.

160. Hows the DLL Hell problem solved in .NET?

Assembly versioning allows the application to specify not only the library it needs to run (which was
available under Win32), but also the version of the assembly.

161. What are the ways to deploy an assembly?

An MSI installer, a CAB archive, and XCOPY command.

162. Whats a satellite assembly?

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

163. What namespaces are necessary to create a localized application?

System.Globalization, System.Resources.

164. Whats the difference between // comments, /* */ comments and /// comments?

Single-line, multi-line and XML documentation comments.

165. How do you generate documentation from the C# file commented properly with a command-
line compiler?

Compile it with a /doc switch.

166. Whats the difference between and XML documentation tag?

Single line code example and multiple-line code example.

167. Is XML case-sensitive? Yes, so and are different elements.



168. What debugging tools come with the .NET SDK?

CorDBG command-line debugger, and DbgCLR graphic debugger. Visual Studio .NET uses the
DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

169. What does the This window show in the debugger?

It points to the object thats pointed to by this reference. Objects instance data is shown.

170. What does assert() do?

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

171. Whats the difference between the Debug class and Trace class?

Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and
release builds.

172. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?

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

173. Where is the output of TextWriterTraceListener redirected?

To the Console or a text file depending on the parameter passed to the constructor.

174. How do you debug an ASP.NET Web application?

Attach the aspnet_wp.exe process to the DbgClr debugger.

175. What are three test cases you should go through in unit testing?

Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper
handling), exception test cases (exceptions are thrown and caught properly).

176. Can you change the value of a variable while debugging a C# application?

Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.

177. Explain the three services model (three-tier application).

Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

178. What are advantages and disadvantages of Microsoft-provided data provider classes in
ADO.NET?

SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from
Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix,
but its a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer
provided for backward compatibility to ODBC engines.

179. Whats the role of the DataReader class in ADO.NET connections?

It returns a read-only dataset from the data source when the command is executed.





180. What is the wildcard character in SQL?

Lets say you want to query database with LIKE for all employees whose name starts with La. The wildcard
character is %, the proper query with LIKE would involve La%.

181. Explain ACID rule of thumb for transactions.

Transaction must be Atomic (it is one unit of work and does not dependent on previous and following
transactions), Consistent (data is either committed or roll back, no in-between case where something has been
updated and something hasnt), 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).

182. What connections does Microsoft SQL Server support?

Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server
username and passwords).

183. Which one is trusted and which one is untrusted?

Windows Authentication is trusted because the username and password are checked with the Active
Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the
transaction.

184. Why would you use untrusted verificaion?

Web Services might use it, as well as non-Windows applications.

185. What does the parameter Initial Catalog define inside Connection String?

The database name to connect to.

186. Whats the data provider name to connect to Access database?

Microsoft.Access.

187. What does Dispose method do with the connection object?

Deletes it from the memory.

188. What is a pre-requisite for connection pooling?

Multiple processes must agree that they will share the same connection, where every parameter is the
same, including the security settings.

















Forms



189. Can you write a class without specifying namespace? Which namespace does it belong to by
default??

Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally,
you wouldnt want global namespace.

190. You are designing a GUI application with a window 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. Whats the
problem?

One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so
it stays at the same location when resized.

191. How can you save the desired properties of Windows Forms application?

.config files in .NET are supported through the API to allow storing and retrieving information. They are nothing
more than simple XML files, sort of like what .ini files were before for Win32 apps.

192. So how do you retrieve the customized properties of a .NET application from XML .config file?

Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in
the name of the property and the type expected. Assign the result to the appropriate variable.

193. Can you automate this process?

In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.

194. My progress bar freezes up and dialog window shows blank, when an intensive background
process takes over.

Yes, you shouldve multi-threaded your GUI, with taskbar and main form being one thread, and the background
process being the other.

195. Whats the safest way to deploy a Windows Forms app?

Web deployment: the user always downloads the latest version of the code; the program runs within security
sandbox, properly written app will not require additional security privileges.

196. Why is it not a good idea to insert code into InitializeComponent method when working with
Visual Studio?

The designer will likely throw it away; most of the code inside InitializeComponent is auto-generated.

197. Whats the difference between WindowsDefaultLocation and Windows Default Bounds?

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.

198. Whats the difference between Move and LocationChanged? Resize and SizeChanged?

Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.







199. How would you create a non-rectangular window, lets say an ellipse?

Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will
effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None,
which will remove the contour and contents of the form.

200. How do you create a separator in the Menu Designer?

A hyphen - would do it. Also, an ampersand &\ would underline the next letter.

201. Hows anchoring different from docking?

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

Remoting

202. Whats a Windows process?

Its an application thats running and had been allocated memory.

203. Whats typical about a Windows process in regards to memory allocation?

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.

204. Why do you call it a process? Whats different between process and application in .NET, not
common computer usage, terminology?

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.

205. What distributed process frameworks outside .NET do you know?

Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object
Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).

206. What are possible implementations of distributed applications in .NET?

.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are
in System.Runtime.Remoting and System.Web.Services.

207. When would you use .NET Remoting and when Web services?

Use remoting for more efficient exchange of information when you control both ends of the application. Use Web
services for open-protocol-based information exchange when you are just a client or a server with the other end
belonging to someone else.

208. Whats a proxy of the server object in .NET Remoting?

Its a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles
the communication between real server object and the client object. This process is also known as marshaling.







209. What are remotable objects in .NET Remoting?

Remotable objects are the objects that can be marshaled across the application domains. You can marshal by
value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by
reference, where just a reference to an existing object is passed.

210. What are channels in .NET Remoting?

Channels represent the objects that transfer the other serialized objects from one application domain to another
and from one computer to another, as well as one process to another on the same box. A channel must exist
before an object can be transferred.

211. What security measures exist for .NET Remoting in System.Runtime.Remoting?

None. Security should be taken care of at the application level. Cryptography and other security techniques can
be applied at application or server level.

212. What is a formatter?

A formatter is an object that is responsible for encoding and serializing data into messages on one end, and
deserializing and decoding messages into data on the other end.

213. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the
trade-offs?

Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

214. Whats SingleCall activation mode used for?

If the server object is instantiated for responding to just one single request, the request should be made in
SingleCall mode.

215. Whats Singleton activation mode?

A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined
by lifetime lease.

216. How do you define the lease of the object?

By implementing ILease interface when writing the class code.

217. Can you configure a .NET Remoting object via XML file?

Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings
take precedence over machine.config.

218. How can you automatically generate interface for the remotable object in .NET with Microsoft
tools?

Use the Soapsuds tool.











ASP.NET

1. What is view state and use of it?

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

2. What are user controls and custom controls?

Custom controls:

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

User Controls:

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

3. What are the validation controls?

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

4. What's the difference between Response.Write() andResponse.Output.Write()?

The latter one allows you to write formattedoutput.

5. What methods are fired during the page load? Init()

When the page is instantiated, Load() - when the page is loaded into server memory,PreRender () - the brief
moment before the page is displayed to the user as HTML, Unload() - when page finishes loading.

6. What are the different types of caching?

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

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

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

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

7. What do you mean by authentication and authorization?



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

8. What are different types of directives in .NET?

@Page: Defines page-specific attributes used by the ASP.NET page parser and compiler. Can be included only
in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>

@Control:Defines control-specific attributes used by the ASP.NET page parser and compiler. Can be included
only in .ascx files. <%@ Control Language="VB" EnableViewState="false" %>

@Import: Explicitly imports a namespace into a page or user control. The Import directive cannot have more
than one namespace attribute. To import multiple namespaces, use multiple @Import directives. <% @
Import Namespace="System.web" %>

@Implements: Indicates that the current page or user control implements the specified .NET framework
interface.<%@ Implements Interface="System.Web.UI.IPostBackEventHandler" %>

@Register: Associates aliases with namespaces and class names for concise notation in custom server control
syntax.<%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="AdRotator.ascx" %>

@Assembly: Links an assembly to the current page during compilation, making all the assembly's classes
and interfaces available for use on the page. <%@ Assembly Name="MyAssembly" %><%@ Assembly
Src="MySource.vb" %>

@OutputCache: Declaratively controls the output caching policies of an ASP.NET page or a user control
contained in a page<%@ OutputCache Duration="#ofseconds" Location="Any | Client | Downstream | Server |
None" Shared="True | False" VaryByControl="controlname" VaryByCustom="browser | customstring"
VaryByHeader="headers" VaryByParam="parametername" %>

@Reference: Declaratively indicates that another user control or page source file should be dynamically
compiled and linked against the page in which this directive is declared.

9. How do I debug an ASP.NET application that wasn't written with Visual Studio.NET and that doesn't
use code-behind?

Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing the code
you want to debug, and set your breakpoints. Start the ASP.NET application. Go back to DbgClr, choose Debug
Processes from the Tools menu, and select aspnet_wp.exe from the list of processes. (If aspnet_wp.exe doesn't
appear in the list,check the "Show system processes" box.) Click the Attach button to attach to aspnet_wp.exe
and begin debugging.

Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can enable tell ASP.NET to
build debug executables by placing a

<%@ Page Debug="true" %> statement at the top of an ASPX file or a />statement in a Web.config file.

10. Can a user browsing my Web site read my Web.config or Global.asax files?

No. The section of Machine.config, which holds the master configuration settings for
ASP.NET, contains entries that map ASAX files, CONFIG files, and selected other file types to an HTTP handler
named HttpForbiddenHandler, which fails attempts to retrieve the associated file. You can modify it by editing
Machine.config or including an section in a local Web.config file.

11. What's the difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript?

RegisterClientScriptBlock is for returning blocks of client-side script containing functions. RegisterStartupScript is
for returning blocks of client-script not packaged in functions-in other words, code that's to execute when the



page is loaded. The latter positions script blocks near the end of the document so elements on the page that the
script interacts are loaded before the script runs.<%@ Reference Control="MyControl.ascx" %>

12. What are different templates available in Repeater,DataList and Datagrid ?

Templates enable one to apply complicated formatting to each of the items displayed by a control.Repeater control
supports five types of templates.HeaderTemplate controls how the header of the repeater control is
formatted.ItemTemplate controls the formatting of each item displayed.AlternatingItemTemplate controls how
alternate items are formatted and the SeparatorTemplate displays a separator between each item
displyed.FooterTemplate is used for controlling how the footer of the repeater control is formatted.The DataList
and Datagrid supports two templates in addition to the above five.SelectedItem Template controls how a selected
item is formatted and EditItemTemplate controls how an item selected for editing is formatted.

13. What is ViewState ? and how it is managed ?

ASP.NET ViewState is a new kind of state service that developers can use to track UI state on a per-user basis.
Internally it uses an an old Web programming trick-roundtripping state in a hidden form field and bakes it right
into the page-processing framework.It needs less code to write and maintain state in your Web-based forms.

14. What is web.config file ?

Web.config file is the configuration file for the Asp.net web application. There is one web.config file for one
asp.net application which configures

the particular application. Web.config file is written in XML with specific tags having specific meanings.It includes
databa which includes

connections,Session States,Error Handling,Security etc.

For example :

< configuration >

< appSettings >

< add key="ConnectionString"

value="server=localhost;uid=sa;pwd=;database=MyDB" / >

< /appSettings >

< /configuration >

15. What is advantage of viewstate and what are benefits?

When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a
lot of information and the server comes back with an error. You will have to go back to the form and correct the
information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to
start all over again! The site did not maintain your ViewState.With ASP .NET, the form reappears in the browser
window together with all form values.This is because ASP .NET maintains your ViewState. The ViewState indicates
the status of the page when submitted to the server.

16. What tags do you need to add within the asp:datagrid tags to bind columns manually?

Set AutoGenerateColumns Property to false on the datagrid tag and then use Column tag and an ASP:databound
tag

< asp:DataGrid runat="server" id="ManualColumnBinding" AutoGenerateColumns="False" >

< Columns >



< asp:BoundColumn HeaderText="Column1" DataField="Column1"/ >

< asp:BoundColumn HeaderText="Column2" DataField="Column2"/ >

< /Columns >

< /asp:DataGrid >





Which property on a Combo Box do you set with a column name, prior to setting the DataSource,
to display data in the combo box?

DataTextField and DataValueField

17. Which control would you use if you needed to make sure the values in two different controls
matched?

CompareValidator is used to ensure that two fields are identical.

18. What is validationsummary server control?where it is used?.

The ValidationSummary control allows you to summarize the error messages from all validation controls
on a Web page in a single location. The summary can be displayed as a list, a bulleted list, or a single paragraph,
based on the value of the DisplayMode property. The error message displayed in the ValidationSummary control
for each validation control on the page is specified by the ErrorMessage property of each validation control. If the
ErrorMessage property of the validation control is not set, no error message is displayed in the ValidationSummary
control for that validation control. You can also specify a custom title in the heading section of the
ValidationSummary control by setting the HeaderText property.

You can control whether the ValidationSummary control is displayed or hidden by setting the ShowSummary
property. The summary can also be displayed in a message box by setting the ShowMessageBox property to true.

19. What is the sequence of operation takes place when a page is loaded?

BeginTranaction - only if the request is transacted

Init - every time a page is processed

LoadViewState - Only on postback

ProcessPostData1 - Only on postback

Load - every time

ProcessData2 - Only on Postback

RaiseChangedEvent - Only on Postback

RaisePostBackEvent - Only on Postback

PreRender - everytime

BuildTraceTree - only if tracing is enabled

SaveViewState - every time



Render - Everytime

End Transaction - only if the request is transacted

Trace.EndRequest - only when tracing is enabled

UnloadRecursive - Every request

20. Difference between asp and asp.net?.

"ASP (Active Server Pages) and ASP.NET are both server side technologies for building web sites and web
applications, ASP.NET is Managed compiled code - asp is interpreted. and ASP.net is fully Object oriented. ASP.NET
has been entirely re-architected to provide a highly productive programming experience based on the .NET
Framework, and a robust infrastructure for building reliable and scalable web applications."

21. Name the validation control available in asp.net?.

RequiredField, RangeValidator,RegularExpression,Custom validator,compare Validator

22. What are the various ways of securing a web site that could prevent from hacking ?

1) Authentication/Authorization

2) Encryption/Decryption

3) Maintaining web servers outside the corporate firewall. etc.,

22. What is the difference between in-proc and out-of-proc?

An inproc is one which runs in the same process area as that of the client giving tha advantage of speed
but the disadvantage of stability becoz if it crashes it takes the client application also with it.Outproc is one which
works outside the clients memory thus giving stability to the client, but we have to compromise a bit on speed.

23. When youre running a component within ASP.NET, what process is it running within on Windows
XP? Windows 2000? Windows 2003?

On Windows 2003 (IIS 6.0) running in native mode, the component is running within the w3wp.exe process
associated with the application pool which has been configured for the web application containing the component.

On Windows 2003 in IIS 5.0 emulation mode, 2000, or XP, it's running within the IIS helper process whose name I
do not remember, it being quite a while since I last used IIS 5.0.

24. What does aspnet_regiis -i do ?

Aspnet_regiis.exe is The ASP.NET IIS Registration tool allows an administrator or installation program to easily
update the script maps for an ASP.NET application to point to the ASP.NET ISAPI version associated with the tool.
The tool can also be used to display the status of all installed versions of ASP. NET, register the ASP.NET version
coupled with the tool, create client-script directories, and perform other configuration operations.

When multiple versions of the .NET Framework are executing side-by-side on a single computer, the ASP.NET
ISAPI version mapped to an ASP.NET application determines which version of the common language runtime is
used for the application.

The tool can be launched with a set of optional parameters. Option "i" Installs the version of ASP.NET associated
with Aspnet_regiis.exe and updates the script maps at the IIS metabase root and below. Note that only
applications that are currently mapped to an earlier version of ASP.NET are affected





25. What is a PostBack?

The process in which a Web page sends data back to the same page on the server.

26. What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?

ViewState is the mechanism ASP.NET uses to keep track of server control state values that don't
otherwise post back as part of the HTTP form. ViewState Maintains the UI State of a Page

ViewState is base64-encoded.

It is not encrypted but it can be encrypted by setting EnableViewStatMAC="true" & setting the machineKey
validation type to 3DES. If you want to NOT maintain the ViewState, include the directive < %@ Page
EnableViewState="false" % > at the top of an .aspx page or add the attribute EnableViewState="false" to any
control.

27. What is the < machinekey > element and what two ASP.NET technologies is it used for?

Configures keys to use for encryption and decryption of forms authentication cookie data and view state
data, and for verification of out-of-process session state identification.There fore 2 ASP.Net technique in which it is
used are Encryption/Decryption & Verification

28. What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of
each?

ASP.NET provides three distinct ways to store session data for your application: in-process session state,
out-of-process session state as a Windows service, and out-of-process session state in a SQL Server database.
Each has it advantages.

1.In-process session-state mode

Limitations:

* When using the in-process session-state mode, session-state data is lost if aspnet_wp.exe or the application
domain restarts.

* If you enable Web garden mode in the < processModel > element of the application's Web.config file, do not
use in-process session-state mode. Otherwise, random data loss can occur.

Advantage:

* in-process session state is by far the fastest solution. If you are storing only small amounts of volatile data in
session state, it is recommended that you use the in-process provider.

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

3. SQL mode, session states are stored in a SQL Server database and the worker process talks directly to SQL. The
ASP.NET worker processes are then able to take advantage of this simple storage service by serializing and saving
(using .NET serialization services) all objects within a client's Session collection at the end of each Web request

Both these out-of-process solutions are useful primarily if you scale your application across multiple processors or
multiple computers, or where data cannot be lost if a server or process is restarted.

29. What is the difference between HTTP-Post and HTTP-Get?

As their names imply, both HTTP GET and HTTP POST use HTTP as their underlying protocol. Both of these
methods encode request parameters as name/value pairs in the HTTP request.

The GET method creates a query string and appends it to the script's URL on the server that handles the request.



The POST method creates a name/value pairs that are passed in the body of the HTTP request message.

Name and describe some HTTP Status Codes and what they express to the requesting client.

When users try to access content on a server that is running Internet Information Services (IIS) through HTTP or
File Transfer Protocol (FTP), IIS returns a numeric code that indicates the status of the request. This status code is
recorded in the IIS log, and it may also be displayed in the Web browser or FTP client. The status code can
indicate whether a particular request is successful or unsuccessful and can also reveal the exact reason why a
request is unsuccessful. There are 5 groups ranging from 1xx - 5xx of http status codes exists.

101 - Switching protocols.

200 - OK. The client request has succeeded

302 - Object moved.

400 - Bad request.

500.13 - Web server is too busy.

30. Explain < @OutputCache% > and the usage of VaryByParam, VaryByHeader.

OutputCache is used to control the caching policies of an ASP.NET page or user control. To cache a page
@OutputCache directive should be defined as follows < %@ OutputCache Duration="100" VaryByParam="none"
% >

VaryByParam: A semicolon-separated list of strings used to vary the output cache. By default, these strings
correspond to a query string value sent with GET method attributes, or a parameter sent using the POST method.
When this attribute is set to multiple parameters, the output cache contains a different version of the requested
document for each specified parameter. Possible values include none, *, and any valid query string or POST
parameter name.

VaryByHeader: A semicolon-separated list of HTTP headers used to vary the output cache. When this attribute is
set to multiple headers, the output cache contains a different version of the requested document for each specified
header.

31. What is the difference between repeater over datalist and datagrid?

The Repeater class is not derived from the WebControl class, like the DataGrid and DataList. Therefore, the
Repeater lacks the stylistic properties common to both the DataGrid and DataList. What this boils down to is that if
you want to format the data displayed in the Repeater, you must do so in the HTML markup.

The Repeater control provides the maximum amount of flexibility over the HTML produced. Whereas the DataGrid
wraps the DataSource contents in an HTML < table >, and the DataList wraps the contents in either an HTML <
table > or < span > tags (depending on the DataList's RepeatLayout property), the Repeater adds absolutely no
HTML content other than what you explicitly specify in the templates.

While using Repeater control, If we wanted to display the employee names in a bold font we'd have to alter the
"ItemTemplate" to include an HTML bold tag, Whereas with the DataGrid or DataList, we could have made the text
appear in a bold font by setting the control's ItemStyle-Font-Bold property to True.

The Repeater's lack of stylistic properties can drastically add to the development time metric. For example,
imagine that you decide to use the Repeater to display data that needs to be bold, centered, and displayed in a
particular font-face with a particular background color. While all this can be specified using a few HTML tags, these
tags will quickly clutter the Repeater's templates. Such clutter makes it much harder to change the look at a later
date. Along with its increased development time, the Repeater also lacks any built-in functionality to assist in
supporting paging, editing, or editing of data. Due to this lack of feature-support, the Repeater scores poorly on
the usability scale.



However, The Repeater's performance is slightly better than that of the DataList's, and is more noticeably better
than that of the DataGrid's. Following figure shows the number of requests per second the Repeater could handle
versus the DataGrid and DataList

32. Can we handle the error and redirect to some pages using web.config?

Yes, we can do this, but to handle errors, we must know the error codes; only then we can take the user to a
proper error message page, else it may confuse the user.

CustomErrors Configuration section in web.config file:

The default configuration is:

< customErrors mode="RemoteOnly" defaultRedirect="Customerror.aspx" >

< error statusCode="404" redirect="Notfound.aspx" / >

< /customErrors >

If mode is set to Off, custom error messages will be disabled. Users will receive detailed exception error messages.

If mode is set to On, custom error messages will be enabled.

If mode is set to RemoteOnly, then users will receive custom errors, but users accessing the site locally will receive
detailed error messages.

Add an < error > tag for each error you want to handle. The error tag will redirect the user to the Notfound.aspx
page when the site returns the 404 (Page not found) error.

[Example]

There is a page MainForm.aspx

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Put user code to initialize the page here

Dim str As System.Text.StringBuilder

str.Append("hi") ' Error Line as str is not instantiated

Response.Write(str.ToString)

End Sub

[Web.Config]

< customErrors mode="On" defaultRedirect="Error.aspx"/ >

' a simple redirect will take the user to Error.aspx [user defined] error file.

< customErrors mode="RemoteOnly" defaultRedirect="Customerror.aspx" >

< error statusCode="404" redirect="Notfound.aspx" / >

< /customErrors >

'This will take the user to NotFound.aspx defined in IIS.



33. How do you implement Paging in .Net?

The DataGrid provides the means to display a group of records from the data source (for example, the first 10),
and then navigate to the "page" containing the next 10 records, and so on through the data.

Using Ado.Net we can explicit control over the number of records returned from the data source, as well as how
much data is to be cached locally in the DataSet.

1.Using DataAdapter.fill method give the value of 'Maxrecords' parameter

(Note: - Don't use it because query will return all records but fill the dataset based on value of 'maxrecords'
parameter).

2.For SQL server database, combines a WHERE clause and a ORDER BY clause with TOP predicate.

3.If Data does not change often just cache records locally in DataSet and just take some records from the DataSet
to display.

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

Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested
page. Data can be persist across the pages using Context.Item collection, which is one of the best way to transfer
data from one page to another keeping the page state alive.

Response.Dedirect() :client knows the physical location (page name and query string as well). Context.Items loses
the persistence when navigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new
Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has
several important drawbacks. The biggest problem is that this method causes each page to be treated as a
separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect
introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all
of the properties in the Request object. Sure, there are workarounds, but they're difficult. Finally,
Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems.
As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the
server without requiring a roundtrip to the client.

Response.Redirect sends a response to the client browser instructing it to request the second page. This requires a
round-trip to the client, and the client initiates the Request for the second page. Server.Transfer transfers the
process to the second page without making a round-trip to the client. It also transfers the HttpContext to the
second page, enabling the second page access to all the values in the HttpContext of the first page.

35. Can you create an app domain?

Yes, We can create user app domain by calling on of the following overload static methods of the
System.AppDomain class

1. Public static AppDomain CreateDomain(String friendlyName)

2. Public static AppDomain CreateDomain(String friendlyName, Evidence securityInfo)

3. Public static AppDomain CreateDomain(String friendlyName, Evidence securityInfo, AppDomainSetup info)

4. Public static AppDomain CreateDomain(String friendlyName, Evidence securityInfo, String appBasePath, String
appRelativeSearchPath, bool shadowCopyFiles)

36. What are the various security methods which IIS Provides apart from .NET ?

The various security methods which IIS provides are

a) Authentication Modes



b) IP Address and Domain Name Restriction

c) DNS Lookups DNS Lookups

d) The Network ID and Subnet Mask

e) SSL

37.What is Web Gardening? How would using it affect a design?

The Web Garden Model

The Web garden model is configurable through the section of the machine.config file. Notice that the
section is the only configuration section that cannot be placed in an application-specific web.config file. This means
that the Web garden mode applies to all applications running on the machine. However, by using the node in the
machine.config source, you can adapt machine-wide settings on a per-application basis.

Two attributes in the section affect the Web garden model. They are webGarden and cpuMask. The
webGarden attribute takes a Boolean value that indicates whether or not multiple worker processes (one per each
affinitized CPU) have to be used. The attribute is set to false by default. The cpuMask attribute stores a DWORD
value whose binary representation provides a bit mask for the CPUs that are eligible to run the ASP.NET worker
process. The default value is -1 (0xFFFFFF), which means that all available CPUs can be used. The contents of the
cpuMask attribute is ignored when the webGarden attribute is false. The cpuMask attribute also sets an upper
bound to the number of copies of aspnet_wp.exe that are running.

Web gardening enables multiple worker processes to run at the same time. However, you should note that
all processes will have their own copy of application state, in-process session state, ASP.NET cache, static data,
and all that is needed to run applications. When the Web garden mode is enabled, the ASP.NET ISAPI launches as
many worker processes as there are CPUs, each a full clone of the next (and each affinitized with the
corresponding CPU). To balance the workload, incoming requests are partitioned among running processes in a
round-robin manner. Worker processes get recycled as in the single processor case. Note that ASP.NET inherits
any CPU usage restriction from the operating system and doesn't include any custom semantics for doing this.

All in all, the Web garden model is not necessarily a big win for all applications. The more stateful
applications are, the more they risk to pay in terms of real performance. Working data is stored in blocks of shared
memory so that any changes entered by a process are immediately visible to others. However, for the time it
takes to service a request, working data is copied in the context of the process. Each worker process, therefore,
will handle its own copy of working data, and the more stateful the application, the higher the cost in performance.
In this context, careful and savvy application benchmarking is an absolute must.

Changes made to the section of the configuration file are effective only after IIS is restarted. In IIS 6,
Web gardening parameters are stored in the IIS metabase; the webGarden and cpuMask attributes are ignored.

38. What is view state?.where it stored?.can we disable it?

The web is state-less protocol, so the page gets instantiated, executed, rendered and then disposed on
every round trip to the server. The developers code to add "statefulness" to the page by using Server-side storage
for the state or posting the page to itself. When require to persist and read the data in control on webform,
developer had to read the values and store them in hidden variable (in the form), which were then used to restore
the values. With advent of .NET framework, ASP.NET came up with ViewState mechanism, which tracks the data
values of server controls on ASP.NET webform. In effect,ViewState can be viewed as "hidden variable managed by
ASP.NET framework!". When ASP.NET page is executed, data values from all server controls on page are collected
and encoded as single string, which then assigned to page's hidden atrribute "< input type=hidden >", that is
part of page sent to the client.

ViewState value is temporarily saved in the client's browser.ViewState can be disabled for a single control, for an
entire page orfor an entire web application. The syntax is:

Disable ViewState for control (Datagrid in this example)

< asp:datagrid EnableViewState="false" ... / >



Disable ViewState for a page, using Page directive

< %@ Page EnableViewState="False" ... % >

Disable ViewState for application through entry in web.config

< Pages EnableViewState="false" ... / >








C# and VB.NET



Explain the differences between Server-side and Client-side code?

Server side code executes on the server.For this to occur page has to be submitted or posted back.Events fired by
the controls are executed on the server.Client side code executes in the browser of the client without submitting
the page.

e.g. In ASP.NET for webcontrols like asp:button the click event of the button is executed on the server hence the
event handler for the same in a part of the code-behind (server-side code). Along the server-side code events one
can also attach client side events which are executed in the clients browser i.e. javascript events.

How does VB.NET/C# achieve polymorphism?

Polymorphism is also achieved through interfaces. Like abstract classes, interfaces also describe the methods that
a class needs to implement. The difference between abstract classes and interfaces is that abstract classes always
act as a base class of the related classes in the class hierarchy. For example, consider a hierarchy-car and truck
classes derived from four-wheeler class; the classes two-wheeler and four-wheeler derived from an abstract class
vehicle. So, the class 'vehicle' is the base class in the class hierarchy. On the other hand dissimilar classes can
implement one interface. For example, there is an interface that compares two objects. This interface can be
implemented by the classes like box, person and string, which are unrelated to each other.

C# allows multiple interface inheritance. It means that a class can implement more than one interface. The
methods declared in an interface are implicitly abstract. If a class implements an interface, it becomes mandatory
for the class to override all the methods declared in the interface, otherwise the derived class would become
abstract.

Can you explain what inheritance is and an example of when you might use it?

The savingaccount class has two data members-accno that stores account number, and trans that keeps track of
the number of transactions. We can create an object of savingaccount class as shown below.

savingaccount s = new savingaccount ( "Amar", 5600.00f ) ;

From the constructor of savingaccount class we have called the two-argument constructor of the account class
using the base keyword and passed the name and balance to this constructor using which the data member's
name and balance are initialised.

We can write our own definition of a method that already exists in a base class. This is called method overriding.
We have overridden the deposit( ) and withdraw( ) methods in the savingaccount class so that we can make sure
that each account maintains a minimum balance of Rs. 500 and the total number of transactions do not exceed 10.
From these methods we have called the base class's methods to update the balance using the base keyword. We
have also overridden the display( ) method to display additional information, i.e. account number.



Working of currentaccount class is more or less similar to that of savingaccount class.

Using the derived class's object, if we call a method that is not overridden in the derived class, the base class
method gets executed. Using derived class's object we can call base class's methods, but the reverse is not
allowed.

Unlike C++, C# does not support multiple inheritance. So, in C# every class has exactly one base class.

Now, suppose we declare reference to the base class and store in it the address of instance of derived class as
shown below.

account a1 = new savingaccount ( "Amar", 5600.00f ) ;

account a2 = new currentaccount ( "MyCompany Pvt. Ltd.", 126000.00f) ;

Such a situation arises when we have to decide at run-time a method of which class in a class hierarchy should get
called. Using a1 and a2, suppose we call the method display( ), ideally the method of derived class should get
called. But it is the method of base class that gets called. This is because the compiler considers the type of
reference (account in this case) and resolves the method call. So, to call the proper method we must make a small
change in our program. We must use the virtual keyword while defining the methods in base class as shown
below.

public virtual void display( ) { }

We must declare the methods as virtual if they are going to be overridden in derived class. To override a virtual
method in derived classes we must use the override keyword as given below.

public override void display( ) { }

Now it is ensured that when we call the methods using upcasted reference, it is the derived class's method that
would get called. Actually, when we declare a virtual method, while calling it, the compiler considers the contents
of the reference rather than its type.

If we don't want to override base class's virtual method, we can declare it with new modifier in derived class. The
new modifier indicates that the method is new to this class and is not an override of a base class method.

How would you implement inheritance using VB.NET/C#?

When we set out to implement a class using inheritance, we must first start with an existing class from which we
will derive our new subclass. This existing class, or base class, may be part of the .NET system class library
framework, it may be part of some other application or .NET assembly, or we may create it as part of our existing
application. Once we have a base class, we can then implement one or more subclasses based on that base class.
Each of our subclasses will automatically have all of the methods, properties, and events of that base class ?
including the implementation behind each method, property, and event. Our subclass can add new methods,
properties, and events of its own - extending the original interface with new functionality. Additionally, a subclass
can replace the methods and properties of the base class with its own new

implementation - effectively overriding the original behavior and replacing it with new behaviors. Essentially
inheritance is a way of merging functionality from an existing class into our new subclass. Inheritance also defines
rules for how these methods, properties, and events can be merged. In VB.NET we can use implements keyword
for inheritance, while in C# we can use the sign ( : ) between subclass and baseclass.

How is a property designated as read-only?

In VB.NET:

Private mPropertyName as DataType

Public ReadOnly Property PropertyName() As DataType



Get Return mPropertyName

End Get

End Property

In C#

Private DataType mPropertyName;

public returntype PropertyName

{

get{

//property implementation goes here

return mPropertyName;

}

// Do not write the set implementation

}



What is hiding in CSharp ?

Hiding is also called as Shadowing. This is the concept of Overriding the methods. It is a concept used in the
Object Oriented Programming.

E.g.

public class ClassA {

public virtual void MethodA() {

Trace.WriteLine("ClassA Method");

}

}

public class ClassB : ClassA {

public new void MethodA() {

Trace.WriteLine("SubClass ClassB Method");

}

}

public class TopLevel {



static void Main(string[] args) {

TextWriter tw = Console.Out;

Trace.Listeners.Add(new TextWriterTraceListener(tw));



ClassA obj = new ClassB();

obj.MethodA(); // Outputs Class A Method"



ClassB obj1 = new ClassB();

obj.MethodA(); // Outputs SubClass ClassB Method

}

}

What is the difference between an XML "Fragment" and an XML "Document."

An XML fragment is an XML document with no single top-level root element. To put it simple it is a part (fragment)
of a well-formed xml document. (node) Where as a well-formed xml document must have only one root element.

What does it meant to say the canonical form of XML?

"The purpose of Canonical XML is to define a standard format for an XML document. Canonical XML is a very strict
XML syntax, which lets documents in canonical XML be compared directly.

Using this strict syntax makes it easier to see whether two XML documents are the same. For example, a section
of text in one document might read Black & White, whereas the same section of text might read Black & White in
another document, and even in another. If you compare those three documents byte by byte, they'll be different.
But if you write them all in canonical XML, which specifies every aspect of the syntax you can use, these three
documents would all have the same version of this text (which would be Black & White) and could be compared
without problem.

This Comparison is especially critical when xml documents are digitally signed. The digital signal may be
interpreted in different way and the document may be rejected.

Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to
solve?

"The XML Information Set (Infoset) defines a data model for XML. The Infoset describes the abstract
representation of an XML Document. Infoset is the generalized representation of the XML Document, which is
primarily meant to act as a set of definitions used by XML technologies to formally describe what parts of an XML
document they operate upon.

The Document Object Model (DOM) is one technology for representing an XML Document in memory and to
programmatically read, modify and manipulate a xml document.

Infoset helps defining generalized standards on how to use XML that is not dependent or tied to a particular XML
specification or API. The Infoset tells us what part of XML Document should be considered as significant
information.





Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why?

Document Type Definition (DTD) describes a model or set of rules for an XML document. XML Schema Definition
(XSD) also describes the structure of an XML document but XSDs are much more powerful.

The disadvantage with the Document Type Definition is it doesnt support data types beyond the basic 10 primitive
types. It cannot properly define the type of data contained by the tag.

An Xml Schema provides an Object Oriented approach to defining the format of an xml document. The Xml
schema support most basic programming types like integer, byte, string, float etc., We can also define complex
types of our own which can be used to define a xml document.

Xml Schemas are always preferred over DTDs as a document can be more precisely defined using the XML
Schemas because of its rich support for data representation.

Speaking of Boolean data types, what's different between C# and C/C++?

There's no conversion between 0 and false, as well as any other number and true, like in C/C++.

How do you convert a string into an integer in .NET?

Int32.Parse(string)

Can you declare a C++ type destructor in C# like ~MyClass()?

Yes, but what's the point, since it will call Finalize(), and Finalize() has no guarantees when the memory will be
cleaned up, plus, it introduces additional load on the garbage collector.

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

No semicolon.

What's the difference between const and readonly?

The readonly keyword is different from the const keyword. A const field can only be initialized at the
declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore,
readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-
time constant, the readonly field can be used for runtime constants as in the following example:

public static readonly uint l1 = (uint) DateTime.Now.Ticks;

What does \a character do?

On most systems, produces a rather annoying beep.

Can you create enumerated data types in C#?

Yes.

What's different about switch statements in C#?

No fall-throughs allowed.

What happens when you encounter a continue statement inside the for loop?

The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop.

How do you retrieve the customized properties of a .NET application from XML .config file? Can you
automate this process?



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. In Visual Studio
yes, use Dynamic Properties for automatic .config creation, storage and retrieval.

What are array?

An array is a data structure that contains a number of variables, which are accessed through computed indices.
The variables contained in an array, also called the elements of the array, are all of the same type, and this type is
called the element type of the array.

An array has a rank that determines the number of indices associated with each array element. The rank of an
array is also referred to as the dimensions of the array. An array with a rank of one is called a single-dimensional
array. An array with a rank greater than one is called a multi-dimensional array. Specific sized multidimensional
arrays are often referred to as two-dimensional arrays, three-dimensional arrays, and so on.

What are jagged arrays?

A jagged array is an array whose elements are arrays. The elements of jagged array can be of different
dimensions and sizes. A jagged array is sometimes called as array-of-arrays. It is called jagged because each of
its rows is of different size so the final or graphical representation is not a square.

When you create a jagged array you declare the number of rows in your array. Each row will hold an array that
will be on any length. Before filling the values in the inner arrays you must declare them.

Jagged array declaration in C#:For e.g. : int [] [] myJaggedArray = new int [3][];

Declaration of inner arrays:

myJaggedArray[0] = new int[5] ; // First inner array will be of length 5.

myJaggedArray[1] = new int[4] ; // Second inner array will be of length 4.

myJaggedArray[2] = new int[3] ; // Third inner array will be of length 3.

Now to access third element of second row we write: int value = myJaggedArray[1][2];

Note that while declaring the array the second dimension is not supplied because this you will declare later on in
the code.Jagged array are created out of single dimensional arrays so be careful while using them. Dont confuse it
with multi-dimensional arrays because unlike them jagged arrays are not rectangular arrays.

What is a delegate, why should you use it and how do you call it ?

A delegate is a reference type that refers to a Shared method of a type or to an instance method of an object.
Delegate is like a function pointer in C and C++. Pointers are used to store the address of a thing. Delegate lets
some other code call your function without needing to know where your function is actually located. All events in
.NET actually use delegates in the background to wire up events. Events are really just a modified form of a
delegate.

It should give you an idea of some different areas in which delegates may be appropriate:

They enable callback functionality in multi-tier applications as demonstrated in the examples above.


The CacheItemRemoveCallback delegate can be used in ASP.NET to keep cached information up to date.
When the cached information is removed for any reason, the associated callback is exercised and could contain a
reload of the cached information.

Use delegates to facilitate asynchronous processing for methods that do not offer asynchronous behavior.



Events use delegates so clients can give the application events to call when the event is fired. Exposing
custom events within your applications requires the use of delegates.

How does the XmlSerializer work?

XmlSerializer in the .NET Framework is a great tool to convert Xml into runtime objects and vice versa

If you define integer variable and a object variable and a structure then how those will be plotted in
memory.

Integer , structure System.ValueType -- Allocated memory on stack , infact integer is primitive type recognized
and allocated memory by compiler itself .

Infact , System.Int32 definition is as follows :

[C#]

[Serializable]

public struct Int32 : IComparable, IFormattable, IConvertible

So , its a struct by definition , which is the same case with various other value types .

Object Base class , that is by default reference type , so at runtime JIT compiler allocates memory on the Heap
Data structure .

Reference types are defined as class , derived directly or indirectly by System.ReferenceType

Whats an abstract class?

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

What is an interface class?

Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not
provide implementation. They are implemented by classes, and defined as separate entities from classes.

Whats the difference between an interface and abstract class?

In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods
can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have
accessibility modifiers

What is the difference between a Struct and a Class?

Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another
difference is that structs cannot inherit.













Remoting FAQ's

________________________________________

What distributed process frameworks outside .NET do you know?

Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object
Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation
(RMI).

What are possible implementations of distributed applications in .NET?

.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are
in System.Runtime.Remoting and System.Web.Services.

When would you use .NET Remoting and when Web services?

Use remoting for more efficient exchange of information when you control both ends of the application. Use Web
services for open-protocol-based information exchange when you are just a client or a server with the other end
belonging to someone else.

What's a proxy of the server object in .NET Remoting?

It's a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles
the communication between real server object and the client object. This process is also known as marshaling.

What are remotable objects in .NET Remoting?

Remotable objects are the objects that can be marshaled across the application domains. You can marshal by
value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by
reference, where just a reference to an existing object is passed.

What are channels in .NET Remoting?

Channels represent the objects that transfer the other serialized objects from one application domain to another
and from one computer to another, as well as one process to another on the same box. A channel must exist
before an object can be transferred.

What security measures exist for .NET Remoting in System.Runtime.Remoting?

None. Security should be taken care of at the application level. Cryptography and other security techniques can
be applied at application or server level.

What is a formatter?

A formatter is an object that is responsible for encoding and serializing data into messages on one end, and
deserializing and decoding messages into data on the other end.

Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-
offs?

Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

What's SingleCall activation mode used for?

If the server object is instantiated for responding to just one single request, the request should be made in
SingleCall mode.





What's Singleton activation mode?

A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined
by lifetime lease.

How do you define the lease of the object?

By implementing ILease interface when writing the class code.

Can you configure a .NET Remoting object via XML file?

Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings
take precedence over machine.config.

How can you automatically generate interface for the remotable object in .NET with Microsoft tools?

Use the Soapsuds tool.

What are CAO's i.e. Client Activated Objects ?

Client-activated objects are objects whose lifetimes are controlled by the calling application domain, just as they
would be if the object were local to the client. With client activation, a round trip to the server occurs when the
client tries to create an instance of the server object, and the client proxy is created using an object reference
(ObjRef) obtained on return from the creation of the remote object on the server. Each time a client creates an
instance of a client-activated type, that instance will service only that particular reference in that particular client
until its lease expires and its memory is recycled. If a calling application domain creates two new instances of the
remote type, each of the client references will invoke only the particular instance in the server application domain
from which the reference was returned.

In COM, clients hold an object in memory by holding a reference to it. When the last client releases its last
reference, the object can delete itself. Client activation provides the same client control over the server object's
lifetime, but without the complexity of maintaining references or the constant pinging to confirm the continued
existence of the server or client. Instead, client-activated objects use lifetime leases to determine how long they
should continue to exist. When a client creates a remote object, it can specify a default length of time that the
object should exist. If the remote object reaches its default lifetime limit, it contacts the client to ask whether it
should continue to exist, and if so, for how much longer. If the client is not currently available, a default time is
also specified for how long the server object should wait while trying to contact the client before marking itself for
garbage collection. The client might even request an indefinite default lifetime, effectively preventing the remote
object from ever being recycled until the server application domain is torn down. The difference between this and
a server-activated indefinite lifetime is that an indefinite server-activated object will serve all client requests for
that type, whereas the client-activated instances serve only the client and the reference that was responsible for
their creation. For more information, see Lifetime Leases.

To create an instance of a client-activated type, clients either configure their application programmatically (or
using a configuration file) and call new (New in Visual Basic), or they pass the remote object's configuration in a
call to Activator.CreateInstance. The following code example shows such a call, assuming a TcpChannel has been
registered to listen on port 8080.

How many processes can listen on a single TCP/IP port? One.

What technology enables out-of-proc communication in .NET?

Most usually Remoting;.NET remoting enables client applications to use objects in other processes on the
same computer or on any other computer available on its network.While you could implement an out-of-proc
component in any number of other ways, someone using the term almost always means Remoting.

How can objects in two diff. App Doimains communicate with each other?

.Net framework provides various ways to communicate with objects in different app domains.

First is XML Web Service on internet, its good method because it is built using HTTP protocol and SOAP formatting.



If the performance is the main concern then go for second option which is .Net remoting because it gives you the
option of using binary encoding and the default TcpChannel, which offers the best interprocess communication
performance

What is the difference between .Net Remoting and Web Services?

Although we can develop an application using both technologies, each of them has its distinct advantages. Yes you
can look at them in terms of performance but you need to consider your need first. There are many other factors
such authentications, authorizing in process that need to be considered.

Point Remoting Webservices

If your application needs interoperability with other platforms or operating systems No Yes, Choose
Web Services because it is more flexible in that they are support SOAP.

If performance is the main requirement with security You should use the TCP channel and the binary
formatter No

Complex Programming Yes No

State Management Supports a range of state management, depending on what object lifetime scheme you
choose (single call or singleton call). Its stateless service management (does not inherently correlate multiple
calls from the same user)

Transport Protocol It can access through TCP or HTTP channel. It can be access only through HTTP
channel.

How do you trigger the Paint event in System.Drawing?

Invalidate the current form, the OS will take care of repainting. The Update method forces the repaint.

With these events, why wouldn't Microsoft combine Invalidate and Paint, so that you wouldn't have to
tell it to repaint, and then to force it to repaint?

Painting is the slowest thing the OS does, so usually telling it to repaint, but not forcing it allows for the process to
take place in the background.

How can you assign an RGB color to a System.Drawing.Color object?

Call the static method FromArgb of this class and pass it the RGB values.

What class does Icon derive from?

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

Before in my VB app I would just load the icons from DLL. How can I load the icons provided by .NET
dynamically?

By using System.Drawing.SystemIcons class, for example System.Drawing.SystemIcons.Warning produces an
Icon with a warning sign in it.

When displaying fonts, what's the difference between pixels, points and ems?

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





Dot Net an Overview

1. Introduction

1.1 What is .NET?

That's difficult to sum up in a sentence. According to Microsoft, .NET is a "revolutionary new platform, built on
open Internet protocols and standards, with tools and services that meld computing and communications in new
ways".

A more practical definition would be that .NET is a new environment for developing and running software
applications, featuring ease of development of web-based services, rich standard run-time services available to
components written in a variety of programming languages, and inter-language and inter-machine interoperability.

Note that when the term ".NET" is used in this FAQ it refers only to the new .NET runtime and associated
technologies. This is sometimes called the ".NET Framework". This FAQ does NOT cover any of the various other
existing and new products/technologies that Microsoft are attaching the .NET name to (e.g. SQL Server.NET).

1.2 Does .NET only apply to people building web-sites?

No. If you write any Windows software (using ATL/COM, MFC, VB, or even raw Win32), .NET may offer a viable
alternative (or addition) to the way you do things currently. Of course, if you do develop web sites, then .NET has
lots to interest you - not least ASP.NET.

1.3 When was .NET announced?

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

1.4 When was the first version of .NET released?

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

1.5 What tools can I use to develop .NET applications?

There are a number of tools, described here in ascending order of cost:

.NET Framework SDK: The SDK is free and includes command-line compilers for C++, C#, and VB.NET
and various other utilities to aid development.

ASP.NET Web Matrix: This is a free ASP.NET development environment from Microsoft. As well as a GUI
development environment, the download includes a simple web server that can be used instead of IIS to host
ASP.NET apps. This opens up ASP.NET development to users of Windows XP Home Edition, which cannot run IIS.

Microsoft Visual C# .NET Standard 2003: This is a cheap (around $100) version of Visual Studio limited to
one language and also with limited wizard support. For example, there's no wizard support for class libraries or
custom UI controls. Useful for beginners to learn with, or for savvy developers who can work around the
deficiencies in the supplied wizards. As well as C#, there are VB.NET and C++ versions.

Microsoft Visual Studio.NET Professional 2003: If you have a license for Visual Studio 6.0, you can get the
upgrade. You can also upgrade from VS.NET 2002 for a token $30. Visual Studio.NET includes support for all the
MS languages (C#, C++, VB.NET) and has extensive wizard support.

At the top end of the price spectrum are the Visual Studio.NET 2003 Enterprise and Enterprise Architect editions.
These offer extra features such as Visual Sourcesafe (version control), and performance and analysis tools. Check
out the Visual Studio.NET Feature Comparison at http://msdn.microsoft.com/vstudio/howtobuy/choosing.asp.





1.6 What platforms does the .NET Framework run on?

The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported.
Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on Windows
XP and Windows 2000. Windows 98/ME cannot be used for development.

IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the ASP.NET
Web Matrix web server does run on XP Home.

The Mono project is attempting to implement the .NET framework on Linux.

1.7 What languages does the .NET Framework support?

MS provides compilers for C#, C++, VB and JScript. Other vendors have announced that they intend to develop
.NET compilers for languages such as COBOL, Eiffel, Perl, Smalltalk and Python.

1.8 Will the .NET Framework go through a standardisation process?

From http://msdn.microsoft.com/net/ecma/: "On December 13, 2001, the ECMA General Assembly ratified the C#
and common language infrastructure (CLI) specifications into international standards. The ECMA standards will be
known as ECMA-334 (C#) and ECMA-335 (the CLI)."

2. Basic terminology

2.1 What is the CLR?

CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can
take advantage of, regardless of programming language. Robert Schmidt (Microsoft) lists the following CLR
resources in his MSDN PDC# article:

Object-oriented programming model (inheritance, polymorphism, exception handling, garbage collection)

Security model

Type system

All .NET base classes

Many .NET framework classes

Development, debugging, and profiling tools

Execution and code management

IL-to-native translators and optimizers

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

2.2 What is the CTS?

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

2.3 What is the CLS?



CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to
support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program
written in any language.

In theory this allows very tight interop between different .NET languages - for example allowing a C# class to
inherit from a VB class.

2.4 What is IL?

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

2.5 What is C#?

C# is a new language designed by Microsoft to work with the .NET framework. In their "Introduction to C#"
whitepaper, Microsoft describe C# as follows:

"C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C#
(pronounced C sharp) is firmly planted in the C and C++ family tree of languages, and will immediately be
familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power
of C++."

Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still works pretty well :-).

If you are a C++ programmer, you might like to check out my C# FAQ.

2.6 What does 'managed' mean in the .NET context?

The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly
different things.

Managed code: The .NET framework provides several core run-time services to the programs that run within it -
for example exception handling and security. For these services to work, the code must provide a minimum level
of information to the runtime. Such code is called managed code. All C# and Visual Basic.NET code is managed by
default. VS7 C++ code is not managed by default, but the compiler can produce managed code by specifying a
command-line switch (/com+).

Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and
VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+ switch, but
it can be marked as managed using the __gc keyword.

Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME
C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for
instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a
fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a
benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit
from a VB class. An example of a restriction is that a managed class can only inherit from one base class.

2.7 What is reflection?

All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is
packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a
mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate
the types for a module/assembly.

Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in
COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across
context/process/machine boundaries.



Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create
types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

3. Assemblies

3.1 What is an assembly?

An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry point)
or a library. An assembly consists of one or more files (dlls, exes, html files etc), and represents a group of
resources, type definitions, and implementations of those types. An assembly may also contain references to other
assemblies. These resources, types and references are described in a block of data called a manifest. The manifest
is part of the assembly, thus making the assembly self-describing.

An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the
assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type
called T, and assembly B exports a type called T, the .NET runtime sees these as two completely different types.
Furthermore, don't get confused between assemblies and namespaces - namespaces are merely a hierarchical way
of organising type names. To the runtime, type names are type names, regardless of whether namespaces are
used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to
a namespace) that uniquely indentifies a type to the runtime.

Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at
the assembly boundary.

Finally, assemblies are the unit of versioning in .NET - more on this below.

3.2 How can I produce an assembly?

The simplest way to produce an assembly is directly from a .NET compiler. For example, the following C#
program:

public class CTest

{

public CTest()

{

System.Console.WriteLine( "Hello from CTest" );

}

}

can be compiled into a library assembly (dll) like this:

csc /t:library ctest.cs

You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET
SDK.

Alternatively you can compile your source into modules, and then combine the modules into an assembly using the
assembly linker (al.exe). For the C# compiler, the /target:module switch is used to generate a module instead of
an assembly.

3.3 What is the difference between a private assembly and a shared assembly?

Location and visibility: A private assembly is normally used by a single application, and is stored in the
application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly



cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries
of code which many applications will find useful, e.g. the .NET framework classes.

Versioning: The runtime enforces versioning constraints only on shared assemblies, not on private
assemblies.

3.4 How do assemblies find each other?

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

3.5 How does assembly versioning work?

Each assembly has a version number called the compatibility version. Also each reference to an assembly (from
another assembly) includes both the name and version of the referenced assembly.

The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different
are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies
are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible.
However, this is just the default guideline - it is the version policy that decides to what extent these rules are
enforced. The version policy can be specified via the application configuration file.

Remember: versioning is only applied to shared assemblies, not private assemblies.

4. Application Domains

4.1 What is an Application Domain?

An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process.
The primary purpose of the AppDomain is to isolate an application from other applications.

Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive
and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory
- all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do
not access each other's memory.

4.2 How does an AppDomain get created?

AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you
run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every
application.

AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain,
creates an instance of an object inside it, and then executes one of the object's methods. Note that you must
name the executable 'appdomaintest.exe' for this code to work as-is.

using System;

using System.Runtime.Remoting;



public class CAppDomainInfo : MarshalByRefObject

{

public string GetAppDomainInfo()



{

return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName;

}



}

public class App

{

public static int Main()

{

AppDomain ad = AppDomain.CreateDomain( "Andy's new domain", null, null );

ObjectHandle oh = ad.CreateInstance( "appdomaintest", "CAppDomainInfo" );

CAppDomainInfo adInfo = (CAppDomainInfo)(oh.Unwrap());

string info = adInfo.GetAppDomainInfo();



Console.WriteLine( "AppDomain info: " + info );

return 0;

}

}

4.3 Can I write my own .NET host?

Yes.

5. Garbage Collection

5.1 What is garbage collection?

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

5.2 Is it true that objects don't always get destroyed immediately when the last reference goes away?

Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory
reclaimed.

5.3 Why doesn't the .NET runtime offer deterministic destruction?

Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a
list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during
this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the



runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during
the next sweep of the heap. Furthermore, this type of algorithm works best by performing the garbage collection
sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep.

5.4 Is the lack of deterministic destruction in .NET a problem?

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

5.5 Does non-deterministic destruction affect the usage of COM objects from managed code?

Yes. When using a COM object from managed code, you are effectively relying on the garbage collector to call the
final release on your object. If your COM object holds onto an expensive resource which is only cleaned-up after
the final release, you may need to provide a new interface on your object which supports an explicit Dispose()
method.

5.6 I've heard that Finalize methods should be avoided. Should I implement Finalize on my class?

An object with a Finalize method is more work for the garbage collector than an object without one. Also there are
no guarantees about the order in which objects are Finalized, so there are issues surrounding access to other
objects from the Finalize method. Finally, there is no guarantee that a Finalize method will get called on an object,
so it should never be relied upon to do clean-up of an object's resources.

Microsoft recommend the following pattern:

public class CTest : IDisposable

{

public void Dispose()

{

... // Cleanup activities

GC.SuppressFinalize(this);

}



~CTest() // C# syntax hiding the Finalize() method

{

Dispose();

}

}

In the normal case the client calls Dispose(), the object's resources are freed, and the garbage collector is relieved
of its Finalizing duties by the call to SuppressFinalize(). In the worst case, i.e. the client forgets to call Dispose(),
there is a reasonable chance that the object's resources will eventually get freed by the garbage collector calling
Finalize(). Given the limitations of the garbage collection algorithm this seems like a pretty reasonable approach.



5.7 Do I have any control over the garbage collection algorithm?

A little. For example, the System.GC class exposes a Collect method - this forces the garbage collector to collect
all unreferenced objects immediately.

5.8 How can I find out what the garbage collector is doing?

Lots of interesting statistics are exported from the .NET runtime via the '.NET CLR xxx' performance counters. Use
Performance Monitor to view them.

6. Serialization

6.1 What is serialization?

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

6.2 Does the .NET Framework have in-built support for serialization?

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

6.3 I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or
BinaryFormatter?

It depends. XmlSerializer has severe limitations such as the requirement that the target class has a parameterless
constructor, and only public read/write properties and fields can be serialized. However, on the plus side,
XmlSerializer has good support for customising the XML document that is produced or consumed. XmlSerializer's
features mean that it is most suitable for cross-platform work, or for constructing objects from existing XML
documents.

SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can serialize private fields, for
example. However they both require that the target class be marked with the [Serializable] attribute, so like
XmlSerializer the class needs to be written with serialization in mind. Also there are some quirks to watch out for -
for example on deserialization the constructor of the new object is not invoked.

The choice between SoapFormatter and BinaryFormatter depends on the application. BinaryFormatter makes
sense where both serialization and deserialization will be performed on the .NET platform and where performance
is important. SoapFormatter generally makes more sense in all other cases, for ease of debugging if nothing else.

6.4 Can I customise the serialization process?

Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class.
For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization.
Another example is the [XmlElement] attribute, which can be used to specify the XML element name to be used for
a particular property or field.

Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example,
the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the
serialization process can be acheived by implementing the the ISerializable interface on the class whose instances
are to be serialized.

6.5 Why is XmlSerializer so slow?

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



6.6 Why do I get errors when I try to serialize a Hashtable?

XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable.
SoapFormatter and BinaryFormatter do not have this restriction.

6.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find
out what the problem is?

Look at the InnerException property of the exception that is thrown to get a more specific error message.

7. Attributes

7.1 What are attributes?

There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some
data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other
class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be
attached to a class and means that instances of the class can be serialized.

[serializable] public class CTest {}

The other type of attribute is a context attribute. Context attributes use a similar syntax to metadata attributes
but they are fundamentally different. Context attributes provide an interception mechanism whereby instance
activation and method calls can be pre- and/or post-processed. If you've come across Keith Brown's universal
delegator you'll be familiar with this idea.

7.2 Can I create my own metadata attributes?

Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example:

[AttributeUsage(AttributeTargets.Class)]

public class InspiredByAttribute : System.Attribute

{

public string InspiredBy;



public InspiredByAttribute( string inspiredBy )

{

InspiredBy = inspiredBy;

}

}

[InspiredBy("Andy Mc's brilliant .NET FAQ")]

class CTest

{

}



class CApp

{

public static void Main()

{

object[] atts = typeof(CTest).GetCustomAttributes(true);



foreach( object att in atts )

if( att is InspiredByAttribute )

Console.WriteLine( "Class CTest was inspired by {0}",
((InspiredByAttribute)att).InspiredBy );

}

}

7.3 Can I create my own context attributes?

Yes.

8. Code Access Security

8.1 What is Code Access Security (CAS)?

CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and
what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from
formatting your hard disk.

8.2 How does CAS work?

The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a
member of a particular code group, and each code group is granted the permissions specified in a named
permission set.

For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone -
Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally
the 'Internet' named permission set represents a very restrictive range of permissions.)

8.3 Who defines the CAS code groups?

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

Level = Machine

Code Groups:

1. All code: Nothing

1.1. Zone - MyComputer: FullTrust



1.1.1. Honor SkipVerification requests: SkipVerification

1.2. Zone - Intranet: LocalIntranet

1.3. Zone - Internet: Internet

1.4. Zone - Untrusted: Nothing

1.5. Zone - Trusted: Internet

1.6. StrongName - 0024000004800000940000000602000000240000525341310004000003

000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD06

F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E08

07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5C

AC1DF1734633C602F8F2D5: Everything

Note the hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then sub-
divided into several groups, each of which in turn can be sub-divided. Also note that (somewhat counter-
intuitively) a sub-group can be associated with a more permissive permission set than its parent.

8.4 How do I define my own code group?

Use caspol. For example, suppose you trust code from www.mydomain.com and you want it have full access to
your system, but you want to keep the default restrictions for all other internet sites. To achieve this, you would
add a new code group as a sub-group of the 'Zone - Internet' group, like this:

caspol -ag 1.3 -site www.mydomain.com FullTrust

Now if you run caspol -lg you will see that the new group has been added as group 1.3.1:

...

1.3. Zone - Internet: Internet

1.3.1. Site - www.mydomain.com: FullTrust

...

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

8.5 How do I change the permission set for a code group?

Use caspol. If you are the machine administrator, you can operate at the 'machine' level - which means not only
that the changes you make become the default for the machine, but also that users cannot change the
permissions to be more permissive. If you are a normal (non-admin) user you can still modify the permissions, but
only to make them more restrictive. For example, to allow intranet code to do what it likes you might do this:

caspol -cg 1.2 FullTrust

Note that because this is more permissive than the default policy (on a standard system), you should only do this
at the machine level - doing it at the user level will have no effect.





8.6 Can I create my own permission set?

Yes. Use caspol -ap, specifying an XML file containing the permissions in the permission set. To save you some
time, here is a sample file corresponding to the 'Everything' permission set - just edit to suit your needs. When
you have edited the sample, add it to the range of available permission sets like this:

caspol -ap samplepermset.xml

Then, to apply the permission set to a code group, do something like this:

caspol -cg 1.3 SamplePermSet

(By default, 1.3 is the 'Internet' code group)

8.7 I'm having some trouble with CAS. How can I diagnose my problem?

Caspol has a couple of options that might help. First, you can ask caspol to tell you what code group an assembly
belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a particular assembly
using caspol -rsp.

8.8 I can't be bothered with all this CAS stuff. Can I turn it off?

Yes, as long as you are an administrator. Just run:

caspol -s off

9. Intermediate Language (IL)

9.1 Can I look at the IL for an assembly?

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

9.2 Can source code be reverse-engineered from IL?

Yes, it is often relatively straightforward to regenerate high-level source (e.g. C#) from IL.

9.3 How can I stop my code being reverse-engineered from IL?

There is currently no simple way to stop code being reverse-engineered from IL. In future it is likely that IL
obfuscation tools will become available, either from MS or from third parties. These tools work by 'optimising' the
IL in such a way that reverse-engineering becomes much more difficult.

Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access
to your IL.

9.4 Can I write IL programs directly?

Yes. Peter Drayton posted this simple example to the DOTNET mailing list:

.assembly MyAssembly {}

.class MyApp {

.method static void Main() {

.entrypoint

ldstr "Hello, IL!"



call void System.Console::WriteLine(class System.Object)

ret

}

}

Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.

9.5 Can I do things in IL that I can't do in C#?

Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception,
and you can have non-zero-based arrays.

10. Implications for COM

10.1 Is COM dead?

COM is many things, and it's different things to different people. But to me, COM is fundamentally about how little
blobs of code find other little blobs of code, and how they communicate with each other when they find each other.
COM specifies precisely how this location and communication takes place. In a 'pure' .NET world, consisting
entirely of .NET objects, little blobs of code still find each other and talk to each other, but they don't use COM to
do so. They use a model which is similar to COM in some ways - for example, type information is stored in a
tabular form packaged with the component, which is quite similar to packaging a type library with a COM
component. But it's not COM.

So, does this matter? Well, I don't really care about most of the COM stuff going away - I don't care that finding
components doesn't involve a trip to the registry, or that I don't use IDL to define my interfaces. But there is one
thing that I wouldn't like to go away - I wouldn't like to lose the idea of interface-based development. COM's
greatest strength, in my opinion, is its insistence on a cast-iron separation between interface and implementation.
Unfortunately, the .NET framework seems to make no such insistence - it lets you do interface-based
development, but it doesn't insist. Some people would argue that having a choice can never be a bad thing, and
maybe they're right, but I can't help feeling that maybe it's a backward step.

10.2 Is DCOM dead?

Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on DCOM.
Of course DCOM will still be used in interop scenarios.

10.3 Is MTS/COM+ dead?

No. The approach for the first .NET release is to provide access to the existing COM+ services (through an interop
layer) rather than replace the services with native .NET ones. Various tools and attributes are provided to try to
make this as painless as possible. The PDC release of the .NET SDK includes interop support for core services (JIT
activation, transactions) but not some of the higher level services (e.g. COM+ Events, Queued components).

Over time it is expected that interop will become more seamless - this may mean that some services become a
core part of the CLR, and/or it may mean that some services will be rewritten as managed code which runs on top
of the CLR.

10.4 Can I use COM components from .NET programs?

Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This wrapper
turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation
interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may
be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to .NET-
compatible types.

Here's a simple example for those familiar with ATL. First, create an ATL component which implements the
following IDL:



import "oaidl.idl";

import "ocidl.idl";

[

object,

uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206),

helpstring("ICppName Interface"),

pointer_default(unique),

oleautomation

]

interface ICppName : IUnknown

{

[helpstring("method SetName")] HRESULT SetName([in] BSTR name);

[helpstring("method GetName")] HRESULT GetName([out,retval] BSTR *pName );

};

[

uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D),

version(1.0),

helpstring("cppcomserver 1.0 Type Library")

]

library CPPCOMSERVERLib

{

importlib("stdole32.tlb");

importlib("stdole2.tlb");

[

uuid(600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70),

helpstring("CppName Class")

]

coclass CppName

{



[default] interface ICppName;

};

};

When you've built the component, you should get a typelibrary. Run the TLBIMP utility on the typelibary, like this:

tlbimp cppcomserver.tlb

If successful, you will get a message like this:

Typelib imported successfully to CPPCOMSERVERLib.dll

You now need a .NET client - let's use C#. Create a .cs file containing the following code:

using System;

using CPPCOMSERVERLib;



public class MainApp

{

static public void Main()

{

CppName cppname = new CppName();

cppname.SetName( "bob" );

Console.WriteLine( "Name is " + cppname.GetName() );

}

}

Note that we are using the type library name as a namespace, and the COM class name as the class. Alternatively
we could have used CPPCOMSERVERLib.CppName for the class name and gone without the using
CPPCOMSERVERLib statement.

Compile the C# code like this:

csc /r:cppcomserverlib.dll csharpcomclient.cs

Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using
TLBIMP.

You should now be able to run csharpcomclient.exe, and get the following output on the console:

Name is bob

10.5 Can I use .NET components from COM programs?



Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW (see
previous question), but works in the opposite direction. Again, if the wrapper cannot be automatically generated
by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW can be developed.
Also, for COM to 'see' the .NET component, the .NET component must be registered in the registry.

Here's a simple example. Create a C# file called testcomserver.cs and put the following in it:



using System;



namespace AndyMc

{

[ClassInterface(ClassInterfaceType.AutoDual)]

public class CSharpCOMServer

{

public CSharpCOMServer() {}

public void SetName( string name ) { m_name = name; }

public string GetName() { return m_name; }

private string m_name;

}

}

Then compile the .cs file as follows:

csc /target:library testcomserver.cs

You should get a dll, which you register like this:

regasm testcomserver.dll /tlb:testcomserver.tlb /codebase

Now you need to create a client to test your .NET COM component. VBScript will do - put the following in a file
called comclient.vbs:

Dim dotNetObj

Set dotNetObj = CreateObject("AndyMc.CSharpCOMServer")

dotNetObj.SetName ("bob")

MsgBox "Name is " & dotNetObj.GetName()

and run the script like this:

wscript comclient.vbs



And hey presto you should get a message box displayed with the text "Name is bob".

An alternative to the approach above it to use the dm.net moniker developed by Jason Whittington and Don Box.
Go to http://staff.develop.com/jasonw/clr/readme.htm to check it out.

10.6 Is ATL redundant in the .NET world?

Yes, if you are writing applications that live inside the .NET framework. Of course many developers may wish to
continue using ATL to write C++ COM components that live outside the framework, but if you are inside you will
almost certainly want to use C#. Raw C++ (and therefore ATL which is based on it) doesn't have much of a place
in the .NET world - it's just too near the metal and provides too much flexibility for the runtime to be able to
manage it.

11. Miscellaneous

11.1 How does .NET remoting work?

.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is
intended for LANs only - HTTP can be used for LANs or WANs (internet).

Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By
default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel
uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization
format.

There are a number of styles of remote access:

SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown away
when the request has finished.

Singleton. All incoming requests from clients are processed by a single server object.

Client-activated object. This is the old stateful (D)COM model whereby the client receives a reference to
the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it.

Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a
lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure.
Objects have a default renew time - the lease is renewed when a successful call is made from the client to the
object. The client can also explicitly renew the lease.

If you're interested in using XML-RPC as an alternative to SOAP, take a look at Charles Cook's XML-RPC.Net site at
http://www.cookcomputing.com/xmlrpc/xmlrpc.shtml.

11.2 How can I get at the Win32 API from a .NET program?

Use P/Invoke. This uses similar technology to COM Interop, but is used to access static DLL entry points instead of
COM objects. Here is an example of C# calling the Win32 MessageBox function:

using System;

using System.Runtime.InteropServices;



class MainApp

{

[DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true, CharSet=CharSet.Auto)]



public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType);



public static void Main()

{

MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 );

}

}

12. Class Library

12.1 File I/O

12.1.1 How do I read from a text file?

First, use a System.IO.FileStream object to open the file:

FileStream fs = new FileStream( @"c:\test.txt", FileMode.Open, FileAccess.Read );

FileStream inherits from Stream, so you can wrap the FileStream object with a StreamReader object. This provides
a nice interface for processing the stream line by line:

StreamReader sr = new StreamReader( fs );

string curLine;

while( (curLine = sr.ReadLine()) != null )

Console.WriteLine( curLine );

Finally close the StreamReader object:

sr.Close();

Note that this will automatically call Close() on the underlying Stream object, so an explicit fs.Close() is not
required.

12.1.2 How do I write to a text file?

Similar to the read example, except use StreamWriter instead of StreamReader.

12.1.3 How do I read/write binary files?

Similar to text files, except wrap the FileStream object with a BinaryReader/Writer object instead of a
StreamReader/Writer object.

12.2 Text Processing

12.2.1 Are regular expressions supported?

Yes. Use the System.Text.RegularExpressions.Regex class. For example, the following code updates the title in an
HTML file:



FileStream fs = new FileStream( "test.htm", FileMode.Open, FileAccess.Read );

StreamReader sr = new StreamReader( fs );

Regex r = new Regex( "(.*)" );

string s;

while( (s = sr.ReadLine()) != null )

{

if( r.IsMatch( s ) )

s = r.Replace( s, "New and improved ${1}" );

Console.WriteLine( s );

}

12.3 Internet

12.3.1 How do I download a web page?

First use the System.Net.WebRequestFactory class to acquire a WebRequest object:

WebRequest request = WebRequest.Create( "http://localhost" );

Then ask for the response from the request:

WebResponse response = request.GetResponse();

The GetResponse method blocks until the download is complete. Then you can access the response stream like
this:

Stream s = response.GetResponseStream();

// Output the downloaded stream to the console

StreamReader sr = new StreamReader( s );

string line;

while( (line = sr.ReadLine()) != null )

Console.WriteLine( line );

Note that WebRequest and WebReponse objects can be downcast to HttpWebRequest and HttpWebReponse
objects respectively, to access http-specific functionality.

12.3.2 How do I use a proxy?

Two approaches - to affect all web requests do this:

System.Net.GlobalProxySelection.Select = new WebProxy( "proxyname", 80 );

Alternatively, to set the proxy for a specific web request, do this:



HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://localhost" );

request.Proxy = new WebProxy( "proxyname", 80 );

12.4 XML

12.4.1 Is DOM supported?

Yes. Take this example XML document:



Fred

Bill



This document can be parsed as follows:

XmlDocument doc = new XmlDocument();

doc.Load( "test.xml" );



XmlNode root = doc.DocumentElement;



foreach( XmlNode personElement in root.ChildNodes )

Console.WriteLine( personElement.FirstChild.Value.ToString() );

The output is:

Fred

Bill

12.4.2 Is SAX supported?

No. Instead, a new XmlReader/XmlWriter API is offered. Like SAX it is stream-based but it uses a 'pull' model
rather than SAX's 'push' model. Here's an example:

XmlTextReader reader = new XmlTextReader( "test.xml" );

while( reader.Read() )

{

if( reader.NodeType == XmlNodeType.Element && reader.Name == "PERSON" )

{

reader.Read(); // Skip to the child text



Console.WriteLine( reader.Value );

}

}

12.4.3 Is XPath supported?

Yes, via the XPathXXX classes:

XPathDocument xpdoc = new XPathDocument("test.xml");

XPathNavigator nav = xpdoc.CreateNavigator();

XPathExpression expr = nav.Compile("descendant::PEOPLE/PERSON");

XPathNodeIterator iterator = nav.Select(expr);

while (iterator.MoveNext())

Console.WriteLine(iterator.Current);

12.5 Threading

12.5.1 Is multi-threading supported?

Yes, there is extensive support for multi-threading. New threads can be spawned, and there is a system-provided
threadpool which applications can use.

12.5.2 How do I spawn a thread?

Create an instance of a System.Threading.Thread object, passing it an instance of a ThreadStart delegate that will
be executed on the new thread. For example:

class MyThread

{

public MyThread( string initData )

{

m_data = initData;

m_thread = new Thread( new ThreadStart(ThreadMain) );

m_thread.Start();

}

// ThreadMain() is executed on the new thread.

private void ThreadMain()

{

Console.WriteLine( m_data );



}



public void WaitUntilFinished()

{

m_thread.Join();

}

private Thread m_thread;

private string m_data;

}

In this case creating an instance of the MyThread class is sufficient to spawn the thread and execute the
MyThread.ThreadMain() method:

MyThread t = new MyThread( "Hello, world." );

t.WaitUntilFinished();

12.5.3 How do I stop a thread?

There are several options. First, you can use your own communication mechanism to tell the ThreadStart method
to finish. Alternatively the Thread class has in-built support for instructing the thread to stop. The two principle
methods are Thread.Interrupt() and Thread.Abort(). The former will cause a ThreadInterruptedException to be
thrown on the thread when it next goes into a WaitJoinSleep state. In other words, Thread.Interrupt is a polite
way of asking the thread to stop when it is no longer doing any useful work. In contrast, Thread.Abort() throws a
ThreadAbortException regardless of what the thread is doing. Furthermore, the ThreadAbortException cannot
normally be caught (though the ThreadStart's finally method will be executed). Thread.Abort() is a heavy-handed
mechanism which should not normally be required.

12.5.4 How do I use the thread pool?

By passing an instance of a WaitCallback delegate to the ThreadPool.QueueUserWorkItem() method:

class CApp

{

static void Main()

{

string s = "Hello, World";

ThreadPool.QueueUserWorkItem( new WaitCallback( DoWork ), s );



Thread.Sleep( 1000 ); // Give time for work item to be executed

}





// DoWork is executed on a thread from the thread pool.

static void DoWork( object state )

{

Console.WriteLine( state );

}

}

12.5.5 How do I know when my thread pool work item has completed?

There is no way to query the thread pool for this information. You must put code into the WaitCallback method to
signal that it has completed. Events are useful for this.

12.5.6 How do I prevent concurrent access to my data?

Each object has a concurrency lock (critical section) associated with it. The System.Threading.Monitor.Enter/Exit
methods are used to acquire and release this lock. For example, instances of the following class only allow one
thread at a time to enter method f():

class C

{

public void f()

{

try

{

Monitor.Enter(this);

...

}

finally

{

Monitor.Exit(this);

}

}

}

C# has a 'lock' keyword which provides a convenient shorthand for the code above:



class C

{

public void f()

{

lock(this)

{

...

}

}

}

Note that calling Monitor.Enter(myObject) does NOT mean that all access to myObject is serialized. It means that
the synchronisation lock associated with myObject has been acquired, and no other thread can acquire that lock
until Monitor.Exit(o) is called. In other words, this class is functionally equivalent to the classes above:

class C

{

public void f()

{

lock( m_object )

{

...

}

}



private m_object = new object();

}

12.6 Tracing

12.6.1 Is there built-in support for tracing/logging?

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



12.6.2 Can I redirect tracing to a file?

Yes. The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the
tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection
contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32
OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when
debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more
appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose.

Here's how to use the TextWriterTraceListener class to redirect Trace output to a file:

Trace.Listeners.Clear();

FileStream fs = new FileStream( @"c:\log.txt", FileMode.Create, FileAccess.Write );

Trace.Listeners.Add( new TextWriterTraceListener( fs ) );

Trace.WriteLine( @"This will be writen to c:\log.txt!" );

Trace.Flush();

Note the use of Trace.Listeners.Clear() to remove the default listener. If you don't do this, the output will go to the
file and OutputDebugString(). Typically this is not what you want, because OutputDebugString() imposes a big
performance hit.

12.6.3 Can I customise the trace output?

Yes. You can write your own TraceListener-derived class, and direct all output through it. Here's a simple example,
which derives from TextWriterTraceListener (and therefore has in-built support for writing to files, as shown
above) and adds timing information and the thread ID for each trace line:

class MyListener : TextWriterTraceListener

{

public MyListener( Stream s ) : base(s)

{

}



public override void WriteLine( string s )

{

Writer.WriteLine( "{0:D8} [{1:D4}] {2}",

Environment.TickCount - m_startTickCount,

AppDomain.GetCurrentThreadId(),

s );

}





protected int m_startTickCount = Environment.TickCount;

}

(Note that this implementation is not complete - the TraceListener.Write method is not overridden for example.)

The beauty of this approach is that when an instance of MyListener is added to the Trace.Listeners collection, all
calls to Trace.WriteLine() go through MyListener, including calls made by referenced assemblies that know nothing
about the MyListener class.

SQL

1. Whats the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary
key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another
major difference is that, primary key doesnt allow NULLs, but unique key allows one NULL only.

2. Write a SQL Query to find first Week Day of month?

SELECT DATENAME(dw, DATEADD(dd, - DATEPART(dd, GETDATE()) + 1, GETDATE())) AS FirstDay

3. How to find 6th highest salary from Employee table

SELECT TOP 1 salary FROM (SELECT DISTINCT TOP 6 salary FROM employee

ORDER BY salary DESC) a ORDER BY salary

4. What is a join and List different types of joins.

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table
depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs
are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

5. How can I enforce to use particular index?

You can use index hint (index=index_name) after the table name. SELECT au_lname FROM authors
(index=aunmind)

6. What is sorting and what is the difference between sorting and clustered indexes?

The ORDER BY clause sorts query results by one or more columns up to 8,060 bytes. This will happen by the time
when we retrieve data from database. Clustered indexes physically sorting data, while inserting/updating the
table.

7. What are the differences between UNION and JOINS?

A join selects columns from 2 or more tables. A union selects rows.

8. What is the Referential Integrity?

Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e.
every foreign key value must have a corresponding primary key value

9. What is the row size in SQL Server 2000?

8060 bytes.





10. How to determine the service pack currently installed on SQL Server?

The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service
pack installed. eg: Microsoft SQL Server 2000 - 8.00.760 (Intel X86) Dec 17 2002 14:22:05 Copyright (c) 1988-
2003 Microsoft Corporation Enterprise Edition on Windows NT 5.0 (Build 2195: Service Pack 3)

11. What is the purpose of UPDATE STATISTICS?

Updates information about the distribution of key values for one or more statistics groups (collections) in the
specified table or indexed view.

12. What is the use of SCOPE_IDENTITY() function?

Returns the most recently created identity value for the tables in the current execution scope.

13. What are the different ways of moving data/databases between servers and databases in SQL
Server?

There are lots of options available, you have to choose your option depending upon your requirements. Some of
the options you have are: BACKUP/RESTORE, detaching and attaching databases, replication, DTS, BCP,
logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

14. How do you transfer data from text file to database (other than DTS)?

Using the BCP (Bulk Copy Program) utility.

15. What's the difference between DELETE TABLE and TRUNCATE TABLE commands?

DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it
slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs
the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled
back.

16. What is a deadlock?

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.

17. What is a LiveLock?

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.

18. How to restart SQL Server in single user mode?

From Startup Options :- Go to SQL Server Properties by right-clicking on the Server name in the Enterprise
manager. Under the 'General' tab, click on 'Startup Parameters'. Enter a value of -m in the Parameter.

19. Does SQL Server 2000 clustering support load balancing?

SQL Server 2000 clustering does not provide load balancing; it provides failover support. To achieve load
balancing, you need software that balances the load between clusters, not between servers within a cluster.

20. What is DTC?



The Microsoft Distributed Transaction Coordinator (MS DTC) is a transaction manager that allows client
applications to include several different sources of data in one transaction. MS DTC coordinates committing the
distributed transaction across all the servers enlisted in the transaction.

21. What is DTS?

Microsoft SQL Server 2000 Data Transformation Services (DTS) is a set of graphical tools and programmable
objects that lets you extract, transform, and consolidate data from disparate sources into single or multiple
destinations.

22. What are defaults? Is there a column to which a default can't be bound?

A default is a value that will be used by a column, if no value is supplied to that column while inserting data.
IDENTITY columns and timestamp columns can't have defaults bound to them.

23. What are the constraints ?

Table Constraints define rules regarding the values allowed in columns and are the standard mechanism for
enforcing integrity. SQL Server 2000 supports five classes of constraints. NOT NULL , CHECK, UNIQUE, PRIMARY
KEY, FOREIGN KEY.

24. What is Transaction?

A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must
exhibit four properties, called the ACID (Atomicity, Consistency, Isolation, and Durability) properties, to qualify as
a transaction.

25. What is Isolation Level?

An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL
Server isolation level is Read Committed. A lower isolation level increases concurrency, but at the expense of data
correctness. Conversely, a higher isolation level ensures that data is correct, but can affect concurrency
negatively. The isolation level required by an application determines the locking behavior SQL Server uses. SQL-92
defines the following isolation levels, all of which are supported by SQL Server:

Read uncommitted (the lowest level where transactions are isolated only enough to ensure that physically corrupt
data is not read).

Read committed (SQL Server default level).

Repeatable read.

Serializable (the highest level, where transactions are completely isolated from one another).

26. What is denormalization and when would you go for it?

As the name indicates, denormalization is the reverse process of normalization. It's the controlled introduction of
redundancy in to the database design. It helps improve the query performance as the number of joins could be
reduced.

27. How do you implement one-to-one, one-to-many and many-to-many relationships while designing
tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign
key relationships.

One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key
relationships.



Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the
composite primary key of the junction table.

It will be a good idea to read up a database designing fundamentals text book.

28. What's the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary
key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another
major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

29. What are user defined datatypes and when you should go for them?

User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format
to the database. Take for example, in your database, there is a column called Flight_Num which appears in many
tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called
Flight_num_type of varchar(8) and use it across all your tables.

See sp_addtype, sp_droptype in books online.

30. What is bit datatype and what's the information that can be stored inside a bit column?

Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype
could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can
represent a third state, which is NULL.

31. Define candidate key, alternate key, composite key.

A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the
primary key of the table. If the table has more than one candidate key, one of them will become the primary key,
and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

32. What are defaults? Is there a column to which a default can't be bound?

A default is a value that will be used by a column, if no value is supplied to that column while inserting data.
IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE DEFUALT in books
online.

33. What is a transaction and what are ACID properties?

A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for
Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and
explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book.

34. Explain different isolation levels

An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL
Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation):
Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an
explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you
customize the isolation level at the connection level.

35. CREATE INDEX myIndex ON myTable(myColumn)

What type of Index will get created after executing the above statement?

Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless
specified otherwise.



36. What's the maximum size of a row?

8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'. Check out
SQL Server books online for the page titled: "Maximum Capacity Specifications".

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

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

39. What is lock escalation?

Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level
locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being
occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer
coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards
it's dynamically managed by SQL Server.

40. Whats the difference between DELETE TABLE and TRUNCATE TABLE commands?

DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it
slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs
the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled
back.

41. What are constraints? Explain different types of constraints.

Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create
triggers, rule or defaults.

Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

For an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE TABLE",
"ALTER TABLE"

42. 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?

Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered index on a
table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one
clustered index per table. Non-clustered indexes have their own storage separate from the table data storage.
Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having
the index key and it's row locater. The row located could be the RID or the Clustered index key, depending up on
the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query optimizer can
choose from all the existing indexes to come up with an efficient execution plan. At the same t ime, data
modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the
table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more
indexes you have, more disk space is used.



43. What is RAID and what are different types of RAID configurations?

RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. There
are six RAID levels 0 through 5 offering different levels of performance, fault tolerance. MSDN has some
information about RAID levels and for detailed information, check out the RAID advisory board's homepage

44. What are the steps you will take to improve performance of a poor performing query?

This is a very open ended question and there could be a lot of reasons behind the poor performance of a query.
But some general issues that you could talk about would be: No indexes, table scans, missing or out of date
statistics, blocking, excess recompilations of stored procedures, procedures and triggers without SET NOCOUNT
ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors
and temporary tables.

Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL ON, SET
SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor,
Graphical execution plan in Query Analyzer.

45. What are the steps you will take, if you are tasked with securing an SQL Server?

Again this is another open ended question. Here are some things you could talk about: Preferring NT
authentication, using server, databse and application roles to control access to the data, securing the physical
database files using NTFS permissions, using an unguessable SA password, restricting physical access to the SQL
Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling
auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web
server etc.

46. What is a deadlock and what is a live lock? How will you go about resolving deadlocks?

Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on
the other's piece. Each process would wait indefinitely for the other to release the lock, unless one of the user
processes is terminated. SQL Server detects deadlocks and terminates one user's process.

A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping
shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks.
A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait
indefinitely.

Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also check out the
article Q169960 from Microsoft knowledge base.

47. What is blocking and how would you troubleshoot it?

Blocking happens when one connection from an application holds a lock and a second connection requires a
conflicting lock type. This forces the second connection to wait, blocked on the first.

Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding efficient
transactions.

48. Explain CREATE DATABASE syntax

Many of us are used to craeting databases from the Enterprise Manager or by just issuing the command: CREATE
DATABAE MyDB. But what if you have to create a database with two filegroups, one on drive C and the other on
drive D with log on drive E with an initial size of 600 MB and with a growth factor of 15%? That's why being a DBA
you should be familiar with the CREATE DATABASE syntax. Check out SQL Server books online for more
information.







49. How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration
mode?

SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very important
parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user mode and -
f is used to start the SQL Server in minimal confuguration mode. Check out SQL Server books online for more
parameters and their explanations.

50. What are statistics, under what circumstances they go out of date, how do you update them?

Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of
that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in
determining whether to choose an index or not while executing a query.

Some situations under which you should update statistics:

1) If there is significant change in the key values in the index

2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the
distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement
and then repopulated

3) Database is upgraded from a previous version

Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE, DBCC
SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats, sp_updatestats

51. What are the different ways of moving data/databases between servers and databases in SQL
Server?

There are lots of options available, you have to choose your option depending upon your requirements. Some of
the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP,
logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

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

53. What is database replicaion? What are the different types of replication you can set up in SQL
Server?

Replication is the process of copying/moving data between databases on the same or different servers. SQL Server
supports the following types of replication scenarios:

Snapshot replication ,Transactional replication (with immediate updating subscribers, with queued updating
subscribers) ,Merge replication

54. How to determine the service pack currently installed on SQL Server?

The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service
pack installed. To know more about this process visit SQL Server service packs and versions.

55. What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How
can you avoid cursors?

Cursors allow row-by-row prcessing of the resultsets.



Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a
normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because
they require more resources and temporary storage (results in more IO operations). Furthere, there are
restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike

Salary between 40000 and 55000 -- 7000 hike

Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his salary
according to the above formula. But the same can be achieved by multiple update statements or can be combined
in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =

CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000

WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000

WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000

END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a
particular row meets certain condition. You don't have to use cursors for this. This can be achieved using WHILE
loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row
processing, check out the 'My code library' section of my site or search for WHILE.

56. 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] ]

57. What is a join and explain different types of joins.

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table
depending upon data from another table.



Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER
JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

58. Can you have a nested transaction?

Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

59. What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?

An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using
Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures
using the EXEC statement. See books online to learn how to create extended stored procedures and how to add
them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate
stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy.
For an example of creating a COM object in VB and calling it from T-SQL, see 'My code library' section of this site.

60. What is the system function to get the current user's user id?

USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER,
CURRENT_USER, USER, SUSER_SID(), HOST_NAME().

61. What are triggers? How many triggers you can have on a table? How to invoke a trigger on
demand?

Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or
DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE.
From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But
in 7.0 there's no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which
trigger fires first or fires last using sp_settriggerorder

Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE,
DELETE) happens on the table on which they are defined. Triggers are generally used to implement business rules,
auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use
constraints for this purpose, instead of triggers, as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called
post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000 books online for
INSTEAD OF triggers.

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

63. What is a self join? Explain it with an example.

Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is
an example: Employees table which contains rows for normal employees as well as managers. So, to find out the
managers of all the employees, you need a self join.

CREATE TABLE emp



(

empid int,

mgrid int,

empname char(10)

)

INSERT emp SELECT 1,2,'Vyas'

INSERT emp SELECT 2,3,'Mohan'

INSERT emp SELECT 3,NULL,'Shobha'

INSERT emp SELECT 4,2,'Shridhar'

INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]

FROM emp t1, emp t2 WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super
bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]

FROM emp t1

LEFT OUTER JOIN

emp t2

ON

t1.mgrid = t2.empid

64. Why are my insert, update statements failing with the following error?

Server: Msg 8152, Level 16, State 9, Line 1

String or binary data would be truncated.

The statement has been terminated. This error occurs, when the length of the value entered by you into a char,
varchar, nchar, nvarchar column is longer than the maximum length of the column. For example, inserting 'FAQ'
into a char(2) column would result in this error.

Profiler is handy in troubleshooting this error. If data truncation is okay with you and you don't want to see this
error, then turn off ANSI WARNINGS by using the following SET command: SET ANSI_WARNINGS OFF.

Steps to reproduce the problem:

CREATE TABLE MyTable(Pkey int PRIMARY KEY, Col1 char(10))

GO



INSERT INTO MyTable (Pkey, Col1) VALUES (1, 'SQL Server Clustering FAQ')

GO

Make sure, you restrict the length of input, in your front-end applications. For example, you could use the
MAXLENGTH property of the text boxes in HTML forms. E.g:



65. What is the T-SQL equivalent of IIF (immediate if/ternary operator) function of other
programming languages?

CASE is the equivalent of IIF function. See SQL Server Books Online for more information. Here's a quick example:

CREATE TABLE People

(

[ID] int PRIMARY KEY,

[Name] varchar(25) NOT NULL,

Sex bit NULL

)

INSERT INTO People ([ID],[Name], Sex) VALUES (1,'John Dykes', 1)

INSERT INTO People ([ID],[Name], Sex) VALUES (2,'Deborah Crook', 0)

INSERT INTO People ([ID],[Name], Sex) VALUES (3,'P S Subramanyam', NULL)

SELECT [ID], [Name],

CASE Sex

WHEN 1

THEN 'Male'

WHEN 0

THEN 'Female'

ELSE 'Not specified'

END AS Sex

FROM People

66. How to programmatically find out when the SQL Server service started?

Everytime SQL Server starts, it recreates the tempdb database. So, the creation date and time of the tempdb
database tells us the date and time at which SQL Server service started. This information is stored in the crdate
column of the sysdatabases table in master database. Here's the query to find that out:

SELECT crdate AS 'SQL Server service started approximately at:'



FROM master.dbo.sysdatabases

WHERE name = 'tempdb'

SQL Server error log also has this information (This is more accurate) and the error log can be queried using
xp_readerrorlog

67. How to get rid of the time part from the date returned by GETDATE function?

We have to use the CONVERT function to strip the time off the date. Any of the following commands will do this:

SELECT CONVERT(char,GETDATE(),101)

SELECT CONVERT(char,GETDATE(),102)

SELECT CONVERT(char,GETDATE(),103)

SELECT CONVERT(char,GETDATE(),1)

68. How to upload images or binary files into SQL Server tables?

First of all, if possible, try not to stored images and other binary files in the SQL Server tables, as they slow things
down. Instead, store a link (file path) to the file in the tables and let your applications directly access the files. But
if you must store these files within SQL Server, use the text/ntext or image datatype columns and consider the
following options:

SQL Server 7.0 and 2000 come with a utility called textcopy.exe. You can locate this file in the Binn folder under
your SQL Server installation folder. Run this file from command prompt, and it will prompt you for required input

Use the GetChunk and AppendChunk methods of ADO Field object. MSDN has examples

Use the ADO Stream object

Use the Bulk Insert Image utility (BII) that ships with SQL Server 2000

69. How to run an SQL script file that is located on the disk, using T-SQL?

There's no direct command to read a script file and execute it. But the isql.exe and osql.exe come in handy when
you have to execute a script file from within T-SQL. Just call any of these exes using xp_cmdshell and pass the
script file name as parameter to it. See SQL Server Books Online for more information about the input parameters
of these exes. Here are some quick examples:

EXEC master..xp_cmdshell 'osql -Svaio -Usa -Pzaassds1 -ic:\MySQl.sql -n'

EXEC master..xp_cmdshell 'isql -Svaio -Usa -Pzaassds1 -ic:\MySQl.sql -n'

70. How to get the complete error message from T-SQL while error handling?

Unfortunately, the error handling capabilities of SQL Server are limited. When an error occurs, all you can get is
the error number, using the @@ERROR global variable. There is no @@ERROR_MESSAGE global variable to get
the error description.



For a complete error message, you can always query the master..sysmessages table using the error number, but
most of these messages have place holders (like %s, %l etc.), and hence we can't get the complete error
message.



However, the client applications using an object model such as RDO, ADO have access to the complete error
message.

71. How to get the first day of the week, last day of the week and last day of the month using T-SQL
date functions?

DECLARE @Date datetime

SET @Date = '2001/08/31'

SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 1),@Date) AS 'First day of the week'

SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 7),@Date) AS 'Last day of the week'

SELECT DAY(DATEADD(d, -DAY(DATEADD(m,1,@Date)),DATEADD(m,1,@Date))) AS 'Last day of the month'

72. How to pass a table name, column name etc. to the stored procedure so that I can dynamically
select from a table?

Basically, SELECT and other commands like DROP TABLE won't let you use a variable instead of a hardcoded table
name. To overcome this problem, you have to use dynamic sql. But dynamic SQL has some disadvantages. It's
slow, as the dynamic SQL statement needs to be parsed everytime it's executed. Further, the user who is
executing the dynamic SQL string needs direct permissions on the tables, which defeats the purpose of having
stored procedures to mask the underlying tables. Having said that, here are some examples of dynamic SQL: (Also
see sp_executesql in SQL Server Books Online)

CREATE PROC DropTable

@Table sysname

AS

EXEC ('DROP TABLE ' + @Table)

GO



EXEC DropTable 'MyTable'

GO

CREATE PROC SelectTable

@Table sysname

AS

EXEC ('SELECT * FROM ' + @Table)

GO

EXEC SelectTable 'MyTable'

73. Error inside a stored procedure is not being raised to my front-end applications using ADO. But I
get the error when I run the procedure from Query Analyzer

This typically happens when your stored procedure is returning multiple resultsets and the offending SQL
statement is executed after returning one or more resultsets. ADO will not return an error untill it processes all the



recordsets returned before the offending SQL statement got executed. So, to get to the error message returned by
your procedure. You have to loop through all the recordsets returned. ADO Recordset object has a method called
NextRecordset, which lets you loop through the recordsets.

Having SET NOCOUNT ON at the beginning of the procedure also helps avoid this problem. SET NOCOUNT ON also
helps in improving the stored procedure performance. Here's a sample procedure to simulate the problem:

CREATE PROC TestProc

AS

SELECT MAX(Col1) FROM TestTable

SELECT MIN(Col1) FROM TestTable

INSERT INTO TestTable (Col1, Col2) VALUES (1,'Oracle and SQL Server comparison')

INSERT INTO TestTable (Col1, Col2) VALUES (1,'How to configure SQL Server?') -- Dupplicate key error occurs

GO

74. How to suppress error messages in stored procedures/triggers etc. using T-SQL?

It's not possible to suppress error messages from within T-SQL. Error messages are always returned to the client.
If you don't want your users to see these raw error messages, you should handle them in your front-end
applications. For example, if you are using ADO from ASP to connect to SQL Server, you would do something like
the following:

On Error Resume Next

Set Rs = Conn.Execute ("INSERT INTO MyTable (1,'How to migrate from Oracle to SQL Server','Book'")

If Err.Number <> 0 Then Response.Write ("Error occurred while inserting new data")

On Error GoTo 0

75. How to save the output of a query/stored procedure to a text file using T-SQL?

T-SQL by itself has no support for saving the output of queries/stored procedures to text files. But you could
achieve this using the command line utilities like isql.exe and osql.exe. You could either invoke these exe files
directly from command prompt/batch files or from T-SQL using the xp_cmdshell command. Here are the
examples:

From command prompt:

osql.exe -S YourServerName -U sa -P secretcode -Q "EXEC sp_who2" -o "E:\output.txt"

From T-SQL:

EXEC master..xp_cmdshell 'osql.exe -S YourServerName -U sa -P secretcode -Q "EXEC sp_who2" -o
"E:\output.txt"'

Query Analyzer lets you save the query output to text files manually. The output of stored procedures that are run
as a part of a scheduled job, can also be saved to a text file.

BCP and Data Transformation Services (DTS) let you export table data to text files.





76. How to join tables from different databases?

You just have to qualify the table names in your SELECT queries with database name, followed by table owner
name. In the following example, Table1 from pubs database and Table2 from northwind database are being joined
on the column i. Both tables are owned by dbo.

SELECT a.i, a.j

FROM pubs.dbo.Table1 a

INNER JOIN

northwind.dbo.Table2 b

ON a.i = b.i

GO

77. How to join tables from different servers?

To be able to join tables between two SQL Servers, first you have to link them. After the linked servers are setup,
you just have to prefix your tables names with server name, database name, table owner name in your SELECT
queries. The following example links SERVER_01 to SERVER_02. Execute the following commands in SERVER_02:

EXEC sp_addlinkedserver SERVER_01

GO

/* The following command links 'sa' login on SERVER_02 with the 'sa' login of SERVER_01 */

EXEC sp_addlinkedsrvlogin @rmtsrvname = 'SERVER_01', @useself = 'false', @locallogin = 'sa', @rmtuser = 'sa',
@rmtpassword = 'sa password of SERVER_01'

GO

SELECT a.title_id

FROM SERVER_01.pubs.dbo.titles a

INNER JOIN SERVER_02.pubs.dbo.titles b

ON a.title_id = b.title_id

GO

78. How to convert timestamp data to date data (datetime datatype)?

The name timestamp is a little misleading. Timestamp data has nothing to do with dates and times and can not be
converted to date data. A timestamp is a unique number within the database and is equivalent to a
binary(8)/varbinary(8) datatype. A table can have only one timestamp column. Timestamp value of a row changes
with every update of the row. To avoid the confusion, SQL Server 2000 introduced a synonym to timestamp, called
rowversion.



79. Can I invoke/instantiate COM objects from within stored procedures or triggers using T-SQL?



Yes. SQL Server provides system stored procedures that let you instantiate COM objects using T-SQL from stored
procedures, triggers and SQL batches. Search SQL Server Books Online for sp_OACreate and sp_OA* for
documentation and examples. Also check out my code library for an example.

80. Oracle has a rownum to access rows of a table using row number or row id. Is there any equivalent
for that in SQL Server? Or how to generate output with row number in SQL Server?

There is no direct equivalent to Oracle's rownum or row id in SQL Server. Strictly speaking, in a relational
database, rows within a table are not ordered and a row id won't really make sense. But if you need that
functionality, consider the following three alternatives:

Add an IDENTITY column to your table. See Books Online for more information

Use the following query to generate a row number for each row. The following query generates a row number for
each row in the authors table of pubs database. For this query to work, the table must have a unique key.

SELECT (SELECT COUNT(i.au_id)

FROM pubs..authors i

WHERE i.au_id >= o.au_id ) AS RowID,

au_fname + ' ' + au_lname AS 'Author name'

FROM pubs..authors o

ORDER BY RowID

Use a temporary table approach, to store the entire resultset into a temporary table, along with a row id generated
by the IDENTITY() function. Creating a temporary table will be costly, especially when you are working with large
tables. Go for this approach, if you don't have a unique key in your table. Search for IDENTITY (Function) in SQL
Server Books Online.

81. How to specify a network library like TCP/IP using ADO connect string?

To specify TCP/IP net library, append the following to your ADO connect string:

Network=dbmssocn

For more information on specifying other net libraries in ADO connect strings, click here to read the article from
Microsoft Knowledgebase.

82. Is there a way to find out when a stored procedure was last updated?

Simple answer is 'No'. The crdate column in the sysobjects table always contains the stored procedure create date,
not the last updated date. You can use Profiler to trace ALTER PROC calls to the database, but you can't really
afford to run a trace for ever, as it's resource intensive. Here is a simple idea! Whenever you have to alter your
stored procedure, first drop it, then recreate it with the updated code. This resets the crdate column of sysobjects
table. If you can make sure your developers always follow this plan, then the crdate column of sysobjects will
always reflect the last updated date of the stored procedure. For example, if I have to modify a procedure named
MyProc, instead of doing "ALTER PROC MyProc", here's what I would do:

- Use sp_helptext to get the current code of MyProc.

- Change the code as needed.

- Run the following code to drop the existing version of MyProc:

IF EXISTS(SELECT 1 FROM sysobjects WHERE name = 'MyProc' AND type = 'P' AND USER_NAME(uid) = 'dbo')



BEGIN

DROP PROC dbo.MyProc

END

- Run the updated code to recreate MyProc

83. As a part of your job, what are the DBCC commands that you commonly use for database
maintenance?

DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTIG, DBCC
SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful
for DBAs. Check out SQL Server books online for more information.





Available Academic Dot Net Projects & also real time application.




No comments: