Sie sind auf Seite 1von 99

The IHttpHandler and IHttpHandlerFactory interfaces ?

The IHttpHandler interface is implemented by all the handlers. The interface consists of one property
called IsReusable. The IsReusable property gets a value indicating whether another request can use the
IHttpHandler instance. The method ProcessRequest() allows you to process the current request. This is
the core place where all your code goes. This method receives a parameter of type HttpContext using
which you can access the intrinsic objects such as Request and Response. The IHttpHandlerFactory
interface consists of two methods - GetHandler and ReleaseHandler. The GetHandler() method
instantiates the required HTTP handler based on some condition and returns it back to ASP.NET. The
ReleaseHandler() method allows the factory to reuse an existing handler.
Does .NET CLR and SQL SERVER run in different process?
Dot Net CLR and all .net realtes application and Sql Server run in same process or we can say that that
on the same address because there is no issue of speed because if these two process are run in different
process then there may be a speed issue created one process goes fast and other slow may create the
problem.
What do you mean by three-tier architecture?
The three-tier architecture was comes into existence to improve management of code and contents and
to improve the performance of the web based applications. There are mainly three layers in three-tier
architecture. the are define as follows
(1)Presentation
(2)Business Logic
(3)Database

(1)First layer Presentation contains mainly the interface code, and this is shown to user. This code could
contain any technology that can be used on the client side like HTML, JavaScript or VBScript etc.

(2)Second layer is Business Logic which contains all the code of the server-side .This layer have code to
interact with database and to query, manipulate, pass data to user interface and handle any input from
the UI as well.

(3)Third layer Data represents the data store like MS Access, SQL Server, an XML file, an Excel file or
even a text file containing data also some additional database are also added to that layers.

When not to use Design Patterns


Do not use design patterns in any of the following situations.

• When the software being designed would not change with time.
• When the requirements of the source code of the application are unique.

If any of the above applies in the current software design, there is no need to apply design patterns in the
current design and increase unnecessary complexity in the design.

(B) What’ is the sequence in which ASP.NET events are processed?


Following is the sequence in which the events occur:-
• Page_Init.
• Page Load.
• Control events
• Page- Unload event.
Page_init event only occurs when first time the page is started, but Page Load occurs in subsequent
request of the page.

(B) In which event are the controls fully loaded?

Page load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init
events but you will see that view state is not fully loaded during this event.5
(B) How can we identify that the Page is Post Back?
Page object has an “IsPostBack” property, which can be checked to know that is the page posted back.

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

Refer Caching chapter, For Caching Part 1 and For Part 2 .

(A) What is event bubbling?

Server controls like Data grid, Data List, and Repeater can have other child controls inside them. Example
Data Grid can have combo box inside data grid. These child control do not raise there events by
themselves, rather they pass the event to the container parent (which can be a data grid, data list,
repeater), which passed to the page as “ItemCommand” event. As the child control send events to parent
it is termed as event bubbling.

(B) How do we assign page specific attributes?


Page attributes are specified using the @Page directive.

(A) How do we ensure view state is not tampered?

Using the @Page directive and setting ‘EnableViewStateMac’ property to True.

(B) What is the use of @ Register directives?

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

(B) What is the use of Smart Navigation property?

It’s a feature provided by ASP. NET to prevent flickering and redrawing when the page is posted back.

Note:- This is only supported for IE browser. Project is who have browser compatibility as requirements
have to think some other ways of avoiding flickering.

(B) What is AppSetting Section in “Web.Config” file?

Web.config file defines configuration for a web project. Using “AppSetting” section, we can define user-
defined values. Example below defined is “Connection String” section, which will be used through out the
project for database connection.

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

(B) Where is View State information stored?

In HTML Hidden Fields.


(I) what is the use of @ Output Cache directive in ASP.NET.

It is used for caching. See more for Caching chapter.

(B) How can we create custom controls in ASP.NET?

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

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

<%@ Register tag prefix="Accounting" Tag name="footer" src="Footer.ascx" %>

• Now to use the above accounting footer in page you can use the below directive.

<Accounting: footer runat="server" />

(B) How many types of validation controls are provided by ASP.NET?

There are six main types of validation controls:-

RequiredFieldValidator

It checks whether the control have any value. It is used when you want the control should not be empty.

RangeValidator

It checks if the value in validated control is in that specific range. Example TxtCustomerCode should not
be more than eight lengths.

CompareValidator

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

RegularExpressionValidator

When we want the control, value should match with a specific regular expression.

CustomValidator

It is used to define User Defined validation.


Validation Summary
It displays summary of all current validation errors on an ASP.NET page.

Note: - It is rare that some one will ask step by step all the validation controls. Rather they will ask for
what type of validation which validator will be used. Example in one of the interviews i was asked how will
you display summary of all errors in the validation control...just uttered one word Validation summary.
(B) Can you explain “AutoPostBack”?

If we want the control to automatically post back in case of any event, we will need to check this attribute
as true. Example on a Combo Box change we need to send the event immediately to the server side then
set the “AutoPostBack” attribute to true.

(B) How can you enable automatic paging in Data Grid?

Following are the points to be done in order to enable paging in Data grid:-
• Set the “Allow Paging” to true.
• In PageIndexChanged event set the current page index clicked.

Note: - The answers are very short, if you have implemented practically its just a revision. If you are
fresher, just make sample code using Datagrid and try to implement this functionality.

(B) What is the use of “GLOBAL.ASAX” file?

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

(B) What is the difference between “Web.config” and “Machine.Config”?

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

(B) What is a SESSION and APPLICATION object?

Session object store information between HTTP requests for a particular user, while application object are
global across users.

(I) Do session use cookies?

Twist:- How can we make session to not to use cookies ?


Left to the user, you will enjoy to find this answer.

(I) How can we force all the validation control to run?

Page.Validate

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

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

(A) If client side validation is enabled in your Web page, does that mean server side code is not run.

When client side validation is enabled server emit’s JavaScript code for the custom validators. However,
note that does not mean that server side checks on custom validators do not execute. It does this
redundant check two times, as some of the validators do not support client side scripting.
(A)Which JavaScript file is referenced for validating the validators at the client side?

WebUIValidation.js JavaScript file installed at “aspnet_client” root IIS directory is used to validate the
validation controls at the client side

(B)How to disable client side script in validators?

Set ‘EnableClientScript’ to false.

(A)How can I show the entire validation error message in a message box on the client side?

In validation summary set “ShowMessageBox” to true.

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

Best is to go for CustomValidators. Below is a sample code for a custom validator, which checks that a
textbox should not have zero value
<asp:CustomValidator id="CustomValidator1" runat="server"
ErrorMessage="Number not divisible by Zero"
ControlToValidate="txtNumber"
OnServerValidate="ServerValidate"
ClientValidationFunction="CheckZero" /><br>
Input:
<asp:TextBox id="txtNumber" runat="server" />
<script language="javascript">
<!--function CheckZero(source, args) {
int val = parseInt(args.Value, 10);
if (value==0) {
args.
IsValid = false;
}
}
// -->
</script>

(I)What exactly happens when ASPX page is requested from a browser?

Note: - Here the interviewer is expecting complete flow of how an ASPX page is processed with respect
to IIS and ASP.NET engine.
Following are the steps which occur when we request a ASPX page :-
The browser sends the request to the webserver. Let us assume that the webserver at the other end is
IIS.
Once IIS receives the request he looks on which engine can serve this request.When we mean engine
means the DLL who can parse this page or compile and send a response back to browser. Which request
to map to is decided by file extension of the page requested.
Depending on file extension following are some mapping
• .aspx, for ASP.NET Web pages,
• .asmx, for ASP.NET Web services,
• .config, for ASP.NET configuration files,
• .ashx, for custom ASP.NET HTTP handlers,
• .rem, for remoting resources
You can also configure the extension mapping to which engine can route by using the IIS engine.

Figure: - 7.1 following screen shows some IIS mappings

Example an ASP page will be sent to old classic ASP.DLL to compile. While .ASPX pages will be routed
to ASP.NET engine for compilation.
• As this book mainly will target ASP.NET we will look in to how ASP.NET pages that is ASPX pages
generation sequence occurs. Once IIS passes the request to ASP.NET engine page has to go through
two section HTTP module section and HTTP handler section. Both these section have there own work to
be done in order that the page is properly compiled and sent to the IIS. HTTP modules inspect the
incoming request and depending on that, they can change the internal workflow of the request. HTTP
handler actually compiles the page and generates output. If you see your machine.config file you will see
following section of HTTP modules

<httpModules>
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" />
<add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
<add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule" />
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
<add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" />
<add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule,
System.Web.Mobile, Version=1.0.5000.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</httpModules>

The above mapping will show which Namespace handles which functionality. Example
FormsAthuentication is handled by “System. Web.
Security.FormsAuthenticationModule”. If you look at the web.config, section HTTP module is where
authentication and authorization happens.

Ok now the HTTP handler is where the actual compilation takes place and the output is generated.
Following is a paste from HTTP handler section of WEB.CONFIG file.

<httpHandlers>
<add verb="*" path="*.vjsproj" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.java" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.jsl" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="trace.axd" type="System.Web.Handlers.TraceHandler" />
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />
<add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory" />
...
</httpHandlers>

• Depending on the File extension handler decides which Namespace will generate the output. Example
all .ASPX extension files will be compiled by System.Web.UI.PageHandlerFactory
• Once the file is compiled it will be send back again to the HTTP modules and from there to IIS and then
to the browser.
Figure: - 7.2 IIS flow from various sections.

(B) How can we kill a user session?

Session abandon

(I) How do you upload a file in ASP.NET?

I will leave this to the readers … Just a hint we have to use System.Web.HttpPostedFile class.

(I) How do I send email message from ASP.NET?

ASP.NET provides two namespace SystemWEB.mailmessage class and System.Web.Mail.Smtpmail


class. Just a small homework creates a Asp.NET project and send a email at shiv_koirala@yahoo.com.
Do not Spam.

(A) What are different IIS isolation levels?

IIS has three level of isolation:-


LOW (IIS process):- In this main IIS, process, and ASP.NET application run in same process. So if any
one crashes the other is also affected. Example let us say (well this is not possible) I have hosted yahoo,
hotmail .amazon and goggle on a single PC. So all application and the IIS process runs on the same
process. In case any website crashes, it affects every one.

Figure: - 7.3 LOW IIS process scenario

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

Figure: - 7.4 Medium pooled scenario

High (Isolated):-In high isolated scenario every process is running is there own process. In below figure
there are five processes and every one handling individual application. This consumes heavy memory but
has highest reliability.

Figure: - 7.5 High isolation scenario

(A)ASP used STA threading model, what is the threading model used for ASP.NET.
ASP.NET uses MTA threading model.

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

This attribute works like a compatibility option. As mentioned before ASP worked in STA model and
ASP.NET works in MTA model, but what if your ASP.NET application is using a VB COM component. In
order that VB COM runs properly in ASP.NET threading model, we have to set attribute. After defining the
ASPCOMPAT directive attribute ASP.NET pages runs in STA model thus building the compatibility
between ASP.NET and old COM components that does not support MTA model.

(B) Explain the differences between Server-side and Client-side code?

Server side code is executed at the server side on IIS in ASP.NET framework, while client side code is
executed on the browser.

(I)Can you explain Forms authentication in detail?

In old ASP if you where said to create a login page and do authentication you have to do hell lot of
custom coding. Now in ASP.NET that has made easy by introducing Forms authentication. So let us see
in detail what form authentication is.
Forms authentication uses a ticket cookie to see that user is authenticated or not. That means when user
is authenticated first time a cookie is set to tell that this user is authenticated. If the cookies expire then
Forms authentication mechanism sends the user to the login page.
Following are the steps, which defines steps for Forms authentication:-
• Configure Web.config file with forms authentication. As shown below in the config file you can see we
have give the cookie name and loginurl page.

<configuration>
<system.web>
<!-- Other settings omitted. -->
<authentication mode="Forms">
<forms name="logincookies"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/" />
</authentication>
</system.web>
</configuration>
• Remove anonymous access to the IIS web application, following are changes done to web.config file.

<configuration>
<system.web>
<!-- Other settings omitted. -->
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>

• Create the login page, which will accept user information. You will have create your login page that is
the Login.aspx, which will actually take the user data.
• Finally a small coding in the login button.
Let us assume that the login page has two textboxes TX name and txtapssword.
Also, import System.Web.Security and put the following code in login button of the page.
If Page.IsValid Then
If FormsAuthentication.Authenticate(txtName.Text, txtPassword.Text) Then
FormsAuthentication.RedirectFromLoginPage(txtName.Text, False)
Else
lblStatus.Text = "Error not proper user"
End If
End If

(A)How do I sign out in forms authentication?

FormsAuthentication.Signout ()

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

No, it does not work.

(A)How to use a checkbox in a data grid?

Twist: - How can I track event in checkbox, which is one of the columns of a data grid?

Note: - This is normally asked when the interviewer want to see that have you really worked practically on
a project.

Following are the steps to be done:-


• In ASPX page you have to add Item template tag in data grid.

<ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server" AutoPostBack="True"
OnCheckedChanged="Check_Clicked"></asp:CheckBox>
</ItemTemplate>

If you look at the Item template, we have “OnCheckChanged” event. This “OnCheckChanged” event has
“Check Clicked” subroutine is actually in behind code. Note this method, which is in behind code, should
either be “protected” or “public”
Following below is the subroutine, which defines the method

Protected Sub Check Clicked (By Val sender As Object, By Val e As EventArgs)
‘Do something
End Sub
The above steps should be defined in short to the interviewer, which will give a quick feeling of your
practical experience with ASP.NET’

(I)What are the steps to create a windows service in VB.NET?

Windows Services are long-running executable applications that run in its own Windows session, which
then has the ability to start automatically when the computer boots and also can be manually paused,
stopped or even restarted.
Following are the steps to create a service:-
Create a project of type “Windows Service”.

Figure 7.6:- Create project for Windows Service

• If you see, the class created it is automatically inheriting from “System.ServiceProcess.ServiceBase”.


• You can override the following events provided by service and write your custom code. All the three
main events can be used that is Start, stop and continue.

protected override void OnStart(string[] args)


{
}
protected override void OnStop()
{
}
protected override void OnContinue()
{
}

Now to install the service you need to do run the install util exe.

InstallUtil <Project Path>\BIN\MyNewService.exe

(A) What is the difference between “Web farms” and “Web garden”?

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

Figure 7.7: - Web Farm in action

Above figure explains in detail how web farm work. You can see there is a router in between which takes
a request and sees which one of the server is least loaded and forwards the request to that server.
Therefore, for request1 it route is server1, for request2 it routes server2, for request3 it routes to server3
and final request4 is routed to server4. So you can see because we have web farm at place server1 and
server2 are loaded with two request each rather than one server loading to full. One more advantage of
using this kind of architecture is if one of the servers goes down we can still run with the other server thus
having 24x7 uptime.
The routing logic can be a number of different options:-
• Round robin: Each node gets a request sent to it “in turn”. Therefore, server1 gets a request, then
server2 again, then server1, then server2 again. As shown in the above figure.
• Least Active: Whichever node show to have the lowest number of current connects gets new connects
sent to it. This is good to help keep the load balanced between the server nodes.
• Fastest Reply: Whichever node replies faster is the one that gets new requests. This is also a good
option - especially if there are nodes that might not be “equal” in performance. If one performs better than
the other, then send more requests there rather than which is moving slowly?
Before we try to understand what a web garden is let’s try to understand how IIS handles processes. All
requests to IIS are routed to “aspnet_wp.exe” for IIS 5.0 and “w3wp.exe” for IIS 6.0. In normal case i.e.
with out web garden, we have one worker process instance (“aspnet_wp.exe” / “w3wp.exe”) across all
requests. This one instance of worker process uses the CPU processor as directed by the operating
system.

Figure 7.8: - with out Web Garden

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

Figure 7.9: - With Web Garden

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

(A) How do we configure “Web Garden”?

“Web garden” can be configured by using process model settings in “machine.config” or “Web.config” file.
The configuration section is named <process Model> and is shown in
The following example. The process model is enabled by default (enable=”true”). Below is the snippet
from config file.

<process Model
enable=”true”
timeout=”infinite”
idle Timeout=”infinite”
shutdown Timeout=”0:00:05"
requestLimit=”infinite”
requestQueueLimit=”5000"
memoryLimit=”80"
webGarden=”false”
cpuMask=”12"
userName=””
password=””
logLevel=”errors”
clientConnectedCheck=”0:00:05"
/>

From the above process model section for web garden, we are concerned with only two attributes “web
garden” and “cpuMask”.
Web Garden: - Controls CPU affinity. True indicates that processes should be affinities to the
corresponding CPU. The default is False.
CpuMask:- Specifies which processors on a multiprocessor server are eligible to run ASP.NET
processes. The cpuMask value specifies a bit pattern that indicates the CPUs eligible to run ASP.NET
threads. ASP.NET launches one worker process for each eligible CPU. If web Garden is set to false,
cpuMask is ignored and only one worker process will run regardless of the number of processors in the
machine. If web Garden is set to true, ASP.NET launches one worker process for each CPU that
corresponds to a set bit in cpuMask. The default value of cpuMask is 0xffffffff.
Below are detail steps of how to implement web garden
• Click Start and then click Run.
• Type calc.exe and then click OK.
• Go to View menu, click Scientific.
• Go to View menu, click Binary.
• Use zero and one to specify the processors ASP.NET can or cannot use.
Use one for the processor that you want to use for ASP.NET. Use 0 for the processor that you do not
want to use for ASP.NET. For example, if you want to use the first two processors for ASP.NET of a four-
processor computer, type 1100.
• On the View menu, click Decimal. Note the decimal number.
• Open the Web.config or machine.config file in a text editor such as Notepad. The Web.config file is
located in the folder where the application is saved.
• In the Web.config file, add the process Model configuration element under the System. Web element.
Before adding <process Model> to Web.config file, the user has to make sure that the allow Definition
attribute in the <process Model> section of the Web.config file is set to everywhere.
• Add and then set the web Garden attribute of the process Model element to True.
• Add and then set the cpuMask attribute of the process Model element to the result that is determined in
your calculation.
Do not preface the number with zerox because the result of the calculation is a decimal number. The
following example demonstrates the process Model element that is configured to enable only the first two
processors of a four-processor computer.

<processModel
enable=”true”
webGarden=”true”
cpuMask=”12" />

Save the Web.config file. The ASP.NET application automatically restarts and uses only the specified
processors.

(B) What is the main difference between Grid layout and Flow Layout?

Grid Layout provides absolute positioning for controls placed on the page. Developers that have their
roots in rich-client development environments like Visual Basic will find it easier to develop their pages
using absolute positioning, because they can place items exactly where they want them. On the other
hand, Flow Layout positions items down the page like traditional HTML. Experienced Web developers
favor this approach because it results in pages that are compatible with a wider range of browsers.
If you look in to the HTML code created by absolute positioning you can notice lot of DIV tags. While in
Flow layout, you can see more of using HTML table to position elements, which is compatible with wide
range of browsers.

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

Debug and trace enables you to monitor the application for errors and exception with out VS.NET IDE. In
Debug mode compiler inserts some debugging code inside the executable. As the debugging code is the
part of the executable they run on the same thread where the code runs and they do not given you the
exact efficiency of the code ( as they run on the same thread). So for every full executable DLL you will
see a debug file also as shown in figure ‘Debug Mode’.
Figure 7.10 : - Debug mode

Trace works in both debug as well as release mode. The main advantage of using trace over debug is to
do performance analysis which can not be done by debug. Trace runs on a different thread thus it does
not impact the main code thread.

Note: - There is also a fundamental difference in thinking when we want to use trace and when want to
debug. Tracing is a process about getting information regarding program's execution. On the other hand
debugging is about finding errors in the code.

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

To enable tracing on an ASP.NET page we need to put the ‘trace’ attribute to true on the page attribute as
shown in figure ‘Tracing in Action’ ( Its numbered as 1 in the figure). In the behind code we can use the
trace object to put tracing like one we have shown on the page load numbered as (4). We have used the
‘trace.write’ to display our tracing. You can also see the trace data which is circled. 2 and 3 show the
actual data. You can see how trace shows in details the tracing information for a page with events and
time period for execution. If you make the ‘trace’ as false you will only see the actual display i.e. ‘This is
the actual data’. So you can enable and disable trace with out actually compiling and uploading new
DLL’s on production environment.

Figure 7.11 : - Tracing in Action

The above sample enables tracing only at page level. To enable tracing on application level we need to
modify the ‘web.config’ file and put the ‘trace’ tag with ‘enabled=true’.

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

(B) Which namespace is needed to implement debug and trace ?

Debug and trace class belongs to ‘System.Diagnostic’ namespace.

(A) Can you explain the concept of trace listener?

‘Tracelistener’ are objects that get tracing information from the trace class and they output the data to
some medium. For instance you can see from the figure ‘TraceListener’ how it listens to the trace object
and outputs the same to UI, File or a windows event log. There are three different types of ‘tracelistener’
first is the ‘defaulttracelistener’ (this outputs the data to UI), second is ‘textwritertracelistener’ (this outputs
to a file) and the final one is ‘Eventlogtracelistener’ which outputs the same to a windows event log.

Figure 7.12 : - TraceListener

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


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

Figure 7.13 :- Tracelistener in action

(I) What are trace switches?

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

Figure 7.14 :- Trace switches

‘TraceSwitch’ on the other hand offers more options rather than simple true/false like ‘BooleanSwitch’.
Tracing is enabled for a TraceSwitch object using the Level property. When we set the Level property of a
switch to a particular level, it includes all levels from the indicated level down. For example, if you set a
TraceSwitch's Level property to TraceLevel.Info, then all the lower levels, from TraceLevel.Error to
TraceLevel.Warning, will be taken in to account. Below are the various levels in ‘TraceSwitch’ object.
Off a Outputs no messages to Trace Listeners
Error a Outputs only error messages to Trace Listeners
Warning a Outputs error and warning messages to Trace Listeners
Info a Outputs informational, warning and error messages to Trace Listeners
Verbose a Outputs all messages to Trace Listeners

TraceSwitch objSwitch = new TraceSwitch("TraceWarningandError", "Error in trace") ;


objSwitch.Level = TraceLevel.Warning ;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 >
ASP.NET Questions – 01
August 5, 2006
Explain the .NET architecture.
How many languages .NET is supporting now? – When .NET was introduced it came with several
languages. VB.NET, C#, COBOL and Perl, etc. The site DotNetLanguages.Net says 44 languages are
supported.
How is .NET able to support multiple languages? – a language should comply with the Common
Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft
Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in
.NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a
function written in another language.
How ASP .NET different from ASP? – Scripting is separated from the HTML, Code is compiled as a DLL,
these DLLs can be executed on the server.
Resource Files: How to use the resource files, how to know which language to use?
What is smart navigation? – The cursor position is maintained when the page gets refreshed due to the
server side validation and the page gets refreshed.
What is view state? – The web is stateless. But in ASP.NET, the state of a page is maintained in the in
the page itself automatically. How? The values are encrypted and saved in hidden controls. this is done
automatically by the ASP.NET. This can be switched off / on for a single control
Explain the life cycle of an ASP .NET page.
How do you validate the controls in an ASP .NET page? – Using special validation controls that are
meant for this. We have Range Validator, Email Validator.
Can the validation be done in the server side? Or this can be done only in the Client side? – Client side is
done by default. Server side validation is also possible. We can switch off the client side and server side
can be done.
How to manage pagination in a page? – Using pagination option in DataGrid control. We have to set the
number of records for a page, then it takes care of pagination by itself.
What is ADO .NET and what is difference between ADO and ADO.NET? – ADO.NET is stateless
mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships
between the tables and select insert and updates to the database. I can update the actual database as a
batch.

C# interview questions and answers


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

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


What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one
performs a deep copy of the array, the second one is shallow.
How can you sort the elements of the array in descending order? By calling Sort() and then Reverse()
methods.
What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.
What’s class SortedList underneath? A sorted HashTable.
Will finally block get executed if the exception had not occurred? Yes.
What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data
type in this case and just write catch {}.
Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred
to the finally block (if there are any), and then whatever follows the finally block.
Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has
occurred, then why not write the proper code to handle that error instead of passing a new Exception
object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to
as function pointers.
What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.
How’s the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not
only the library it needs to run (which was available under Win32), but also the version of the assembly.
What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
What’s a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want
to distribute the core application separately from the localized modules, the localized assemblies that
modify the core application are called satellite assemblies.
What namespaces are necessary to create a localized application? System.Globalization,
System.Resources.
What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and
XML documentation comments.
How do you generate documentation from the C# file commented properly with a command-line
compiler? Compile it with a /doc switch.
What’s the difference between <c> and <code> XML documentation tag? Single line code example and
multiple-line code example.
Is XML case-sensitive? Yes, so <Student> and <student> are different elements.
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.
What does the This window show in the debugger? It points to the object that’s pointed to by this
reference. Object’s instance data is shown.
What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and
shows the error dialog if the condition is false. The program proceeds without any interruption if the
condition is true.
What’s the difference between the Debug class and Trace class? Documentation looks the same. Use
Debug class for debug builds, use Trace class for both debug and release builds.
Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite
verbose and for some applications that are constantly running you run the risk of overloading the machine
and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing
activities.
Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the
parameter passed to the constructor.
How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr
debugger.
What are three test cases you should go through in unit testing? Positive test cases (correct data, correct
output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions
are thrown and caught properly).
Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via
Visual Studio.NET, just go to Immediate window.
Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying
code) and data (from storage or other sources).
What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from
Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and
Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a
deprecated layer provided for backward compatibility to ODBC engines.
What’s 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.
What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees
whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
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 hasn’t), Isolated (no transaction
sees the intermediate results of the current transaction), Durable (the values persist if the data had been
committed even if the system crashes right after).
What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and
SQL Server authentication (via Microsoft SQL Server username and passwords).
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.
Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows
applications.
What does the parameter Initial Catalog define inside Connection String? The database name to connect
to.
What’s the data provider name to connect to Access database? Microsoft.Access.
What does Dispose method do with the connection object? Deletes it from the memory.
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.
Here are some SQL Server DBA/Developer interview questions I faced myself personally and/or heard
from people. I will try to answer these questions briefly here, but be advised that these answers may not
be complete and it will be better for you to go through text books, books online and other resources on the
net. At the end of this article, I listed some useful books for aspiring DBAs and developers.

Before you go for the interview, be prepared to explain the database design of one of your latest projects.
Don't be surprised if the interviewer asks you to draw ER diagrams.

Well, here are some questions for you. Hope this helps you prepare for your interview. Wish you all the
best in your job hunt! Feel free to email me 'interview questions' that you've faced.

Questions are categorized under the following sections, for your convenience:

Database design (8 questions)


SQL Server architecture (12 questions)
Database administration (13 questions)
Database programming (10 questions)
Database design (top)
What is normalization? Explain different levels of normalization?
Check out the article Q100139 from Microsoft knowledge base and of course, there's much more
information available in the net. It'll be a good idea to get a hold of any RDBMS fundamentals text book,
especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.

What is denormalization and when would you go for it?


As the name indicates, denormalization is the reverse process of normalization. It's the controlled
introduction of redundancy in to the database design. It helps improve the query performance as the
number of joins could be reduced.

How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and
foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and
foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table.

It will be a good idea to read up a database designing fundamentals text book.

What's the difference between a primary key and a unique key?


Both primary key and unique enforce uniqueness of the column on which they are defined. But by default
primary key creates a clustered index on the column, where are unique creates a nonclustered index by
default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one
NULL only.

What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name,
and format to the database. Take for example, in your database, there is a column called Flight_Num
which appears in many tables. In all these tables it should be varchar(8). In this case you could create a
user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.

See sp_addtype, sp_droptype in books online.

What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit
datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards,
bit datatype can represent a third state, which is NULL.
Define candidate key, alternate key, composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes
the primary key of the table. If the table has more than one candidate key, one of them will become the
primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

What are defaults? Is there a column to which a default can't be bound?


A default is a value that will be used by a column, if no value is supplied to that column while inserting
data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE
DEFUALT in books online.

Back to top

SQL Server architecture (top)


What is a transaction and what are ACID properties?
A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for
Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more
information and explanation of these properties, see SQL Server books online or any RDBMS
fundamentals text book.

Explain different isolation levels


An isolation level determines the degree of isolation of data between concurrent transactions. The default
SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order
of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server
books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION
ISOLATION LEVEL, which lets you customize the isolation level at the connection level.

CREATE INDEX myIndex ON myTable(myColumn)

What type of Index will get created after executing the above statement?
Non-clustered index. Important thing to note: By default a clustered index gets created on the primary
key, unless specified otherwise.

What's the maximum size of a row?


8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'.
Check out SQL Server books online for the page titled: "Maximum Capacity Specifications".

Explain Active/Active and Active/Passive cluster configurations


Hopefully you have experience setting up cluster servers. But if you don't, at least be familiar with the way
clustering works and the two clusterning configurations Active/Active and Active/Passive. SQL Server
books online has enough information on this topic and there is a good white paper available on Microsoft
site.

Explain the architecture of SQL Server


This is a very important question and you better be able to answer it if consider yourself a DBA. SQL
Server books online is the best place to read about SQL Server architecture. Read up the chapter
dedicated to SQL Server Architecture.

What is lock escalation?


Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher
level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory
being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks
to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL
Server 7.0 onwards it's dynamically managed by SQL Server.
What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log,
which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion
of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of
course, TRUNCATE TABLE can be rolled back.

Explain the storage models of OLAP


Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more infomation.

What are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time
of your interview)? What changed between the previous version of SQL Server and the current version?
This question is generally asked to see how current is your knowledge. Generally there is a section in the
beginning of the books online titled "What's New", which has all such information. Of course, reading just
that is not enough, you should have tried those things to better answer the questions. Also check out the
section titled "Backward Compatibility" in books online which talks about the changes that have taken
place in the new version.

What are constraints? Explain different types of constraints.


Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to
create triggers, rule or defaults.

Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

For an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE
TABLE", "ALTER TABLE"

Whar is an index? What are the types of indexes? How many clustered indexes can be created on a
table? I create a separate index on each column of a table. what are the advantages and disadvantages
of this approach?
Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data
quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered
index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can
be only one clustered index per table. Non-clustered indexes have their own storage separate from the
table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with
the leaf level nodes having the index key and it's row locater. The row located could be the RID or the
Clustered index key, depending up on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query
optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the
same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as
every time data changes in the table, all the indexes need to be updated. Another disadvantage is that,
indexes need disk space, the more indexes you have, more disk space is used.

Back to top

Database administration (top)


What is RAID and what are different types of RAID configurations?
RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database
servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance.
MSDN has some information about RAID levels and for detailed information, check out the RAID advisory
board's homepage

What are the steps you will take to improve performance of a poor performing query?
This is a very open ended question and there could be a lot of reasons behind the poor performance of a
query. But some general issues that you could talk about would be: No indexes, table scans, missing or
out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers
without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much
normalization, excess usage of cursors and temporary tables.

Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL
ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000
Performance monitor, Graphical execution plan in Query Analyzer.

Download the white paper on performance tuning SQL Server from Microsoft web site. Don't forget to
check out sql-server-performance.com

What are the steps you will take, if you are tasked with securing an SQL Server?
Again this is another open ended question. Here are some things you could talk about: Preferring NT
authentication, using server, databse and application roles to control access to the data, securing the
physical database files using NTFS permissions, using an unguessable SA password, restricting physical
access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling
the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls,
isolating SQL Server from the web server etc.

Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server
security best practices

What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire
a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless
one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's
process.

A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of
overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and
refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page,
forcing a write transaction to wait indefinitely.

Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also
check out the article Q169960 from Microsoft knowledge base.

What is blocking and how would you troubleshoot it?


Blocking happens when one connection from an application holds a lock and a second connection
requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding
efficient transactions.

Explain CREATE DATABASE syntax


Many of us are used to craeting databases from the Enterprise Manager or by just issuing the command:
CREATE DATABAE MyDB. But what if you have to create a database with two filegroups, one on drive C
and the other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of
15%? That's why being a DBA you should be familiar with the CREATE DATABASE syntax. Check out
SQL Server books online for more information.

How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very
important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in
single user mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL
Server books online for more parameters and their explanations.
As a part of your job, what are the DBCC commands that you commonly use for database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC
SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of
DBCC commands which are very useful for DBAs. Check out SQL Server books online for more
information.

What are statistics, under what circumstances they go out of date, how do you update them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values then the
selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses
these indexes in determining whether to choose an index or not while executing a query.

Some situations under which you should update statistics:


1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the
distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE
statement and then repopulated
3) Database is upgraded from a previous version

Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE,
DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats,
sp_updatestats

What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements.
Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication,
DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

Explian different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would
you go about choosing a backup plan?
Types of backups you can create in SQL 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.

What is database replicaion? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers.
SQL Server supports the following types of replication scenarios:

Snapshot replication
Transactional replication (with immediate updating subscribers, with queued updating subscribers)
Merge replication
See SQL Server books online for indepth coverage on replication. Be prepared to explain how different
replication agents function, what are the main system tables used in replication etc.

How to determine the service pack currently installed on SQL Server?


The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine
the service pack installed. To know more about this process visit SQL Server service packs and versions.

Back to top

Database programming (top)


What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can
you avoid cursors?
Cursors allow row-by-row prcessing of the resultsets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip,
where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are
also costly because they require more resources and temporary storage (results in more IO operations).
Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike


Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his
salary according to the above formula. But the same can be achieved by multiple update statements or
can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =


CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a
column in a particular row meets certain condition. You don't have to use cursors for this. This can be
achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using
WHILE loop for row by row processing, check out the 'My code library' section of my site or search for
WHILE.

Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

What is a join and explain different types of joins.


Joins are used in queries to explain how different tables are related. Joins also let you select data from a
table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as
LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

Can you have a nested transaction?


Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++
using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored
procedures using the EXEC statement. See books online to learn how to create extended stored
procedures and how to add them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using
sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty,
sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-
SQL, see 'My code library' section of this site.

What is the system function to get the current user's user id?
USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER,
SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().

What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?
Triggers are special kind of stored procedures that get executed automatically when an INSERT,
UPDATE or DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one
for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple
triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In SQL
Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder

Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT,
UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend
the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers,
as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are
called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000
books online for INSTEAD OF triggers.

Also check out books online for 'inserted table', 'deleted table' and COLUMNS_UPDATED()

There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to
instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do
you think of this implementation? Can this be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it
slows down the data insertion process. Same is the case with sending emails from triggers. This scenario
can be better implemented by logging all the necessary data into a separate table, and have a job which
periodically checks this table and does the needful.

What is a self join? Explain it with an example.


Self join is just like any other join, except that two instances of the same table will be joined in the query.
Here is an example: Employees table which contains rows for normal employees as well as managers.
So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp


(
empid int,
mgrid int,
empname char(10)
)
INSERT emp SELECT 1,2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]


FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without
managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]


FROM emp t1
LEFT OUTER JOIN
emp t2
ON
t1.mgrid = t2.empid

Given an employee table, how would you find out the second highest salary?
For a solution see the 'My code library' section of this site.

Begin Transaction
Update names_table set employee_name = "Ramesh" where employee_name = "Mahesh"
Save Transaction SAVE_POINT
Update salaries set salary=salary + 900 where employee_job = "Engineer"
Rollback transaction
Commit transaction

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

What operators perform pattern matching?


SELECT employeeNumber, lastName, firstName
FROM employees
WHERE firstName LIKE 'a%'

What is Trigger?
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE)
occurs.

What is View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as
updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the
view was created with.

What is Index?
An index is a physical structure containing pointers to the data. Indices are created in an existing table to
locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a
table, and each index is given a name.

What is the use of DBCC commands?


DBCC stands for database consistency checker. We use these commands to check the consistency of
the databases, i.e., maintenance, validation task and status checks.
E.g. DBCC CHECKDB – Ensures that tables in the db and the indexes are correctly linked.
DBCC CHECKALLOC – To check that all pages in a db are correctly allocated

How to 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.
What is difference between DELETE & TRUNCATE commands?
Delete command removes the rows from a table based on the condition that we provide with a WHERE
clause. Truncate will actually remove all the rows from a table and there will be no data in the table after
we run the truncate command.

Difference between Function and Stored Procedure?


UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as
Stored procedures cannot be.
UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline UDF’s can be though of as views that take parameters and can be used in JOINs and other Rowset
operations.

Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433

6. How to read and write a file using javascript?


I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java
applet that reads files for the script.
5. How do we get JavaScript onto a web page?
You can use several different methods of placing javascript in you pages.
You can directly add a script element inside the body of page.
1. For example, to add the "last updated line" to your pages, In your page text, add the following:
<p>blah, blah, blah, blah, blah.</p>
<script type="text/javascript" >
<!-- Hiding from old browsers
document.write("Last Updated:" +
document.lastModified);
document.close();
// -->
</script>
<p>yada, yada, yada.</p>

(Note: the first comment, "<--" hides the content of the script from browsers that don't understand javascript. The "// -->" finishes the
comment. The "//" tells javascript that this is a comment so javascript doesn't try to interpret the "-->". If your audience has much
older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments
can be omitted. For brevity, in most examples here the comments are not shown. )
The above code will look like this on Javascript enabled browsers,
2. Javascript can be placed inside the <head> element
Functions and global variables typically reside inside the <head> element.
<head>
<title>Default Test Page</title>
<script language="JavaScript" type="text/javascript">
var myVar = "";
function timer(){setTimeout('restart()',10);}
document.onload=timer();
</script>
</head>

3. Javascript can be referenced from a separate file


Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don't use the shorthand ending
"<script ... />). These are typically placed in the <head> element.
<script type="text/javascript" SRC="myStuff.js"></script>

7. How to detect the operating system on the client machine?


In order to detect the operating system on the client machine, the navigator.appVersion
string (property) should be used.

10. What are JavaScript types?


Number, String, Boolean, Function, Object, Null, Undefined.

12. How to create arrays in JavaScript?


We can declare an array like this
var scripts = new Array();
We can add elements to this array like this

scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";

document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);

13. How do you target a specific frame from a hyperlink?


Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm” target=”myframe”>>My Page</a>
14. What is a fixed-width table and its advantages?
Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in
case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table.
If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for
each of the columns. This process can be very slow for large tables

15. Example of using Regular Expressions for syntax checking in JavaScript


var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");
var text = myWidget.value;
var OK = re.test(text);
if( ! OK ) {
alert("The extra parameters need some work.\r\n Should be something like: \"&a=1&c=4\"");
}

How to add Buttons in JavaScript?


function displayHero(button) {
alert("Your hero is \""+button.value+"\".");
}
</script>

<form action="" name="buttonsGalore" method="get">


<fieldset style="margin: 1em; text-align: center;">
<legend>Select a Hero</legend>
<input type="button" value="Agamemnon" onclick="displayHero(this)" />
<input type="button" value="Achilles" onclick="displayHero(this)" />
<input type="button" value="Hector" onclick="displayHero(this)" />
<div style="height: 1em;" />
</fieldset>
</form>

17. Where are cookies actually stored on the hard disk?


This depends on the user's browser and OS.
In the case of Netscape with Windows OS,all the cookies are stored in a single file called

cookies.txt
c:\Program Files\Netscape\Users\username\cookies.txt
In the case of IE,each cookie is stored in a separate file namely username@website.txt.
c:\Windows\Cookies\username@Website.tx

19. How to set a HTML document's background color?


document.bgcolor property can be set to any appropriate color.

23. What is negative infinity?


It’s a number in JavaScript, derived by dividing negative number by zero.

24. In a pop-up browser window, how do you refer to the main browser window that opened it?
Use window.opener to refer to the main window from pop-ups
.
26. Methods GET and POST in HTML forms - what's the difference?.
GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about
2kb.
POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST.
However, there are limits on the maximum amount of data that can be transferred in one name/value pair.

35. What boolean operators does JavaScript support?


&&, || and !

36. What does "1"+2+4 evaluate to?


Since 1 is a string, everything is a string, so the result is 124.

37. What are the ways to emit client-side JavaScript from server-side code in ASP.NET?
The Page object in ASP.NET has two methods that allow emitting of client-side JavaScript:
RegisterClientScriptBlock and RegisterStartupScript.

40. How to get the contents of an input box using Javascript?


Use the "value" property.
var myValue = window.document.getElementById("MyTextBox").value;

41. How to determine the state of a checkbox using Javascript?


var checkedP = window.document.getElementById("myCheckBox").checked;

42. How to set the focus in an element using Javascript?


<script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>

43. How to access an external javascript file that is stored externally and not embedded?
This can be achieved by using the following tag between head tags or between body tags.
<script src="abc.js"></script>How to access an external javascript file that is stored externally and not embedded? where abc.js is
the external javscript file to be accessed.

45. What is a prompt box?


A prompt box allows the user to enter input by providing a text box.

49. How about 2+5+"8"?


Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.

50. What is the difference between SessionState and ViewState?


ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the
web application.

51. What does the EnableViewStateMac setting in an aspx page do?


Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the viewstate for a page has not been
tampered with. If on Postback, the ASP.NET framework detects that there has been a change in the value of viewstate that was
sent to the browser, it raises an error - Validation of viewstate MAC failed.
Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not specified is also true) in an
aspx page.

52. How to Accessing Elements using javascript?


To do something interesting with HTML elements, we must first be able to uniquely identify which element we want. In the example
<body>
<form action="">
<input type="button" id="useless" name="mybutton" value="doNothing" />
</form>
</body>

We can use the "getElementById" method (which is generally preferred)


document.getElementById("useless").style.color = "red";
or we can use the older hierarchical navigation method,
document.forms[0].mybutton.style.color = "blue";
Notice that this uses the "name" attribute of the element to locate it.
# Example of Accessing Elements in a DOM.

<script type="text/javascript" >


function showStatus() {
var selectWidget = document.forms.beerForm.elements["beer"];
var myValue = selectWidget.options[selectWidget.selectedIndex].value;
alert('You drank a \"'+ myValue +"\"");
return true;
}
</script>

<form name="beerForm" action="">


<select name="beer">
<option selected="selected">Select Beer</option>
<option>Heineken</option>
<option>Amstel Light</option>
<option>Corona</option>
<option>Corona Light</option>
<option>Tecate</option>
</select>

<input type="button" name="submitbutton" value="Drink"


onclick="showStatus()" />
</form

53. What looping structures are there in JavaScript?


for, while, do-while loops, but no foreach.

<script language=javascript> <!-- javascript code goes here // --> or Use the <NOSCRIPT>some html code </NOSCRIPT>

56. How to comment javascript code?


Use // for line comments and /* */ for block comments

57. Name the numeric constants representing max,min values


Number.MAX_VALUE
Number.MIN_VALUE

59. How do you create a new object in JavaScript?


var obj = new Object(); or var obj = {};

60. How do you assign object properties?


obj["age"] = 17 or obj.age = 17.

61. What’s a way to append a value to an array?


arr[arr.length] = value;

65. To set all checkboxes to true using JavaScript?


//select all input tags
function SelectAll() {
var checkboxes = document.getElementsByTagName("input");
for(i=0;i<checkboxes.length;i++) {
if(checkboxes.item(i).attributes["type"].value == "checkbox") {
checkboxes.item(i).checked = true;

67. What does undefined value mean in javascript?


Undefined value means the variable used in the code doesnt exist or is not assigned any value or the property doesnt exist.

72. What is === operator ?


==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.

73. How to find the selected radio button immediately using the 'this' variable?
<script>
function favAnimal(button) {
alert('You like '+button.value+'s.');
}.....<input type="radio" name="marsupial" value="Tasmanian Tiger"
onchange="favAnimal(this)">Tasmanian Tiger

75. How to disable an HTML object


document.getElementById("myObject").disabled = true;

76. To write messages to the screen without using "document.write()" ?


Changing the contents of an element is a much better solution. When the method showStatus is invoked it will change the content of
the span.
...
function showStatus(message) {
var element = document.getElementById("mystatus");
element.textContent = message; //for Firefox
element.innerHTML = message; //for IE (why can't we all just get along?)
return true;
}
...
<span id="mystatus">Test. </span>

78. How to Add new elements dynamically.


var newP = document.createElement("p");
var textNode = document.createTextNode(" I'm a new text node");
newP.appendChild(textNode);

82. How to create a confirmation box?


confirm("Do you really want to launch the missile?");

83. How to create an input box?


prompt("What is your temperature?");

84. How to open a window with no toolbar, but with the location object.
window.open("http://www.mysite.org/Misc/Pennies","Pennies","resizable=yes,
status=yes,toolbar=yes,location=yes,menubar=yes,scrollbars=yes,width=800,height=400"

/Sets cookie of current value for myTextBox


function TextBoxOnchange() {
var myBox = window.document.getElementById(myTextBox");
document.cookie = "myTextBox="+ escape(myBox.value) + getExpirationString();

89. How to change style on an element?


Between CSS and javascript is a weird symmetry. CSS style rules are layed on top of the DOM. The CSS property names like "font-
weight" are transliterated into "myElement.style.fontWeight". The class of an element can be swapped out. For example:
document.getElementById("myText").style.color = "green";
document.getElementById("myText").style.fontSize = "20";
-or-
document.getElementById("myText").className = "regular";

90. How to make elements invisible


Change the "visibility" attribute of the style object associated with your element. Remember that a hidden element still takes up
space, use "display" to make the space disappear as well.

if ( x == y) {
myElement.style.visibility = 'visible';
} else {
myElement.style.visibility = 'hidden';
}

91. How to set the cursor to wait.


In theory, we should cache the current state of the cursor and then put it back to its original state.
document.body.style.cursor = 'wait';
//do something interesting and time consuming
document.body.style.cursor = 'auto';

92. How to reload the current page


window.location.reload(true);

93. how to force a page to go to another page using JavaScript?


<script language="JavaScript" type="text/javascript" ><!-- location.href="http://newhost/newpath/newfile.html"; //--></script>

7. What's Math Constants and Functions using JavaScript?


The Math object contains useful constants such as Math.PI, Math.E
Math also has a zillion helpful functions.
Math.abs(value); //absolute value
Math.max(value1, value2); //find the largest
Math.random() //generate a decimal number between 0 and 1
Math.floor(Math.random()*101) //generate a decimal number between 0 and 100

98. What's the Date object using JavaScript?


Time inside a date object is stored as milliseconds since Jan 1, 1970.
new Date(06,01,02) // produces "Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)"
new Date(06,01,02).toLocaleString() // produces "Friday, February 02, 1906 00:00:00"
new Date(06,01,02) - new Date(06,01,01) // produces "86400000"

99. What does the delete operator do?


The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with
var keyword.

103. How to use "join()" to create a string from an array using JavaScript?
"join" concatenates the array elements with a specified seperator between them.

<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("days:"+days.join(","));
</script>
This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday

108. eval()?
The eval() method is incredibly powerful allowing you to execute snippets of code during exection.

<script type="text/javascript">
var USA_Texas_Austin = "521,289";
document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));
</script>
This produces
Population is 521,289

109. What does break and continue statements do?


Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current
loop.

110. How to create a function using function constructor?


The following example illustrates this
It creates a function called square with argument x and returns x multiplied by itself.
var square = new Function ("x","return x*x");
CREATE PROCEDURE OrderSummary @MaxQuantity INT OUTPUT AS
-- SELECT to return a result set summarizing
-- employee sales.
SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID

-- SELECT to fill the output parameter with the


-- maximum quantity from Order Details.
SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]

-- Return the number of all items ordered.


RETURN (SELECT SUM(Quantity) FROM [Order Details])
GO

-- Test the stored procedure.

-- DECLARE variables to hold the return code


-- and output parameter.
DECLARE @OrderSum INT
DECLARE @LargestOrder INT

-- Execute the procedure, which returns


-- the result set from the first SELECT.
EXEC @OrderSum = OrderSummary @MaxQuantity = @LargestOrder OUTPUT

-- Use the return code and output parameter.


PRINT 'The size of the largest single order was: ' +
CONVERT(CHAR(6), @LargestOrder)
PRINT 'The sum of the quantities ordered was: ' +
CONVERT(CHAR(6), @OrderSum)
GO
The output from running this sample is:
EmployeeID SummSales
----------- --------------------------
1 202,143.71
2 177,749.26
3 213,051.30
4 250,187.45
5 75,567.75
6 78,198.10
7 141,295.99
8 133,301.03
9 82,964.00
The size of the largest single order was: 130
The sum of the quantities ordered was: 51317

Which of these is a CSS pseudo class? A) .abc { color:green; } B) a:visited { color:green; } C) h1 h2


{ color:green; }
Posted by: Ddd
NOTE: This is objective type question, Please click question title for correct answer.

Is CSS case Sensitive?


Posted by: Peermohamedmydeen
1. CSS is not case sensitive.

2. But some browsers taking CSS as case sensitive, where there may be the use of XML document and
XHTML doctypes.

3. It is better practice to avoid CSS classes with same name, where the only difference is case.

4.Parts that are not under control of CSS like font family names and URLs can be case sensitive -
IMAGE.gif and image.gif is not the same file.

In HTML attributes, CSS properties which one take precedence over another?
Posted by: Peermohamedmydeen
CSS properties always take precedence over HTML attributes. If both are specified, HTML attributes will
be displayed in browsers without CSS support, but won't have any effect in browsers with CSS support.

What are pseudo-elements?


Posted by: Chikul
Pseudo-elements are fictional elements that do not exist in HTML. They address the element's sub-part
(non-existent in HTML) and not the element itself. In CSS1 there are two pseudo-elements: 'first-line
pseudo-element' and 'first-letter pseudo-element'. They can be attached to block-level elements (e.g.
paragraphs or headings) to allow typographical styling of their sub-parts. Pseudo-element is created by a
colon followed by pseudo-element's name, e.g:

P:first-line
H1:first-letter

and can be combined with normal classes; e.g:


P.initial:first-line

First-line pseudo-element allows sub-parting the element's first line and attaching specific style
exclusively to this sub-part; e.g.:

P.initial:first-line {text-transform: uppercase}

<P class=initial>The first line of this paragraph will be displayed in uppercase letters</P>

First-letter pseudo-element allows sub-parting the element's first letter and attaching specific style
exclusively to this sub-part; e.g.:

P.initial:first-letter { font-size: 200%; color: red}

<P class=initial>The first letter of this paragraph will be displayed in red and twice as large as the
remaining letters</P>

What is contextual selector?


Posted by: Chikul
Contextual selector is a selector that addresses specific occurrence of an element. It is a string of
individual selectors separated by white space, a search pattern, where only the last element in the pattern
is addressed providing it matches the specified context.

TD P CODE {color: red}

The element CODE will be displayed in red but only if it occurs in the context of the element P which must
occur in the context of the element TD.

TD P CODE, H1 EM {color: red}

The element CODE will be displayed in red as described above AND the element EM will also be red but
only if it occurs in the context of H1

P .footnote {color: red}

Any element with CLASS footnote will be red but only if it occurs in the context of P

P .footnote [lang]{color: red}

Any element with attribute LANG will be red but only if it is classed as "footnote" and occurs in the context
of P

What is ID selector?
Posted by: Chikul
ID selector is an individually identified (named) selector to which a specific style is declared. Using the ID
attribute the declared style can then be associated with one and only one HTML element per document
as to differentiate it from all other elements. ID selectors are created by a character # followed by the
selector's name. The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped
characters, Unicode characters 161-255, as well as any Unicode character as a numeric code, however,
they cannot start with a dash or a digit.

#abc123 {color: red; background: black}

<P ID=abc123>This and only this element can be identified as abc123 </P>

What is CSS rule 'ruleset'?


Posted by: Chikul
There are two types of CSS rules: ruleset and at-rule. Ruleset identifies selector or selectors and declares
style which is to be attached to that selector or selectors. For example P {text-indent: 10pt} is a CSS rule.
CSS rulesets consist of two parts: selector, e.g. P and declaration, e.g. {text-indent: 10pt}.

P {text-indent: 10pt} - CSS rule (ruleset)


{text-indent: 10pt} - CSS declaration
text-indent - CSS property
10pt - CSS value

What is embedded style? How to link?


Posted by: Chikul
The HEAD area, where the TITLE and META tags are found, is also used to store CSS commands.
These are called embedded CSS. Any embedded CSS command will over-ride an external CSS
command of the same tag. Embedded commands are more specific to the page.

Embedded CSS codes are placed within the HEAD area of the page code. That is anywhere after the
<HEAD> tag and before the </HEAD> tag. NOT in the HEAD tag itself.

<style type="text/css" media=screen>


<!--
p {font-family: georgia, serif; font-size: x-small;}
hr {color: #ff9900; height: 1px }
a:hover {color: #ff0000; text-decoration: none}
-->
</style>

Now, whenever any of those elements are used within the body of the document, they will be formatted
as instructed in the above style sheet.

CSS Interview Questions

1) What are cascading style sheets?


Cascading style sheets help the designer in various ways. It primarily helps to design style sheets for
content and HTML pages. It can be applied to any XML document or mark up language.
2) Explain about some of the features of CSS?
Some of the features used by CSS are to define a layout, colors, fonts, etc. It separates the content from
the design part which makes the content much more visible thereby improving productivity of the entire
process. It can make the same page appear in different formats.
3) Explain about the rules present in style sheets?
A huge list of rules is defined for style sheets. Each rule consists of selectors and declaration block. A
declaration block consists of declarations which can be defined and separated by using a semicolon
within curly braces. Also each declaration consists of a colon, a property and a semicolon.
4) Explain about the hover element?
A hover element is activated when the user moves a pointer over the area where HTML coding is defined.
This style is being extensively used for online advertising. It is appended to #elementid:hover.
5) State some of the uses of CSS?
CSS offers many possibilities to a designer and developer. Some of them are
1) Moving of the entire style sheet coding to a separate external folder.
2) Repetition and code reuse features make CSS rich.
3) Presentation and structure are made different by CSS etc.
6) State the different type of author styles?
A web page author, developer, designer, etc can describe styles in three different forms they are
1) External style sheets
2) Embedded style
3) Inline styles
4) Local and default style sheet.
A default style sheet consists of the style imparted by the browser which the user is accessing for the
information.
7) What are the main goals of applying style sheets?
The main use of style sheet is to give the user a greater degree of control over his presentation. If the
user does not like a certain font he can change it with flexibility without any difficulty.
Also a developer can minimize the effects which a browser can have on the application or the text part of
the webpage.
Control over the entire web page without any external influences, separation of the page from the HTML
code part.
8) Explain about CSS1?
W3C recommended adoption of CSS1in 1996. Some of the capabilities and features present in CSS1 are
as follows.
1) Font properties
2) Background colors, text colors, etc
3) Spacing between text, words, etc
4) Tables, images alignment
5) Border, margin, padding and positioning of elements
6) Attributes are uniquely identified and classified generically.
W3C still adopts the specifications put forwarded in CSS1.
9) What are the additional features which were present in CSS2 compared to CSS1?
Many of the new features were present in CSS2 some of them are as follows.
1) Positioning of elements will be according to the relative, fixed and the absolute positioning.
2) Inclusion of large number of media functions.
3) Shadows, bidirectional support for text and aural style sheets.

10) Explain about CSS filter?


CSS filter solves designers and coders difficulties. With the help of these filters one can write entirely
different code or modify the existing design patterns so that browsers receive CSS specifications which
they support, thereby not allowing the browsers to make or create any unnecessary changes.
11) Explain about Internet explorer box model bug?
Designers had a very tough time dealing with this bug, because it will not display box widths appropriately
on the webpage. It displayed the block to be narrow in size. This bug can be rectified by using CSS filter
and hacks. Also correct usage and documentation of XHTML can solve the problems.
12) Explain about vertical control limitation?
Vertical control limitations are always a nightmare for a designer. Horizontal positioning of text or element
is always easy but vertically positioning an element always leads to convoluted and impossible tasks.
CSS has unsupported rules for vertical placement of elements.
13) Explain about absence of expressions?
CSS currently does not have the ability to specify property values as simple expressions. For example if
you want to calculate the size of all the columns but you have a restriction on the sum of all columns. This
problem has been solved by many browsers by proprietary expressions which did the job well.
14) Explain about lack of orthogonality?
Lack of orthogonality explains about the various multiple jobs which are either undefined correctly for a
specific application or used multiple times for the same job. CSS defines that internal elements of a table
will not have margins so usage of border spacing is appropriate which leads to confusion.
15) Explain about the ease of maintenance with CSS.
An effective style sheet has effective use of inheritance and cascading style sheets. When changes are
applied to a single element of this global style sheet every element of the web page changes. This made
the maintenance easy because here we can change the style of the whole page by effecting a change to
a single element.

16) Explain about float containment?


CSS does not support float elements as it can cause overflow of the elements. Floats also tend to vary
according to the web browser resolution and size but positions do not. There are some multiple properties
which can define about float but they have their own limitations.
17) State some limitations of style sheets?
Style sheets do have its own share of limitations some of them are as follows: -
1) Inconsistent browser support
2) Vertical control limitations
3) Margin collapsing, float containment, control of element shapes, etc
4) Lack of column declaration and variables are some of the limitations present in CSS.

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 >

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for
responding to application-level and session-level events raised by ASP.NET or by HTTPModule.If you
remember it's same as global.asa in ASP. The Global.asax file resides in the root directory of an
ASP.NET application. At run time, Global.asax is parsed and compiled into a dynamically generated .NET
Framework class derived from the HttpApplication base class. ASP.NET is configured so that any direct
URL request for the Global.asax file is automatically rejected.

The HTTPApplication class exposes the following events for you to handle.

AcquireRequestState
AuthenticateRequest
AuthorizeRequest
BeginRequest
EndRequest
Error
PostRequestHandlerExecute
PreRequestHandlerExecute
PreSendRequestContent
PreSendRequestHeaders
ReleaseRequestState
ResolveRequestCache
UpdateRequestCache

6. How to read and write a file using javascript?


I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be
done by coding a Java applet that reads files for the script.
5. How do we get JavaScript onto a web page?
You can use several different methods of placing javascript in you pages.
You can directly add a script element inside the body of page.
1. For example, to add the "last updated line" to your pages, In your page text, add the following:
<p>blah, blah, blah, blah, blah.</p>
<script type="text/javascript" >
<!-- Hiding from old browsers
document.write("Last Updated:" +
document.lastModified);
document.close();
// -->
</script>
<p>yada, yada, yada.</p>

(Note: the first comment, "<--" hides the content of the script from browsers that don't understand
javascript. The "// -->" finishes the comment. The "//" tells javascript that this is a comment so javascript
doesn't try to interpret the "-->". If your audience has much older browsers, you should put this comments
inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For
brevity, in most examples here the comments are not shown. )
The above code will look like this on Javascript enabled browsers,
2. Javascript can be placed inside the <head> element
Functions and global variables typically reside inside the <head> element.
<head>
<title>Default Test Page</title>
<script language="JavaScript" type="text/javascript">
var myVar = "";
function timer(){setTimeout('restart()',10);}
document.onload=timer();
</script>
</head>

3. Javascript can be referenced from a separate file


Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don't
use the shorthand ending "<script ... />). These are typically placed in the <head> element.
<script type="text/javascript" SRC="myStuff.js"></script>

7. How to detect the operating system on the client machine?


In order to detect the operating system on the client machine, the navigator.appVersion
string (property) should be used.

10. What are JavaScript types?


Number, String, Boolean, Function, Object, Null, Undefined.

12. How to create arrays in JavaScript?


We can declare an array like this
var scripts = new Array();
We can add elements to this array like this

scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";

document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);

13. How do you target a specific frame from a hyperlink?


Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm”
target=”myframe”>>My Page</a>
14. What is a fixed-width table and its advantages?
Fixed width tables are rendered by the browser based on the widths of the columns in the first row,
resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed
width table.
If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then
infer the best width for each of the columns. This process can be very slow for large tables
15. Example of using Regular Expressions for syntax checking in JavaScript
var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");
var text = myWidget.value;
var OK = re.test(text);
if( ! OK ) {
alert("The extra parameters need some work.\r\n Should be something like: \"&a=1&c=4\"");
}

How to add Buttons in JavaScript?


function displayHero(button) {
alert("Your hero is \""+button.value+"\".");
}
</script>

<form action="" name="buttonsGalore" method="get">


<fieldset style="margin: 1em; text-align: center;">
<legend>Select a Hero</legend>
<input type="button" value="Agamemnon" onclick="displayHero(this)" />
<input type="button" value="Achilles" onclick="displayHero(this)" />
<input type="button" value="Hector" onclick="displayHero(this)" />
<div style="height: 1em;" />
</fieldset>
</form>

17. Where are cookies actually stored on the hard disk?


This depends on the user's browser and OS.
In the case of Netscape with Windows OS,all the cookies are stored in a single file called

cookies.txt
c:\Program Files\Netscape\Users\username\cookies.txt
In the case of IE,each cookie is stored in a separate file namely username@website.txt.
c:\Windows\Cookies\username@Website.tx

19. How to set a HTML document's background color?


document.bgcolor property can be set to any appropriate color.

23. What is negative infinity?


It’s a number in JavaScript, derived by dividing negative number by zero.

24. In a pop-up browser window, how do you refer to the main browser window that opened it?
Use window.opener to refer to the main window from pop-ups
.
26. Methods GET and POST in HTML forms - what's the difference?.
GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET
method is limited to about 2kb.
POST: Parameters are passed in the request body. There is no limit to the amount of data that can be
transferred using POST. However, there are limits on the maximum amount of data that can be
transferred in one name/value pair.

35. What boolean operators does JavaScript support?


&&, || and !

36. What does "1"+2+4 evaluate to?


Since 1 is a string, everything is a string, so the result is 124.
37. What are the ways to emit client-side JavaScript from server-side code in ASP.NET?
The Page object in ASP.NET has two methods that allow emitting of client-side JavaScript:
RegisterClientScriptBlock and RegisterStartupScript.

40. How to get the contents of an input box using Javascript?


Use the "value" property.
var myValue = window.document.getElementById("MyTextBox").value;

41. How to determine the state of a checkbox using Javascript?


var checkedP = window.document.getElementById("myCheckBox").checked;

42. How to set the focus in an element using Javascript?


<script> function setFocus() { if(focusElement != null)
{ document.forms[0].elements["myelementname"].focus(); } } </script>

43. How to access an external javascript file that is stored externally and not embedded?
This can be achieved by using the following tag between head tags or between body tags.
<script src="abc.js"></script>How to access an external javascript file that is stored externally and not
embedded? where abc.js is the external javscript file to be accessed.

45. What is a prompt box?


A prompt box allows the user to enter input by providing a text box.

49. How about 2+5+"8"?


Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the
result.

50. What is the difference between SessionState and ViewState?


ViewState is specific to a page in a session. Session state refers to user specific data that can be
accessed across all pages in the web application.

51. What does the EnableViewStateMac setting in an aspx page do?


Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the
viewstate for a page has not been tampered with. If on Postback, the ASP.NET framework detects that
there has been a change in the value of viewstate that was sent to the browser, it raises an error -
Validation of viewstate MAC failed.
Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not
specified is also true) in an aspx page.

52. How to Accessing Elements using javascript?


To do something interesting with HTML elements, we must first be able to uniquely identify which element
we want. In the example
<body>
<form action="">
<input type="button" id="useless" name="mybutton" value="doNothing" />
</form>
</body>

We can use the "getElementById" method (which is generally preferred)


document.getElementById("useless").style.color = "red";
or we can use the older hierarchical navigation method,
document.forms[0].mybutton.style.color = "blue";
Notice that this uses the "name" attribute of the element to locate it.
# Example of Accessing Elements in a DOM.
<script type="text/javascript" >
function showStatus() {
var selectWidget = document.forms.beerForm.elements["beer"];
var myValue = selectWidget.options[selectWidget.selectedIndex].value;
alert('You drank a \"'+ myValue +"\"");
return true;
}
</script>

<form name="beerForm" action="">


<select name="beer">
<option selected="selected">Select Beer</option>
<option>Heineken</option>
<option>Amstel Light</option>
<option>Corona</option>
<option>Corona Light</option>
<option>Tecate</option>
</select>

<input type="button" name="submitbutton" value="Drink"


onclick="showStatus()" />
</form

53. What looping structures are there in JavaScript?


for, while, do-while loops, but no foreach.

<script language=javascript> <!-- javascript code goes here // --> or Use the <NOSCRIPT>some html
code </NOSCRIPT>

56. How to comment javascript code?


Use // for line comments and /* */ for block comments

57. Name the numeric constants representing max,min values


Number.MAX_VALUE
Number.MIN_VALUE

59. How do you create a new object in JavaScript?


var obj = new Object(); or var obj = {};

60. How do you assign object properties?


obj["age"] = 17 or obj.age = 17.

61. What’s a way to append a value to an array?


arr[arr.length] = value;

65. To set all checkboxes to true using JavaScript?


//select all input tags
function SelectAll() {
var checkboxes = document.getElementsByTagName("input");
for(i=0;i<checkboxes.length;i++) {
if(checkboxes.item(i).attributes["type"].value == "checkbox") {
checkboxes.item(i).checked = true;

67. What does undefined value mean in javascript?


Undefined value means the variable used in the code doesnt exist or is not assigned any value or the
property doesnt exist.
72. What is === operator ?
==== is strict equality operator ,it returns true only when the two operands are having the same value
without any type conversion.

73. How to find the selected radio button immediately using the 'this' variable?
<script>
function favAnimal(button) {
alert('You like '+button.value+'s.');
}.....<input type="radio" name="marsupial" value="Tasmanian Tiger"
onchange="favAnimal(this)">Tasmanian Tiger

75. How to disable an HTML object


document.getElementById("myObject").disabled = true;

76. To write messages to the screen without using "document.write()" ?


Changing the contents of an element is a much better solution. When the method showStatus is invoked
it will change the content of the span.
...
function showStatus(message) {
var element = document.getElementById("mystatus");
element.textContent = message; //for Firefox
element.innerHTML = message; //for IE (why can't we all just get along?)
return true;
}
...
<span id="mystatus">Test. </span>

78. How to Add new elements dynamically.


var newP = document.createElement("p");
var textNode = document.createTextNode(" I'm a new text node");
newP.appendChild(textNode);

82. How to create a confirmation box?


confirm("Do you really want to launch the missile?");

83. How to create an input box?


prompt("What is your temperature?");

84. How to open a window with no toolbar, but with the location object.
window.open("http://www.mysite.org/Misc/Pennies","Pennies","resizable=yes,
status=yes,toolbar=yes,location=yes,menubar=yes,scrollbars=yes,width=800,height=400"

/Sets cookie of current value for myTextBox


function TextBoxOnchange() {
var myBox = window.document.getElementById(myTextBox");
document.cookie = "myTextBox="+ escape(myBox.value) + getExpirationString();

89. How to change style on an element?


Between CSS and javascript is a weird symmetry. CSS style rules are layed on top of the DOM. The CSS
property names like "font-weight" are transliterated into "myElement.style.fontWeight". The class of an
element can be swapped out. For example:
document.getElementById("myText").style.color = "green";
document.getElementById("myText").style.fontSize = "20";
-or-
document.getElementById("myText").className = "regular";
90. How to make elements invisible
Change the "visibility" attribute of the style object associated with your element. Remember that a hidden
element still takes up space, use "display" to make the space disappear as well.

if ( x == y) {
myElement.style.visibility = 'visible';
} else {
myElement.style.visibility = 'hidden';
}

91. How to set the cursor to wait.


In theory, we should cache the current state of the cursor and then put it back to its original state.
document.body.style.cursor = 'wait';
//do something interesting and time consuming
document.body.style.cursor = 'auto';

92. How to reload the current page


window.location.reload(true);

93. how to force a page to go to another page using JavaScript?


<script language="JavaScript" type="text/javascript" ><!--
location.href="http://newhost/newpath/newfile.html"; //--></script>

7. What's Math Constants and Functions using JavaScript?


The Math object contains useful constants such as Math.PI, Math.E
Math also has a zillion helpful functions.
Math.abs(value); //absolute value
Math.max(value1, value2); //find the largest
Math.random() //generate a decimal number between 0 and 1
Math.floor(Math.random()*101) //generate a decimal number between 0 and 100

98. What's the Date object using JavaScript?


Time inside a date object is stored as milliseconds since Jan 1, 1970.
new Date(06,01,02) // produces "Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)"
new Date(06,01,02).toLocaleString() // produces "Friday, February 02, 1906 00:00:00"
new Date(06,01,02) - new Date(06,01,01) // produces "86400000"

99. What does the delete operator do?


The delete operator is used to delete all the variables and objects used in the program ,but it does not
delete variables declared with var keyword.

103. How to use "join()" to create a string from an array using JavaScript?
"join" concatenates the array elements with a specified seperator between them.

<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("days:"+days.join(","));
</script>
This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday

108. eval()?
The eval() method is incredibly powerful allowing you to execute snippets of code during exection.

<script type="text/javascript">
var USA_Texas_Austin = "521,289";
document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));
</script>
This produces
Population is 521,289

109. What does break and continue statements do?


Continue statement continues the current loop (if label not specified) in a new iteration whereas break
statement exits the current loop.

110. How to create a function using function constructor?


The following example illustrates this
It creates a function called square with argument x and returns x multiplied by itself.
var square = new Function ("x","return x*x");
General Questions – 01
August 5, 2006
Does C# support multiple-inheritance?
No.
Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).
Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they
are inherited.
Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the specified base class.
What’s the top .NET class that everything is derived from?
System.Object.
What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original
immutable data value was discarded and a new data value was created in memory.
What’s the difference between System.String and System.Text.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.
What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are
immutable, so each time a string is changed, a new instance in memory is created.
Can you store multiple data types in System.Array?
No.
What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original
array. The CopyTo() method copies the elements into another existing array. Both perform a shallow
copy. A shallow copy means the contents (each array element) contains references to the same object
as the elements in the original array. A deep copy (which neither of these methods performs) would
create a new instance of each element’s object, resulting in a different, yet identacle object.
How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.
What class is underneath the SortedList class?
A sorted HashTable.
Will the finally block get executed if an exception has not occurred?
Yes.
What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter
data type in this case and just write catch {}.
Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block (if there are any).
Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).

Basic .NET, C#.NET, ASP.NET interview questions


What is an AppDomain? What is a process? What is thread? What is the difference between AppDomain
and process?
Process: A computer program is a set of instructions. Operating system executes a computer program by
allocating a process for a program. Several processes may be associated with the execution of a single
program. A process is an instance of machine code associated with a program. It has memory for
instructions, data, a call stack and a heap

AppDomain: An AppDomain is a light-weight process which separates one application in .NET with
another. CLR creates an AppDomain when an application is loaded. Each application will have an
AppDomain associated. Each AppDomain can have different threads running in it. Each app domain will
have its associated code, data and configuration. Hence when one application crashes, it does not affect
other.

Thread: Each process can have multiple threads. Multiple threads can share same execution code and
resources. A multi-threaded process can perform several tasks concurrently.

What is a runtime host?

.NET framework supports different type of applications like Web, windows, console etc,. Each type of
application needs a runtime host to start it. This runtime host loads the runtime into a process, creates the
application with in the process and loads the application code into the process.

Runtime hosts included in .NET framework are

ASP.NET: It loads the runtime that can handle a web request into the process. ASP.NET also creates an
application domain for each Web application that will run on a Web server.

Microsoft Internet Explorer: It creates an application domain to run managed controls.

Shell executables: When ever a runtime executable is launched from the shell, this executable invokes
the corresponding runtime host.

What is the difference between manageable and unmanageable code?

Code which targets the .NET framework CLR is manageable meaning CLR can provide its services like
type safety, memory management, exceptional handling etc to this type of code. Managed code is always
compiled into MSIL. When a .NET application is run this compiled MSIL is compiled to native code using
JIT (Just In Time compiler). This JIT generates the native code as per the hardware specification on the
system. Since all this process happens under the control of a managed environment CLR, CLR provides
all its rich functionality. Managed code provides platform independence since the code is converted to
MSIL and then converted to native code depending on the system architecture.

The code that does not target CLR is unmanageable. It cannot run under CLR. This code directly runs
under OS control. Applications written in traditional applications like C++, VB, C generate unmanaged
code. This targets the computer architecture. Unmanaged code is always compiled to target a specific
architecture and will only run on the intended platform. This means that if you want to run the same code
on different architecture then you will have to recompile the code using that particular architecture.
Unmanaged code is always compiled directly to the native code which is architecture specific. This code
cannot be executed on other platforms that are different than the one on which the code was compiled. All
the features provided by CLR are unavailable and are to be taken care by the code. Hence this causes
memory leaks in traditional applications.

ExplainValue and reference types?

“System.Object” is the base class from all the .NET classes.

Value types: Value types inherit from the System.ValueType class, which in turn, inherits from
System.Object. Value types are stored on stack. They are implicitly sealed. Structs and Enumerations are
value types and they are always stored on stack. A value type cannot contain a null value. Variables that
are value types store data.

Reference types: Variables to reference types referred to as object, store reference to actual data. Actual
data is stored on the heap and reference is stored on the stack. This allows the garbage collector to track
outstanding references to a particular instance and free the instance when no references remain.

Integral types : sbyte, byte, char, short, ushort, int, uint, long, ulong
Floating Point types: float, double
Decimal types: decimal

What is the role of garbage collector in .NET?

Objects created are stored on heap. Since the memory (here heap) is exhaustible, .NET identifies a
mechanism to collect the unused memory(heap). GC does an automatic sweep of heap once it is full. GC
can only destroy managed objects.

GC will finalize all the objects in the memory that are not being used anymore and thereby freeing the
memory allocated to them.
.NET uses a three-generation approach to collecting memory. Newly allocated memory tends to be freed
more frequently than older allocations, which tend to be more permanent. Gen 0 (Zero) is the youngest
generation and, after a garbage collection, any survivors go on to Gen 1. Likewise, any survivors of a Gen
1 collection go on to Gen 2. Usually garbage collection will occur only on Gen 0, and only if after it has
reached some limit. Until memory is exhausted, the cost of allocating each new object is that of
incrementing a pointer--which is close to the performance of advancing the stack pointer.

CLR calls the GC when there is a high memory pressure and it is not able to find any exact place to
allocate a new object or the applied threshold is reached.

Can you force Garbage collection if so how?

In applications with significant memory requirements, you can force garbage collection by invoking the
GC.Collect method from the program.

What is CLR?

CLR is a runtime environment provided by .NET framework.


Developers write code in either C# or VB.NET.
.NET compilers convert this high level code into Microsoft Intermediate Language(MSIL). At runtime JIT
compiler converts the MSIL into native code specific to the OS. CLR runs MSIL.
CLR provides memory management, exceptional handling, security etc to the .NET code.

Explain CLS and CTS?

CLS: Common Language specification is a set of rules that are to be followed by a language in order to
be .NET complaint. This facilitates cross-language integration. Programs written in one .NET language
can interoperate with programs written in another .NET language.

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

What is Type safety in .NET?


Type-safe code accesses only the memory locations it is authorized to access. For example, type-safe
code cannot read values from another object's private fields. It accesses types only in well-defined,
allowable ways. If we want to work directly with memory addresses and can manipulate bytes at these
addresses then we have to declare that code chunk as unsafe using the unsafe Keyword in C#. So that
CLR will not do any extra verification on this code.

Actually during just-in-time (JIT) compilation, an optional verification process examines the metadata and
Microsoft intermediate language (MSIL) of a method to be JIT-compiled into native machine code to verify
that they are type safe. This process is skipped if the code has permission to bypass verification. For
example, the runtime cannot prevent unmanaged code from calling into native (unmanaged) code and
performing malicious operations. When code is type safe, the runtime's security enforcement mechanism
ensures that it does not access native code unless it has permission to do so. All code that is not type
safe must have been granted Security Permission with the passed enum member SkipVerification to run.

What is an assembly?
An assembly is a basic building block for an application. It can be a DLL or EXE. An assembly contains
IL. It consists of metadata about the types inside the assembly.

What do I need to create and run an ASP.NET application?


Windows 2000, Windows Server 2003 or Windows XP.
ASP.NET, which can be either the redistributable (included in the .NET SDK) or Visual Studio .NET.
Where can I download the .NET SDK?
.NET SDK can be obtained here.

(You have to install the Microsoft .NET Framework Version 1.1 Redistributable Package before installing
the .NET SDK.)

Are there any free IDEs for the .NET SDK?


Microsoft provides Visual Studio 2005 Express Edition Beta for free. Of particular interest to the ASP.NET
developers would be the Visual Web Developer 2005 Express Edition Beta 2 available as a free
download.
The ASP.NET Web Matrix Project (supported by Microsoft) is a free IDE for developing ASP.NET
applications and is available here.
There is also a free open-source UNIX version of the Microsoft .NET development platform called Mono
available for download here.
Another increasingly popular Open Source Development Environment for .NET is the #develop (short for
SharpDevelop) available for download here.
When was ASP.NET released?
ASP.NET is a part of the .NET framework which was released as a software platform in 2002.

Is a new version coming up?


ASP.NET 2.0, Visual Studio 2005 (Whidbey), Visual Web Developer 2005 Express Edition are the next
releases of Microsoft's Web platform and tools. They have already been released as Beta versions. They
are scheduled to be released in the week of November 7, 2005.

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.

List the types of Authentication supported by ASP.NET.


Windows (default)
Forms
Passport
None (Security disabled)
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).

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

List the various stages of Page-Load lifecycle.


Init()
Load()
PreRender()
Unload()
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.

What is Shadow Copy?


In order to replace a COM component on a live dedicated 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.

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.

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.

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.

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

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.

Enumerate the types of Directives.


@ Page directive
@ Import directive
@ Implements directive
@ Register directive
@ Assembly directive
@ OutputCache directive
@ Reference directive
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.

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.

List the ASP.NET validation controls?


RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
ValidationSummary
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.

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.

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.

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.
Questions to ask a SQL Server database developer applicant
October 16, 2006, 5:19pm PDT
Recommend
0
Votes
23
Comments
Share

more +
It is very difficult in today's job market to find well-qualified database developers. As a colleague of mine
once said, "SQL development is a language that is easy to learn, but very difficult to master."

When I interview SQL Server database developer candidates, I use a standard set of baseline technical
questions. The following questions are ones that I find can really help weed out less-qualified candidates.
They are listed in order from easiest to more difficult. When you get to the question about primary and
foreign keys, it starts to get challenging because the answers can be more difficult to explain and
articulate, especially in an interview setting.

Can you give me an overview of some of the database objects available for use in SQL Server 2000?

You are looking for objects such as: tables, views, user-defined functions, and stored procedures; it's
even better if they mention additional objects such as triggers. It's not a good sign if an applicant cannot
answer this basic question.

What is an index? What types of indexes are available in SQL Server 2000?

Any experienced database developer should be able to answer this question with ease. Some of the less-
experienced developers will be able to answer it, but with a little less clarity.

Weekly SQL tips in your inbox


TechRepublic's free SQL Server newsletter, delivered each Tuesday, contains hands-on tips that will help
you become more adept with this powerful relational database management system.
Automatically sign up today!
In its most simple terms, an index is a data structure used to provide quick access to data in a database
table or view. In SQL Server, they come in two flavors: clustered and non-clustered. Clustered indexes
store the data at the leaf level of the index. This means that whichever field(s) in your table are included in
the clustered index, they will be stored in an orderly fashion in the table. Because of this sorting, you can
only have one clustered index per table. Non-clustered indexes contain a row identifier at the leaf level of
the index. This row identifier is a pointer to a location of the data on the disk. This allows you to have
more than one non-clustered index per table.

What does NULL mean?

The value NULL is a very tricky subject in the database world, so don't be surprised if several applicants
trip up on this question.

The value NULL means UNKNOWN; it does not mean '' (empty string). Assuming ANSI_NULLS are on in
your SQL Server database, which they are by default, any comparison to the value NULL will yield the
value NULL. You cannot compare any value with an UNKNOWN value and logically expect to get an
answer. You must use the IS NULL operator instead.

What is a primary key? What is a foreign key?

A primary key is the field(s) in a table that uniquely defines the row in the table; the values in the primary
key are always unique. A foreign key is a constraint that establishes a relationship between two tables.
This relationship typically involves the primary key field(s) from one table with an adjoining set of field(s)
in another table (although it could be the same table). The adjoining field(s) is the foreign key.

What are triggers? What are the different types of triggers in SQL Server 2000?

It's very beneficial for a potential database developer to know the types of triggers available, and how to
implement them.

A trigger is a specialized type of stored procedure that is bound to a table or view in SQL Server 2000. In
SQL Server 2000, there are INSTEAD-OF triggers and AFTER triggers. INSTEAD-OF triggers are
procedures that execute in place of a Data Manipulation Language (DML) statement on a table. For
example, if I have an INSTEAD-OF-UPDATE trigger on TableA, and I execute an update statement on
that table, the code in the INSTEAD-OF-UPDATE trigger will execute instead of the update statement that
I executed.

An AFTER trigger executes after a DML statement has taken place in the database. These types of
triggers are very handy for auditing data changes that have occurred in your database tables.

How can you ensure that a table named TableB with a field named Fld1 will only have those values in the
Fld1 field that are also in the table named TableA with a field named Fld1?

This relationship related question has two potential answers. The first answer (and the one that you want
to hear) is the use of foreign key constraints. A foreign key constraint is used to maintain referential
integrity. It is used to ensure that a field in a table will only hold values that are already defined in another
field in a different (or the same) table. That field is the candidate key (usually a primary key of the other
table).

The other option is the use of triggers. Triggers can be used to ensure the same effect of constraints in a
roundabout way, but it is much more difficult to set up and maintain, and the performance is typically
worse. Because of this, Microsoft recommends that developers use foreign key constraints instead of
triggers for maintaining referential integrity.

What is a performance consideration of having too many indexes on a production online transaction
processing (OLTP) table?

You are looking for the applicant to make some reference regarding data manipulations. The more
indexes on a table, the more time it takes for the database engine to update, insert, or delete data, as the
indexes all have to be maintained as the data manipulation occurs.

What can be used to ensure that a field in a table only accepts a certain range of values?

This question can be answered a couple of different ways, but only one answer is a "good" one. The
answer you want to hear is a Check constraint, which is defined on a database table that limits the values
entered into that column. These constraints are relatively easy to create, and they are the recommended
type for enforcing domain integrity in SQL Server.

Triggers can also be used to restrict the values accepted in a field in a database table, but this solution
requires the trigger to be defined on the table, which can hinder performance in certain situations. For this
reason, Microsoft recommends Check constraints over all other methods for restricting domain integrity.

What is the difference between a return parameter and an OUTPUT parameter?

If the applicant is able to answer this question correctly, the odds are good that they have some
experience working with stored procedures.
A return parameter is always returned by a stored procedure, and it is meant to indicate the success or
failure of the stored procedure. The return parameter is always an INT data type.

An OUTPUT parameter is designated specifically by the developer, and it can return other types of data,
such as characters and numeric values. (There are some limitations on the data types that can be used
as output parameters.) You can use multiple OUTPUT parameters in a stored procedure, whereas you
can only use one return parameter.

What is a correlated sub-query? How can these queries be useful?

The more seasoned developer will be able to accurately describe this type of query.

A correlated sub-query is a special type of query containing a sub-query. The sub-query contained in the
query actually requests values from the outside query, creating a situation similar to a loop. You can find
a more detailed description as to how these special types of queries work in this article.

Here are some SQL Server DBA/Developer interview questions I faced myself personally and/or heard
from people. I will try to answer these questions briefly here, but be advised that these answers may not
be complete and it will be better for you to go through text books, books online and other resources on the
net. At the end of this article, I listed some useful books for aspiring DBAs and developers.

Before you go for the interview, be prepared to explain the database design of one of your latest projects.
Don't be surprised if the interviewer asks you to draw ER diagrams.

Well, here are some questions for you. Hope this helps you prepare for your interview. Wish you all the
best in your job hunt! Feel free to email me 'interview questions' that you've faced.

Questions are categorized under the following sections, for your convenience:

Database design (8 questions)


SQL Server architecture (12 questions)
Database administration (13 questions)
Database programming (10 questions)
Database design (top)
What is normalization? Explain different levels of normalization?
Check out the article Q100139 from Microsoft knowledge base and of course, there's much more
information available in the net. It'll be a good idea to get a hold of any RDBMS fundamentals text book,
especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.

What is denormalization and when would you go for it?


As the name indicates, denormalization is the reverse process of normalization. It's the controlled
introduction of redundancy in to the database design. It helps improve the query performance as the
number of joins could be reduced.

How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and
foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and
foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table.

It will be a good idea to read up a database designing fundamentals text book.

What's the difference between a primary key and a unique key?


Both primary key and unique enforce uniqueness of the column on which they are defined. But by default
primary key creates a clustered index on the column, where are unique creates a nonclustered index by
default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one
NULL only.

What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name,
and format to the database. Take for example, in your database, there is a column called Flight_Num
which appears in many tables. In all these tables it should be varchar(8). In this case you could create a
user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.

See sp_addtype, sp_droptype in books online.

What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit
datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards,
bit datatype can represent a third state, which is NULL.

Define candidate key, alternate key, composite key.


A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes
the primary key of the table. If the table has more than one candidate key, one of them will become the
primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

What are defaults? Is there a column to which a default can't be bound?


A default is a value that will be used by a column, if no value is supplied to that column while inserting
data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE
DEFUALT in books online.

Back to top

SQL Server architecture (top)


What is a transaction and what are ACID properties?
A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for
Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more
information and explanation of these properties, see SQL Server books online or any RDBMS
fundamentals text book.

Explain different isolation levels


An isolation level determines the degree of isolation of data between concurrent transactions. The default
SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order
of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server
books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION
ISOLATION LEVEL, which lets you customize the isolation level at the connection level.

CREATE INDEX myIndex ON myTable(myColumn)

What type of Index will get created after executing the above statement?
Non-clustered index. Important thing to note: By default a clustered index gets created on the primary
key, unless specified otherwise.

What's the maximum size of a row?


8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'.
Check out SQL Server books online for the page titled: "Maximum Capacity Specifications".
Explain Active/Active and Active/Passive cluster configurations
Hopefully you have experience setting up cluster servers. But if you don't, at least be familiar with the way
clustering works and the two clusterning configurations Active/Active and Active/Passive. SQL Server
books online has enough information on this topic and there is a good white paper available on Microsoft
site.

Explain the architecture of SQL Server


This is a very important question and you better be able to answer it if consider yourself a DBA. SQL
Server books online is the best place to read about SQL Server architecture. Read up the chapter
dedicated to SQL Server Architecture.

What is lock escalation?


Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher
level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory
being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks
to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL
Server 7.0 onwards it's dynamically managed by SQL Server.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log,
which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion
of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of
course, TRUNCATE TABLE can be rolled back.

Explain the storage models of OLAP


Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more infomation.

What are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time
of your interview)? What changed between the previous version of SQL Server and the current version?
This question is generally asked to see how current is your knowledge. Generally there is a section in the
beginning of the books online titled "What's New", which has all such information. Of course, reading just
that is not enough, you should have tried those things to better answer the questions. Also check out the
section titled "Backward Compatibility" in books online which talks about the changes that have taken
place in the new version.

What are constraints? Explain different types of constraints.


Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to
create triggers, rule or defaults.

Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

For an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE
TABLE", "ALTER TABLE"

Whar is an index? What are the types of indexes? How many clustered indexes can be created on a
table? I create a separate index on each column of a table. what are the advantages and disadvantages
of this approach?
Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data
quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered
index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can
be only one clustered index per table. Non-clustered indexes have their own storage separate from the
table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with
the leaf level nodes having the index key and it's row locater. The row located could be the RID or the
Clustered index key, depending up on the absence or presence of clustered index on the table.
If you create an index on each column of a table, it improves the query performance, as the query
optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the
same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as
every time data changes in the table, all the indexes need to be updated. Another disadvantage is that,
indexes need disk space, the more indexes you have, more disk space is used.

Back to top

Database administration (top)


What is RAID and what are different types of RAID configurations?
RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database
servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance.
MSDN has some information about RAID levels and for detailed information, check out the RAID advisory
board's homepage

What are the steps you will take to improve performance of a poor performing query?
This is a very open ended question and there could be a lot of reasons behind the poor performance of a
query. But some general issues that you could talk about would be: No indexes, table scans, missing or
out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers
without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much
normalization, excess usage of cursors and temporary tables.

Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL
ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000
Performance monitor, Graphical execution plan in Query Analyzer.

Download the white paper on performance tuning SQL Server from Microsoft web site. Don't forget to
check out sql-server-performance.com

What are the steps you will take, if you are tasked with securing an SQL Server?
Again this is another open ended question. Here are some things you could talk about: Preferring NT
authentication, using server, databse and application roles to control access to the data, securing the
physical database files using NTFS permissions, using an unguessable SA password, restricting physical
access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling
the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls,
isolating SQL Server from the web server etc.

Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server
security best practices

What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire
a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless
one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's
process.

A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of
overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and
refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page,
forcing a write transaction to wait indefinitely.

Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also
check out the article Q169960 from Microsoft knowledge base.

What is blocking and how would you troubleshoot it?


Blocking happens when one connection from an application holds a lock and a second connection
requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding
efficient transactions.

Explain CREATE DATABASE syntax


Many of us are used to craeting databases from the Enterprise Manager or by just issuing the command:
CREATE DATABAE MyDB. But what if you have to create a database with two filegroups, one on drive C
and the other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of
15%? That's why being a DBA you should be familiar with the CREATE DATABASE syntax. Check out
SQL Server books online for more information.

How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very
important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in
single user mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL
Server books online for more parameters and their explanations.

As a part of your job, what are the DBCC commands that you commonly use for database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC
SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of
DBCC commands which are very useful for DBAs. Check out SQL Server books online for more
information.

What are statistics, under what circumstances they go out of date, how do you update them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values then the
selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses
these indexes in determining whether to choose an index or not while executing a query.

Some situations under which you should update statistics:


1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the
distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE
statement and then repopulated
3) Database is upgraded from a previous version

Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE,
DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats,
sp_updatestats

What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements.
Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication,
DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

Explian different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would
you go about choosing a backup plan?
Types of backups you can create in SQL 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.

What is database replicaion? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers.
SQL Server supports the following types of replication scenarios:

Snapshot replication
Transactional replication (with immediate updating subscribers, with queued updating subscribers)
Merge replication
See SQL Server books online for indepth coverage on replication. Be prepared to explain how different
replication agents function, what are the main system tables used in replication etc.

How to determine the service pack currently installed on SQL Server?


The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine
the service pack installed. To know more about this process visit SQL Server service packs and versions.

Back to top

Database programming (top)


What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can
you avoid cursors?
Cursors allow row-by-row prcessing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip,
where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are
also costly because they require more resources and temporary storage (results in more IO operations).
Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike


Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his
salary according to the above formula. But the same can be achieved by multiple update statements or
can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =


CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a
column in a particular row meets certain condition. You don't have to use cursors for this. This can be
achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using
WHILE loop for row by row processing, check out the 'My code library' section of my site or search for
WHILE.

Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

What is a join and explain different types of joins.


Joins are used in queries to explain how different tables are related. Joins also let you select data from a
table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as
LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

Can you have a nested transaction?


Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++
using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored
procedures using the EXEC statement. See books online to learn how to create extended stored
procedures and how to add them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using
sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty,
sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-
SQL, see 'My code library' section of this site.

What is the system function to get the current user's user id?
USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER,
SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().

What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?
Triggers are special kind of stored procedures that get executed automatically when an INSERT,
UPDATE or DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one
for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple
triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In SQL
Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder

Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT,
UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend
the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers,
as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are
called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000
books online for INSTEAD OF triggers.

Also check out books online for 'inserted table', 'deleted table' and COLUMNS_UPDATED()

There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to
instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do
you think of this implementation? Can this be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it
slows down the data insertion process. Same is the case with sending emails from triggers. This scenario
can be better implemented by logging all the necessary data into a separate table, and have a job which
periodically checks this table and does the needful.

What is a self join? Explain it with an example.


Self join is just like any other join, except that two instances of the same table will be joined in the query.
Here is an example: Employees table which contains rows for normal employees as well as managers.
So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp


(
empid int,
mgrid int,
empname char(10)
)

INSERT emp SELECT 1,2,'Vyas'


INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]


FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without
managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]


FROM emp t1
LEFT OUTER JOIN
emp t2
ON
t1.mgrid = t2.empid

Given an employee table, how would you find out the second highest salary?
For a solution see the 'My code library' section of this site.

Begin Transaction
Update names_table set employee_name = "Ramesh" where employee_name = "Mahesh"
Save Transaction SAVE_POINT
Update salaries set salary=salary + 900 where employee_job = "Engineer"
Rollback transaction
Commit transaction

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

What operators perform pattern matching?


SELECT employeeNumber, lastName, firstName
FROM employees
WHERE firstName LIKE 'a%'
What is Trigger?
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE)
occurs.

What is View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as
updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the
view was created with.

What is Index?
An index is a physical structure containing pointers to the data. Indices are created in an existing table to
locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a
table, and each index is given a name.

What is the use of DBCC commands?


DBCC stands for database consistency checker. We use these commands to check the consistency of
the databases, i.e., maintenance, validation task and status checks.
E.g. DBCC CHECKDB – Ensures that tables in the db and the indexes are correctly linked.
DBCC CHECKALLOC – To check that all pages in a db are correctly allocated

How to 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.
What is difference between DELETE & TRUNCATE commands?
Delete command removes the rows from a table based on the condition that we provide with a WHERE
clause. Truncate will actually remove all the rows from a table and there will be no data in the table after
we run the truncate command.

Difference between Function and Stored Procedure?


UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as
Stored procedures cannot be.
UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline UDF’s can be though of as views that take parameters and can be used in JOINs and other Rowset
operations.

Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433

Here are some SQL Server DBA/Developer interview questions I faced myself personally and/or heard
from people. I will try to answer these questions briefly here, but be advised that these answers may not
be complete and it will be better for you to go through text books, books online and other resources on the
net. At the end of this article, I listed some useful books for aspiring DBAs and developers.

Before you go for the interview, be prepared to explain the database design of one of your latest projects.
Don't be surprised if the interviewer asks you to draw ER diagrams.

Well, here are some questions for you. Hope this helps you prepare for your interview. Wish you all the
best in your job hunt! Feel free to email me 'interview questions' that you've faced.

Questions are categorized under the following sections, for your convenience:
Database design (8 questions)
SQL Server architecture(12 questions)
Database administration(13 questions)
Database programming (10 questions)
Database design (top)
What is normalization? Explain different levels of normalization?
Check out the article Q100139 from Microsoft knowledge base and of course, there's much more
information available in the net. It'll be a good idea to get a hold of any RDBMS fundamentals text book,
especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.

What is denormalization and when would you go for it?


As the name indicates, denormalization is the reverse process of normalization. It's the controlled
introduction of redundancy in to the database design. It helps improve the query performance as the
number of joins could be reduced.

How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and
foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and
foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table.

It will be a good idea to read up a database designing fundamentals text book.

What's the difference between a primary key and a unique key?


Both primary key and unique enforce uniqueness of the column on which they are defined. But by default
primary key creates a clustered index on the column, where are unique creates a nonclustered index by
default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one
NULL only.

What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name,
and format to the database. Take for example, in your database, there is a column called Flight_Num
which appears in many tables. In all these tables it should be varchar(8). In this case you could create a
user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.

See sp_addtype, sp_droptype in books online.

What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit
datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards,
bit datatype can represent a third state, which is NULL.

Define candidate key, alternate key, composite key.


A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes
the primary key of the table. If the table has more than one candidate key, one of them will become the
primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

What are defaults? Is there a column to which a default can't be bound?


A default is a value that will be used by a column, if no value is supplied to that column while inserting
data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE
DEFUALT in books online.
Back to top

SQL Server architecture(top)


What is a transaction and what are ACID properties?
A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for
Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more
information and explanation of these properties, see SQL Server books online or any RDBMS
fundamentals text book.

Explain different isolation levels


An isolation level determines the degree of isolation of data between concurrent transactions. The default
SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order
of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server
books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION
ISOLATION LEVEL, which lets you customize the isolation level at the connection level.

CREATE INDEX myIndex ON myTable(myColumn)

What type of Index will get created after executing the above statement?
Non-clustered index. Important thing to note: By default a clustered index gets created on the primary
key, unless specified otherwise.

What's the maximum size of a row?


8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'.
Check out SQL Server books online for the page titled: "Maximum Capacity Specifications".

Explain Active/Active and Active/Passive cluster configurations


Hopefully you have experience setting up cluster servers. But if you don't, at least be familiar with the way
clustering works and the two clusterning configurations Active/Active and Active/Passive. SQL Server
books online has enough information on this topic and there is a good white paper available on Microsoft
site.

Explain the architecture of SQL Server


This is a very important question and you better be able to answer it if consider yourself a DBA. SQL
Server books online is the best place to read about SQL Server architecture. Read up the chapter
dedicated to SQL Server Architecture.

What is lock escalation?


Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher
level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory
being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks
to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL
Server 7.0 onwards it's dynamically managed by SQL Server.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log,
which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion
of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of
course, TRUNCATE TABLE can be rolled back.

Explain the storage models of OLAP


Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more infomation.

What are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time
of your interview)? What changed between the previous version of SQL Server and the current version?
This question is generally asked to see how current is your knowledge. Generally there is a section in the
beginning of the books online titled "What's New", which has all such information. Of course, reading just
that is not enough, you should have tried those things to better answer the questions. Also check out the
section titled "Backward Compatibility" in books online which talks about the changes that have taken
place in the new version.

What are constraints? Explain different types of constraints.


Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to
create triggers, rule or defaults.

Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

For an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE
TABLE", "ALTER TABLE"

Whar is an index? What are the types of indexes? How many clustered indexes can be created on a
table? I create a separate index on each column of a table. what are the advantages and disadvantages
of this approach?
Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data
quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered
index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can
be only one clustered index per table. Non-clustered indexes have their own storage separate from the
table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with
the leaf level nodes having the index key and it's row locater. The row located could be the RID or the
Clustered index key, depending up on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query
optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the
same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as
every time data changes in the table, all the indexes need to be updated. Another disadvantage is that,
indexes need disk space, the more indexes you have, more disk space is used.

Back to top

Database administration(top)
What is RAID and what are different types of RAID configurations?
RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database
servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance.
MSDN has some information about RAID levels and for detailed information, check out the RAID advisory
board's homepage

What are the steps you will take to improve performance of a poor performing query?
This is a very open ended question and there could be a lot of reasons behind the poor performance of a
query. But some general issues that you could talk about would be: No indexes, table scans, missing or
out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers
without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much
normalization, excess usage of cursors and temporary tables.

Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL
ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000
Performance monitor, Graphical execution plan in Query Analyzer.

Download the white paper on performance tuning SQL Server from Microsoft web site. Don't forget to
check out sql-server-performance.com
What are the steps you will take, if you are tasked with securing an SQL Server?
Again this is another open ended question. Here are some things you could talk about: Preferring NT
authentication, using server, databse and application roles to control access to the data, securing the
physical database files using NTFS permissions, using an unguessable SA password, restricting physical
access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling
the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls,
isolating SQL Server from the web server etc.

Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server
security best practices

What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire
a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless
one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's
process.

A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of
overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and
refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page,
forcing a write transaction to wait indefinitely.

Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also
check out the article Q169960 from Microsoft knowledge base.

What is blocking and how would you troubleshoot it?


Blocking happens when one connection from an application holds a lock and a second connection
requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding
efficient transactions.

Explain CREATE DATABASE syntax


Many of us are used to craeting databases from the Enterprise Manager or by just issuing the command:
CREATE DATABAE MyDB. But what if you have to create a database with two filegroups, one on drive C
and the other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of
15%? That's why being a DBA you should be familiar with the CREATE DATABASE syntax. Check out
SQL Server books online for more information.

How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very
important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in
single user mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL
Server books online for more parameters and their explanations.

As a part of your job, what are the DBCC commands that you commonly use for database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC
SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of
DBCC commands which are very useful for DBAs. Check out SQL Server books online for more
information.

What are statistics, under what circumstances they go out of date, how do you update them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values then the
selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses
these indexes in determining whether to choose an index or not while executing a query.
Some situations under which you should update statistics:
1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the
distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE
statement and then repopulated
3) Database is upgraded from a previous version

Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE,
DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats,
sp_updatestats

What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements.
Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication,
DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

Explian different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would
you go about choosing a backup plan?
Types of backups you can create in SQL 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.

What is database replicaion? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers.
SQL Server supports the following types of replication scenarios:

Snapshot replication
Transactional replication (with immediate updating subscribers, with queued updating subscribers)
Merge replication
See SQL Server books online for indepth coverage on replication. Be prepared to explain how different
replication agents function, what are the main system tables used in replication etc.

How to determine the service pack currently installed on SQL Server?


The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine
the service pack installed. To know more about this process visit SQL Server service packs and versions.

Back to top

Database programming (top)


What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can
you avoid cursors?
Cursors allow row-by-row prcessing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip,
where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are
also costly because they require more resources and temporary storage (results in more IO operations).
Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:
Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his
salary according to the above formula. But the same can be achieved by multiple update statements or
can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =


CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a
column in a particular row meets certain condition. You don't have to use cursors for this. This can be
achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using
WHILE loop for row by row processing, check out the 'My code library' section of my site or search for
WHILE.

Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

What is a join and explain different types of joins.


Joins are used in queries to explain how different tables are related. Joins also let you select data from a
table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as
LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

Can you have a nested transaction?


Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++
using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored
procedures using the EXEC statement. See books online to learn how to create extended stored
procedures and how to add them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using
sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty,
sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-
SQL, see 'My code library' section of this site.

What is the system function to get the current user's user id?
USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER,
SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().

What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?
Triggers are special kind of stored procedures that get executed automatically when an INSERT,
UPDATE or DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one
for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple
triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In SQL
Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder

Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT,
UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend
the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers,
as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are
called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000
books online for INSTEAD OF triggers.

Also check out books online for 'inserted table', 'deleted table' and COLUMNS_UPDATED()

There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to
instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do
you think of this implementation? Can this be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it
slows down the data insertion process. Same is the case with sending emails from triggers. This scenario
can be better implemented by logging all the necessary data into a separate table, and have a job which
periodically checks this table and does the needful.

What is a self join? Explain it with an example.


Self join is just like any other join, except that two instances of the same table will be joined in the query.
Here is an example: Employees table which contains rows for normal employees as well as managers.
So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp


(
empid int,
mgrid int,
empname char(10)
)

INSERT emp SELECT 1,2,'Vyas'


INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]


FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without
managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]


FROM emp t1
LEFT OUTER JOIN
emp t2
ON
t1.mgrid = t2.empid

Given an employee table, how would you find out the second highest salary?
For a solution see the 'My code library' section of this site.

Begin Transaction
Update names_table set employee_name = "Ramesh" where employee_name = "Mahesh"
Save Transaction SAVE_POINT
Update salaries set salary=salary + 900 where employee_job = "Engineer"
Rollback transaction
Commit transaction

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

What operators perform pattern matching?


SELECT employeeNumber, lastName, firstName
FROM employees
WHERE firstName LIKE 'a%'

What is Trigger?
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE)
occurs.

What is View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as
updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the
view was created with.

What is Index?
An index is a physical structure containing pointers to the data. Indices are created in an existing table to
locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a
table, and each index is given a name.

What is the use of DBCC commands?


DBCC stands for database consistency checker. We use these commands to check the consistency of
the databases, i.e., maintenance, validation task and status checks.
E.g. DBCC CHECKDB – Ensures that tables in the db and the indexes are correctly linked.
DBCC CHECKALLOC – To check that all pages in a db are correctly allocated

How to 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.
What is difference between DELETE & TRUNCATE commands?
Delete command removes the rows from a table based on the condition that we provide with a WHERE
clause. Truncate will actually remove all the rows from a table and there will be no data in the table after
we run the truncate command.

Difference between Function and Stored Procedure?


UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as
Stored procedures cannot be.
UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline UDF’s can be though of as views that take parameters and can be used in JOINs and other Rowset
operations.

Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433
Which of these is a CSS pseudo class? A) .abc { color:green; } B) a:visited { color:green; } C) h1 h2
{ color:green; }
Posted by: Ddd
NOTE: This is objective type question, Please click question title for correct answer.

Is CSS case Sensitive?


Posted by: Peermohamedmydeen
1. CSS is not case sensitive.

2. But some browsers taking CSS as case sensitive, where there may be the use of XML document and
XHTML doctypes.

3. It is better practice to avoid CSS classes with same name, where the only difference is case.

4.Parts that are not under control of CSS like font family names and URLs can be case sensitive -
IMAGE.gif and image.gif is not the same file.

In HTML attributes, CSS properties which one take precedence over another?
Posted by: Peermohamedmydeen
CSS properties always take precedence over HTML attributes. If both are specified, HTML attributes will
be displayed in browsers without CSS support, but won't have any effect in browsers with CSS support.

What are pseudo-elements?


Posted by: Chikul
Pseudo-elements are fictional elements that do not exist in HTML. They address the element's sub-part
(non-existent in HTML) and not the element itself. In CSS1 there are two pseudo-elements: 'first-line
pseudo-element' and 'first-letter pseudo-element'. They can be attached to block-level elements (e.g.
paragraphs or headings) to allow typographical styling of their sub-parts. Pseudo-element is created by a
colon followed by pseudo-element's name, e.g:

P:first-line
H1:first-letter

and can be combined with normal classes; e.g:

P.initial:first-line

First-line pseudo-element allows sub-parting the element's first line and attaching specific style
exclusively to this sub-part; e.g.:

P.initial:first-line {text-transform: uppercase}


<P class=initial>The first line of this paragraph will be displayed in uppercase letters</P>

First-letter pseudo-element allows sub-parting the element's first letter and attaching specific style
exclusively to this sub-part; e.g.:

P.initial:first-letter { font-size: 200%; color: red}

<P class=initial>The first letter of this paragraph will be displayed in red and twice as large as the
remaining letters</P>

What is contextual selector?


Posted by: Chikul
Contextual selector is a selector that addresses specific occurrence of an element. It is a string of
individual selectors separated by white space, a search pattern, where only the last element in the pattern
is addressed providing it matches the specified context.

TD P CODE {color: red}

The element CODE will be displayed in red but only if it occurs in the context of the element P which must
occur in the context of the element TD.

TD P CODE, H1 EM {color: red}

The element CODE will be displayed in red as described above AND the element EM will also be red but
only if it occurs in the context of H1

P .footnote {color: red}

Any element with CLASS footnote will be red but only if it occurs in the context of P

P .footnote [lang]{color: red}

Any element with attribute LANG will be red but only if it is classed as "footnote" and occurs in the context
of P

What is ID selector?
Posted by: Chikul
ID selector is an individually identified (named) selector to which a specific style is declared. Using the ID
attribute the declared style can then be associated with one and only one HTML element per document
as to differentiate it from all other elements. ID selectors are created by a character # followed by the
selector's name. The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped
characters, Unicode characters 161-255, as well as any Unicode character as a numeric code, however,
they cannot start with a dash or a digit.

#abc123 {color: red; background: black}

<P ID=abc123>This and only this element can be identified as abc123 </P>

What is CSS rule 'ruleset'?


Posted by: Chikul
There are two types of CSS rules: ruleset and at-rule. Ruleset identifies selector or selectors and declares
style which is to be attached to that selector or selectors. For example P {text-indent: 10pt} is a CSS rule.
CSS rulesets consist of two parts: selector, e.g. P and declaration, e.g. {text-indent: 10pt}.

P {text-indent: 10pt} - CSS rule (ruleset)


{text-indent: 10pt} - CSS declaration
text-indent - CSS property
10pt - CSS value

What is embedded style? How to link?


Posted by: Chikul
The HEAD area, where the TITLE and META tags are found, is also used to store CSS commands.
These are called embedded CSS. Any embedded CSS command will over-ride an external CSS
command of the same tag. Embedded commands are more specific to the page.

Embedded CSS codes are placed within the HEAD area of the page code. That is anywhere after the
<HEAD> tag and before the </HEAD> tag. NOT in the HEAD tag itself.

<style type="text/css" media=screen>


<!--
p {font-family: georgia, serif; font-size: x-small;}
hr {color: #ff9900; height: 1px }
a:hover {color: #ff0000; text-decoration: none}
-->
</style>

Now, whenever any of those elements are used within the body of the document, they will be formatted
as instructed in the above style sheet.

CSS Interview Questions

1) What are cascading style sheets?


Cascading style sheets help the designer in various ways. It primarily helps to design style sheets for
content and HTML pages. It can be applied to any XML document or mark up language.
2) Explain about some of the features of CSS?
Some of the features used by CSS are to define a layout, colors, fonts, etc. It separates the content from
the design part which makes the content much more visible thereby improving productivity of the entire
process. It can make the same page appear in different formats.
3) Explain about the rules present in style sheets?
A huge list of rules is defined for style sheets. Each rule consists of selectors and declaration block. A
declaration block consists of declarations which can be defined and separated by using a semicolon
within curly braces. Also each declaration consists of a colon, a property and a semicolon.
4) Explain about the hover element?
A hover element is activated when the user moves a pointer over the area where HTML coding is defined.
This style is being extensively used for online advertising. It is appended to #elementid:hover.
5) State some of the uses of CSS?
CSS offers many possibilities to a designer and developer. Some of them are
1) Moving of the entire style sheet coding to a separate external folder.
2) Repetition and code reuse features make CSS rich.
3) Presentation and structure are made different by CSS etc.
6) State the different type of author styles?
A web page author, developer, designer, etc can describe styles in three different forms they are
1) External style sheets
2) Embedded style
3) Inline styles
4) Local and default style sheet.
A default style sheet consists of the style imparted by the browser which the user is accessing for the
information.
7) What are the main goals of applying style sheets?
The main use of style sheet is to give the user a greater degree of control over his presentation. If the
user does not like a certain font he can change it with flexibility without any difficulty.
Also a developer can minimize the effects which a browser can have on the application or the text part of
the webpage.
Control over the entire web page without any external influences, separation of the page from the HTML
code part.
8) Explain about CSS1?
W3C recommended adoption of CSS1in 1996. Some of the capabilities and features present in CSS1 are
as follows.
1) Font properties
2) Background colors, text colors, etc
3) Spacing between text, words, etc
4) Tables, images alignment
5) Border, margin, padding and positioning of elements
6) Attributes are uniquely identified and classified generically.
W3C still adopts the specifications put forwarded in CSS1.
9) What are the additional features which were present in CSS2 compared to CSS1?
Many of the new features were present in CSS2 some of them are as follows.
1) Positioning of elements will be according to the relative, fixed and the absolute positioning.
2) Inclusion of large number of media functions.
3) Shadows, bidirectional support for text and aural style sheets.

10) Explain about CSS filter?


CSS filter solves designers and coders difficulties. With the help of these filters one can write entirely
different code or modify the existing design patterns so that browsers receive CSS specifications which
they support, thereby not allowing the browsers to make or create any unnecessary changes.
11) Explain about Internet explorer box model bug?
Designers had a very tough time dealing with this bug, because it will not display box widths appropriately
on the webpage. It displayed the block to be narrow in size. This bug can be rectified by using CSS filter
and hacks. Also correct usage and documentation of XHTML can solve the problems.
12) Explain about vertical control limitation?
Vertical control limitations are always a nightmare for a designer. Horizontal positioning of text or element
is always easy but vertically positioning an element always leads to convoluted and impossible tasks.
CSS has unsupported rules for vertical placement of elements.
13) Explain about absence of expressions?
CSS currently does not have the ability to specify property values as simple expressions. For example if
you want to calculate the size of all the columns but you have a restriction on the sum of all columns. This
problem has been solved by many browsers by proprietary expressions which did the job well.
14) Explain about lack of orthogonality?
Lack of orthogonality explains about the various multiple jobs which are either undefined correctly for a
specific application or used multiple times for the same job. CSS defines that internal elements of a table
will not have margins so usage of border spacing is appropriate which leads to confusion.
15) Explain about the ease of maintenance with CSS.
An effective style sheet has effective use of inheritance and cascading style sheets. When changes are
applied to a single element of this global style sheet every element of the web page changes. This made
the maintenance easy because here we can change the style of the whole page by effecting a change to
a single element.

16) Explain about float containment?


CSS does not support float elements as it can cause overflow of the elements. Floats also tend to vary
according to the web browser resolution and size but positions do not. There are some multiple properties
which can define about float but they have their own limitations.
17) State some limitations of style sheets?
Style sheets do have its own share of limitations some of them are as follows: -
1) Inconsistent browser support
2) Vertical control limitations
3) Margin collapsing, float containment, control of element shapes, etc
4) Lack of column declaration and variables are some of the limitations present in CSS.
CSS Interview Questions And Answers Set - 2

'Fixed' Background?
There is the possibility to use the HTML tag bgproperties="fixed", but that is IE proprietary, and
dependent upon the 'background' attribute (deprecated in HTML4).

With CSS, you can declare the background like:

BODY {
font-family : "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
background-image: url(images/yourimage.gif);
background-repeat: no-repeat; /*no-tiling background*/
background-position: center;
background-attachment: fixed;
background-color: #hexcolor;
color : #hexcolor;
margin: 10px;
}

that shows a background-image in the center of the <BODY> element, non-scrolling and non-repeating -
in IE or NN6. NN 4.xx gets the non-repeat-part right, but stuffs the picture in the upper left corner and
scrolls ...

What is embedded style? How to link?


Embedded style is the style attached to one specific document. The style information is specified as a
content of the STYLE element inside the HEAD element and will apply to the entire document.

<HEAD>
<STYLE TYPE="text/css">
<!--
P {text-indent: 10pt}
-->
</STYLE>
</HEAD>

Note: The styling rules are written as a HTML comment, that is, between <!-- and --> to hide the content
in browsers without CSS support which would otherwise be displayed.

What is ID selector?
ID selector is an individually identified (named) selector to which a specific style is declared. Using the ID
attribute the declared style can then be associated with one and only one HTML element per document
as to differentiate it from all other elements. ID selectors are created by a character # followed by the
selector's name. The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped
characters, Unicode characters 161-255, as well as any Unicode character as a numeric code, however,
they cannot start with a dash or a digit.

#abc123 {color: red; background: black}

<P ID=abc123>This and only this element can be identified as abc123 </P>

What is contextual selector?


Contextual selector is a selector that addresses specific occurrence of an element. It is a string of
individual selectors separated by white space, a search pattern, where only the last element in the pattern
is addressed providing it matches the specified context.
TD P CODE {color: red}

The element CODE will be displayed in red but only if it occurs in the context of the element P which must
occur in the context of the element TD.

TD P CODE, H1 EM {color: red}

The element CODE will be displayed in red as described above AND the element EM will also be red but
only if it occurs in the context of H1

P .footnote {color: red}

Any element with CLASS footnote will be red but only if it occurs in the context of P

P .footnote [lang]{color: red}

Any element with attribute LANG will be red but only if it is classed as "footnote" and occurs in the context
of P

How do I have a background image that isn't tiled?


Specify the background-repeat property as no-repeat. You can also use the background property as a
shortcut for specifying multiple background-* properties at once. Here's an example:

BODY {background: #FFF url(watermark.jpg) no-repeat;}

What does \ABCD (and \ABCDE) mean?


CSS allows Unicode characters to be entered by number. For example, if a CLASS value in some
Russian document contains Cyrillic letters EL PE (Unicode numbers 041B and 041F) and you want to
write a style rule for that class, you can put that letter into the style sheet by writing:

.\041B\041F {font-style: italic;}


This works on all keyboards, so you don't need a Cyrillic keyboard to write CLASS names in Russian or
another language that uses that script.

The digits and letters after the backslash (\) are a hexadecimal number. Hexadecimal numbers are made
from ordinary digits and the letters A to F (or a to f). Unicode numbers consist of four such digits.

If the number starts with a 0, you may omit it. The above could also be written as:

.\41B\41F {font-style: italic;}


But be careful if the next letter after the three digits is also a digit or a letter a to f! This is OK: .\41B-\41F,
since the dash (-) cannot be mistaken for a hexadecimal digit, but .\41B9\41F is only two letters, not three.

Four digits is the maximum, however, so if you write:


.\041B9\041F {font-style: italic;}

Why do style sheets exist?


SGML (of which HTML is a derivative) was meant to be a device-independent method for conveying a
document's structural and semantic content (its meaning.) It was never meant to convey physical
formatting information. HTML has crossed this line and now contains many elements and attributes which
specify visual style and formatting information. One of the main reasons for style sheets is to stop the
creation of new HTML physical formatting constructs and once again separate style information from
document content.

What are the advantages/disadvantages of the various style methods?


External Style Sheets
Advantages

* Can control styles for multiple documents at once


* Classes can be created for use on multiple HTML element types in many documents
* Selector and grouping methods can be used to apply styles under complex contexts

Disadvantages

* An extra download is required to import style information for each document


* The rendering of the document may be delayed until the external style sheet is loaded
* Becomes slightly unwieldy for small quantities of style definitions

Embedded Style Sheets


Advantages

* Classes can be created for use on multiple tag types in the document
* Selector and grouping methods can be used to apply styles under complex contexts
* No additional downloads necessary to receive style information

Disadvantages

* This method can not control styles for multiple documents at once

Inline Styles
Advantages

* Useful for small quantities of style definitions


* Can override other style specification methods at the local level so only exceptions need to be listed in
conjunction with other style methods

Disadvantages

* Does not distance style information from content (a main goal of SGML/HTML)
* Can not control styles for multiple documents at once
* Author can not create or control classes of elements to control multiple element types within the
document
* Selector grouping methods can not be used to create complex element addressing scenarios

What is inline style? How to link?


Inline style is the style attached to one specific element. The style is specified directly in the start tag as a
value of the STYLE attribute and will apply exclusively to this specific element occurrence.

<P STYLE="text-indent: 10pt">Indented paragraph</P>

What is imported Style Sheet? How to link?


Imported Style Sheet is a sheet that can be imported to (combined with) another sheet. This allows
creating one main sheet containing declarations that apply to the whole site and partial sheets containing
declarations that apply to specific elements (or documents) that may require additional styling. By
importing partial sheets to the main sheet a number of sources can be combined into one.
To import a style sheet or style sheets include the @import notation or notations in the STYLE element.
The @import notations must come before any other declaration. If more than one sheet is imported they
will cascade in order they are imported - the last imported sheet will override the next last; the next last
will override the second last, and so on. If the imported style is in conflict with the rules declared in the
main sheet then it will be overridden.
<LINK REL=STYLESHEET HREF="main.css" TYPE="text/css">
<STYLE TYPE="text=css">
<!--
@import url(http://www.and.so.on.partial1.css);
@import url(http://www.and.so.on.partial2.css);
.... other statements
-->
</STYLE>

What is a Style Sheet?


Style sheets are the way that standards-compliant Web designers define the layout, look-and-feel, and
design of their pages. They are called Cascading Style Sheets or CSS. With style sheets, a designer can
define many aspects of a Web page:

* fonts
* colors
* layout
* positioning
* imagery
* accessibility

Style sheets give you a lot of power to define how your pages will look. And another great thing about
them is that style sheets make it really easy to update your pages when you want to make a new design.
Simply load in a new style sheet onto your pages and you're done.

What is alternate Style Sheet? How to link?


Alternate Style Sheet is a sheet defining an alternate style to be used in place of style(s) declared as
persistent and/or preferred .
Persistent style is a default style that applies when style sheets are enabled but can disabled in favor of
an alternate style, e.g.:

<LINK REL=Stylesheet HREF="style.css" TYPE="text/css">

Preferred style is a default style that applies automatically and is declared by setting the TITLE attribute to
the LINK element. There can only be one preferred style, e.g.:

<LINK REL=Stylesheet HREF="style2.css" TYPE="text/css" TITLE="appropriate style description">

Alternate style gives an user the choice of selecting an alternative style - a very convenient way of
specifying a media dependent style. Note: Each group of alternate styles must have unique TITLE, e.g.:

<LINK REL="Alternate Stylesheet" HREF="style3.css" TYPE="text/css" TITLE="appropriate style


description" MEDIA=screen>
<LINK REL="Alternate Stylesheet" HREF="style4.css" TYPE="text/css" TITLE="appropriate style
description" MEDIA=print>

Alternate stylesheet are not yet supported.

How can you set a minimum width for IE?


To set a minimum width, the CSS property is 'min-width'. This can be very useful and works well in good
browsers. IE doesn't understand 'min-width'. However, it has a proprietary property called 'expression'
which allows us to feed it javascript via a stylesheet. Below is how to set a (780px) minimum width for IE...

<!--[if gte IE 5]> <style type="text/css">


body {
width:expression(documentElement.clientWidth < 780 ? (documentElement.clientWidth == 0 ?
(body.clientWidth < 780 ? "780px" : "auto") : "780px") : "auto" );
}
</style>
<![endif]-->

As the property is non-standard, it won't validate with the W3C validator, so if we put it in the head like
this (above) - in an IE conditional comment - the validator will ignore it and the page will get a clean bill of
health.

Which browsers support CSS?


It depends on your definition of "support." If you are interested in those browsers which makes some
attempt at supporting CSS, no matter how partial or bug-ridden, then the list is:

* Internet Explorer 3.0 and above


* Navigator 4.0 and above
* Opera 3.6 and above
* Konqueror
* Arena
* Emacs-w3
* Amaya
* Lexicon
* XPublish by Media Design in?Progress

If instead you're interested in those browsers which are known to do a credible job of bug-free and mostly
completel support for CSS1, then the list narrows somewhat dramatically:

* Internet Explorer 5.0 for Macintosh and above


* Internet Exporer 5.5 for Windows and above
* Netscape Navigator 6.0 and above
* Opera 4.0 and above
What is CSS?
1. CSS stands for Cascading Style Sheets and is a simple styling language which allows attaching style
to HTML elements. Every element type as well as every occurrence of a specific element within that type
can be declared an unique style, e.g. margins, positioning, color or size.

2. CSS is a web standard that describes style for XML/HTML documents.

3. CSS is a language that adds style (colors, images, borders, margins?) to your site. It?s really that
simple. CSS is not used to put any content on your site, it?s just there to take the content you have and
make it pretty. First thing you do is link a CSS-file to your HTML document. Do this by adding this line:

<link rel="stylesheet" href="style.css"


type="text/css">

The line should be placed in between your <head> and </head> tags. If you have several pages you
could add the exact same line to all of them and they will all use the same stylesheet, but more about that
later. Let?s look inside the file ?style.css? we just linked to.

h1 {
font-size: 40px;
height: 200px;
}
.warning {
color: Red;
font-weight: bold;
}
#footer {
background-color: Gray;
}

4. Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g. fonts, colors, spacing) to
Web documents. This is also where information meets the artistic abilities of a web-designer. CSS helps
you spice up your web-page and make it look neat in wide variety of aspects.

What are Cascading Style Sheets?


A Cascading Style Sheet (CSS) is a list of statements (also known as rules) that can assign various
rendering properties to HTML elements. Style rules can be specified for a single element occurrence,
multiple elements, an entire document, or even multiple documents at once. It is possible to specify many
different rules for an element in different locations using different methods. All these rules are collected
and merged (known as a "cascading" of styles) when the document is rendered to form a single style rule
for each element.

How do I center block-elements with CSS1?


There are two ways of centering block level elements:

1. By setting the properties margin-left and margin-right to auto and width to some explicit value:

BODY {width: 30em; background: cyan;}


P {width: 22em; margin-left: auto; margin-right: auto}

In this case, the left and right margins will each be four ems wide, since they equally split up the eight
ems left over from (30em - 22em). Note that it was not necessary to set an explicit width for the BODY
element; it was done here to keep the math clean.

Another example:

TABLE {margin-left: auto; margin-right: auto; width: 400px;}


In most legacy browsers, a table's width is by default determined by its content. In CSS-conformant
browsers, the complete width of any element (including tables) defaults to the full width of its parent
element's content area. As browser become more conformant, authors will need to be aware of the
potential impact on their designs.

If background and color should always be set together, why do they exist as separate properties?
There are several reasons for this. First, style sheets become more legible -- both for humans and
machines. The background property is already the most complex property in CSS1 and combining it with
color would make it even more complex. Second, color inherits, but background doesn't and this would be
a source of confusion.

What is class?
Class is a group of 1) instances of the same element to which an unique style can be attached or 2)
instances of different elements to which the same style can be attached.

1) The rule P {color: red} will display red text in all paragraphs. By classifying the selector P different style
can be attached to each class allowing the display of some paragraphs in one style and some other
paragraphs in another style.
2) A class can also be specified without associating a specific element to it and then attached to any
element which is to be styled in accordance with it's declaration. All elements to which a specific class is
attached will have the same style.

To classify an element add a period to the selector followed by an unique name. The name can contain
characters a-z, A-Z, digits 0-9, period, hyphen, escaped characters, Unicode characters 161-255, as well
as any Unicode character as a numeric code, however, they cannot start with a dash or a digit. (Note: in
HTML the value of the CLASS attribute can contain more characters). (Note: text between /* and */ are
my comments).

CSS
P.name1 {color: red} /* one class of P selector */
P.name2 {color: blue} /* another class of P selector */
.name3 {color: green} /* can be attached to any element */

HTML
<P class=name1>This paragraph will be red</P>
<P class=name2>This paragraph will be blue</P>
<P class=name3>This paragraph will be green</P>
<LI class=name3>This list item will be green</LI>

It is a good practice to name classes according to their function than their appearance; e.g. P.fotnote and
not P.green. In CSS1 only one class can be attached to a selector. CSS2 allows attaching more classes,
e.g.:
P.name1.name2.name3 {declaration} <P class="name1 name2 name2">This paragraph has three
classes attached</P>

What is grouping ?
Grouping is gathering (1) into a comma separated list two or more selectors that share the same style or
(2) into a semicolon separated list two or more declarations that are attached to the same selector (2).

1. The selectors LI, P with class name .first and class .footnote share the same style, e.g.:
LI {font-style: italic}
P.first {font-style: italic}
.footnote {font-style: italic}

To reduce the size of style sheets and also save some typing time they can all be grouped in one list.
LI, P.first, .footnote {font-style: italic}

2. The declarations {font-style: italic} and {color: red} can be attached to one selector, e.g.:
H2 {font-style: italic}
H2 {color: red}
and can also be grouped into one list:
H2 {font-style: italic; color: red}

What is external Style Sheet? How to link?


External Style Sheet is a template/document/file containing style information which can be linked with any
number of HTML documents. This is a very convenient way of formatting the entire site as well as
restyling it by editing just one file. The file is linked with HTML documents via the LINK element inside the
HEAD element. Files containing style information must have extension .css, e.g. style.css. <HEAD>
<LINK REL=STYLESHEET HREF="style.css" TYPE="text/css"> </HEAD>

Is CSS case sensitive?


Cascading Style Sheets (CSS) is not case sensitive. However, font families, URLs to images, and other
direct references with the style sheet may be.
The trick is that if you write a document using an XML declaration and an XHTML doctype, then the CSS
class names will be case sensitive for some browsers.

It is a good idea to avoid naming classes where the only difference is the case, for example:

div.myclass { ...}
div.myClass { ... }
If the DOCTYPE or XML declaration is ever removed from your pages, even by mistake, the last instance
of the style will be used, regardless of case.

Three selectors: h1, .warning and #footer, what they do ?


An element points at a HTML-tag somewhere on your page. In the example above we want to style the
<h1>-tag. Note that using an element like that affects all tags with that name, so using p { margin-left:
100px; } gives all <p>-tags a left-margin.
Using a class is just as simple. When writing .your_class you style all tags with a class with the name ?
your_class?. In the example above we have .warning which will style e.g. <div class="warning"> and <em
class="warning">, that is, any element with the class warning. Classes are used when you want to style
just a few of your tags in a way, perhaps you want some of your links red? Add a class to all those links.
You need one more building block: the id. This time you style an element with the attribute ?id? set to the
id you have chosen. Ids work exactly like classes except for one thing; you can only have one id with a
certain name in each of your HTML documents. In the example above we style <div id="footer">. If you
look at the example it does make sense: a HTML document may contain several warnings but only one
footer. Ids should be used when you want to style just one specific tag.
Using those three building blocks will take you far but when you get to more advanced layouts you might
want to combine the building blocks into more advanced selectors. Just to give you two examples of what
you can do: em.warning to style only those <em>-tags with the class .warning set. You can also use
#footer a to style only the links that are nested inside the tag with id ?footer.
Each of the selectors has a set of declarations tied to them. Each declaration has a property, describing
what we want to change and a value, what we should change it to. An example: a { color: Blue; font-size:
3em; }. You have the selector a there, so all links in your document will be styled. We have two
declarations: color: Blue and font-size: 3em;. Lastly each declaration consists of two parts: the property
color and the value Blue.
there is a LOT of things you can style and play with. Additionally (close to) all tags are equal in CSS, so
you can set e.g. borders and colors of any element just like you could with a table if you used only HTML.

What are Style Sheets?


Style Sheets are templates, very similar to templates in desktop publishing applications, containing a
collection of rules declared to various selectors (elements).

What is CSS rule 'ruleset'?


There are two types of CSS rules: ruleset and at-rule. Ruleset identifies selector or selectors and declares
style which is to be attached to that selector or selectors. For example P {text-indent: 10pt} is a CSS rule.
CSS rulesets consist of two parts: selector, e.g. P and declaration, e.g. {text-indent: 10pt}.

P {text-indent: 10pt} - CSS rule (ruleset)


{text-indent: 10pt} - CSS declaration
text-indent - CSS property
10pt - CSS value
How do I place text over an image?
To place text or image over an image you use the position property. The below exemple is supported
by IE 4.0. All you have to do is adapt the units to your need.

<div style="position: relative; width: 200px; height: 100px">


<div style="position: absolute; top: 0; left: 0; width: 200px">
<image>
</div>
<div style="position: absolute; top: 20%; left: 20%; width: 200px">
Text that nicely wraps
</div>
</div>
what CSS is, why not start coding?
CSS is sort of like scripting language made for the web. In contrary with HTML, DHTML, JavaScript,
VBScript and many others. CSS is strictly for formatting your web-page and now many new browser
support it. (NOTE: Older browser do not support CSS, so please check your browser version and make
sure whether it supports it or not. You may have to update your current Browser.)

The way the code goes into your Web-page is through a variety of ways. The way CSS works is that is
the code is set between the<head></head> tags. You can put the CSS code after </title> which is
what most people do. Now, here are the following ways of making your webpage with CSS enabled
features:

1.) Writing your CSS code within your HTML source code. This is how it would look like:

<html><head><title>My First CSS!</title>


<!-- Now begin the CSS coding! -->
<STYLE TYPE = "text/css">
<!--
body {
background-color: #eeeee;
}
p{
text-align: left;
color: black;
font: Verdana;
font-size: 80%;
}
a{
text-decoration: none;
color: black;
font-weight: bold;
}
a:hover {
text-decoration: underline;
color: red;
font-weight: bold;
}
-->
</STYLE>
<!-- End CSS code -->
</head><body></body></html>

2.) Linking to your CSS file. This tells the webpage to find the .css file and use it as the CSS code.
Here is the code that would allow you to do:

<html><head><title>CSS</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head><body /></html>

As you can see from the code above, the <link> tag is pretty helpful. What it does is that it links to
the style.css file which has all the css code. Just like embedding an image throught he <img> tag.
Now to explain a bit from the first example. CSS code isn't very hard to understand.Take for example
the body { ..} part. What it does is that it formats how the <body> tag in HTML would work. That is a
very simple way of formatting the body tag with the CSS. To help you understand better, here is a
simple syntax for CSS:

selector { property1: value1; property2: value2;}

The "selector" sort of relates to the html tags used for outputting etc...

We all know that <a> is a tag used for links. You will see in the example about a:hover and a itself.
<br>What a does it just sets the characteristics of the format. You can set how you want a link to
appear using the font size, weight etc..

Then comes the "a:hover". What does is also pretty self explanatory. It acts on when a person moves
the mouse cursor over the links.

ADVANCED CSS FEATURES:


CSS can be even used to change the appearance of the scroll bar at your right side. Unfortunately,
that only works with IE. You have to be using IE in order for this to work. Here is how to change some
appearances of your scroll bar:

The CSS statements for doing this are:


1) scrollbar-3dlight-color
2)scrollbar-arrow-color
3) scrollbar-base-color
4) scrollbar-dark shadow-color
5) scrollbar-face-color
6) scrollbar-highlight-color
7) scrollbar-shadow-color
8) scrollbar-track-color

<style type="text/css">
<!--
BODY {
scrollbar-arrow-color: green;
scrollbar-face-color: #FFFFFF;
scrollbar-track-color: rgb(12,35,244);
}
// -->
</style>

How to customize your textboxes.


Here is the code on how to do it:

<style type="text/css">
<!--
BODY {
scrollbar-arrow-color: green;
scrollbar-face-color: #FFFFFF;
scrollbar-track-color: rgb(12,35,244);
}
TEXTAREA {
scrollbar-arrow-color: green;
scrollbar-face-color: #FFFFFF;
scrollbar-track-color: rgb(12,35,244);
}
// -->
</style>

That above code, has some similarities. The textbox area is treated with the same function statements
as for the scrollbar. The scrollbar statements goes in the BODY selector.
Why does my content shift to the left on some pages (in FF)?
That'll be the pages with more content? The ones that have a vertical scrollbar? If you look in IE
there's probably a white space on the right where there would be a scrollbar if there were enough
content to require one. In Firefox, the scrollbar appears when it's needed and the viewport becomes
about 20px smaller, so the content seems to shift to the left when you move from a page with little
content to one with lots of content. It's not a bug or something that needs to be fixed, but it does
confuse and irritate some developers.

If, for some reason, you'd like Firefox to always have scrollbars - whether they're needed or not - you
can do this :

CSS html {
height:100.1%;
}
How do I combine multiple sheets into one?
To combine multiple/partial style sheets into one set the TITLE attribute taking one and the same
value to the LINK element. The combined style will apply as a preferred style, e.g.:

<LINK REL=Stylesheet HREF="default.css" TITLE="combined">


<LINK REL=Stylesheet HREF="fonts.css" TITLE="combined">
<LINK REL=Stylesheet HREF="tables.css" TITLE="combined">
What is attribute selector?
Attribute selector is a selector defined by 1) the attribute set to element(s), 2) the attribute and
value(s), 3) the attribute and value parts:

1a) A[title] {text-decoration: underline}


All A elements containing the TITLE attribute will be underlined

1b) A[class=name] {text-decoration: underline}


The A elements classed as 'name' will be underlined

2) A[title="attribute element"] {text-decoration: underline}


The A elements containing the TITLE attribute with a value that is an exact match of the specified
value, which in this example is 'attribute element', will be underlined

3) A[title~="attribute"] {text-decoration: underline}


The A elements containing the TITLE attribute with a value containing the specified word, which in this
example is 'attribute', will be underlined
What is parent-child selector?
Parent-child selector is a selector representing the direct descendent of a parent element. Parent-child
selectors are created by listing two or more tilde (~) separated selectors.

BODY ~ P {background: red; color: white}


The P element will be declared the specified style only if it directly descends from the BODY element:
<BODY> <P>Red and white paragraph </P> </BODY>

BODY ~ P ~ EM {background: red; color: white}


The EM element will be declared the specified style only if it directly descends from the P element
which in its turn directly descends from the BODY element:

< <P> <EM>Red and white EM </EM> </P> </BODY>


How can I specify background images?
With CSS, you can suggest a background image (and a background color, for those not using your
image) with the background property. Here is an example:

body {
background: white url(example.gif) ;
color: black ;
}
If you specify a background image, you should also specify text, link, and background colors since the
reader's default colors may not provide adequate contrast against your background image. The
background color may be used by those not using your background image. Authors should not rely on
the specified background image since browsers allow their users to disable image loading or to
override document-specified backgrounds.
How do I have a fixed (non-scrolling) background image?
With CSS, you can use the background-attachment property. The background attachment can be
included in the shorthand background property, as in this example:

body {
background: white url(example.gif) fixed ;
color: black ;
}

Note that this CSS is supported by Internet Explorer, Mozilla, Firefox Opera, Safari, and other
browsers. In contrast, Microsoft's proprietary BGPROPERTIES attribute is supported only by Internet
Explorer.
What are inline, block, parent, children, replaced and floating elements?
Inline
elements which do not have line breaks. Can occur in block elements or other inline elements, cannot
contain block elements.
Inline elements in HTML 3.2; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, TT, I, B, U, STRIKE,
BIG, SMALL, SUB, SUP, A, IMG, APPLET, FONT, BASEFONT, BR, SCRIPT, MAP, INPUT, SELECT,
TEXTAREA.

Inline elements in HTML 4.0; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ABBR, ACRONYM, TT,
I, B, BIG, SMALL, SUB, SUP, A, IMG, OBJECT, BR, SCRIPT, MAP, Q, SPAN, BDO, INPUT, SELECT,
TEXTAREA, LABEL, BUTTON, (INS, DEL).
Inline elements in HTML 4.0 Transitional; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ABBR,
ACRONYM, TT, I, B, U, S, STRIKE, BIG, SMALL, SUB, SUP, A, IMG, APPLET, OBJECT, FONT,
BASEFONT, BR, SCRIPT, MAP, Q, SPAN, BDO, IFRAME, INPUT, SELECT, TEXTAREA, LABEL, BUTTON,
(INS, DEL).

Block
elements which do have line breaks. May occur in other block elements, cannot occur in inline
elements, may contain both block and inline elements.

Block elements in HTML 3.2; H1, H2, H3, H4, H5, H6, ADDRESS, P, DL, DT, DD, UL, OL, DIR, MENU,
LI, DIV, CENTER, BLOCKQUOTE, PRE, HR, ISINDEX, TABLE, FORM.

Block elements in HTML 4.0; P, H1, H2, H3, H4, H5, H6, UL, OL, PRE, DL, DIV, NOSCRIPT,
BLOCKQUOTE, FORM, HR, TABLE, FIELDSET, ADDRESS, (INS, DEL).

Block elements in HTML 4.0 Transitional; P, H1, H2, H3, H4, H5, H6, UL, OL, DIR, MENU, PRE, DL,
DIV, CENTER, NOSCRIPT, NOFRAMES, BLOCKQUOTE, FORM, ISINDEX, HR, TABLE, FIELDSET,
ADDRESS, (INS, DEL).

Parents and children


elements which either contain (parents) or are in the content of (children) other elements, e.g.
<P>text<STRONG>text</STRONG>text</P>. P is a parent of STRONG. STRONG is a child of P. If not
specified otherwise, children will inherit parent's properties.
Replaced
elements which content is replaced. For example content of the IMG element is replaced with an
image, content of the INPUT element is replace with a field.
Floating
elements which follow the flow of a parent - inline elements.
Which set of definitions, HTML attributes or CSS properties, take precedence?
CSS properties take precedence over HTML attributes. If both are specified, HTML attributes will be
displayed in browsers without CSS support but won't have any effect in browsers with CSS support.
How do I eliminate the blue border around linked images?
in your CSS, you can specify the border property for linked images:

a img { border: none ; }


However, note that removing the border that indicates an image is a link makes it harder for users to
distinguish quickly and easily which images on a web page are clickable.
Why call the subtended angle a "pixel", instead of something else (e.g. "subangle")?
In most cases, a CSS pixel will be equal to a device pixel. But, as you point out, the definition of a
CSS pixel will sometimes be different. For example, on a laser printer, one CSS pixel can be equal to
3x3 device pixels to avoid printing illegibly small text and images. I don't recall anyone ever proposing
another name for it. Subangle? Personally, I think most people would prefer the pragmatic "px" to the
non-intuitive "sa".
Why was the decision made to make padding apply outside of the width of a 'box', rather
than inside, which would seem to make more sense?
It makes sense in some situations, but not in others. For example, when a child element is set to
width: 100%, I don't think it should cover the padding of its parent. The box-sizing property in CSS3
addresses this issue. Ideally, the issue should have been addressed earlier, though.
How to use CSS to separate content and design ?
The idea here is that all sites contain two major parts, the content: all your articles, text and photos
and the design: rounded corners, colors and effects. Usually those two are made in different parts of a
webpage?s lifetime. The design is determined at the beginning and then you start filling it with content
and keep the design fixed.

In CSS you just add the nifty <link>-tag I?ve told you about to the head of your HTML document and
you have created a link to your design. In the HTML document you put content only, and that link of
yours makes sure it looks right. You can also use the exact same link on many of your pages, giving
them all of them the same design. You want to add content? Just write a plain HTML document and
think about marking things up like ?header? instead of ?big blue header? and use CSS to make all
headers look the way you want!
Some examples of good and bad coding. What?s wrong with this?
<font size="3">Welcome to my page</font>

Comment: The font-tag is design and design shouldn?t be in the HTML document. All design should be
in the CSS-file! Instead do this:

In the HTML:
<h1>Welcome to my page</h1>

In the CSS:
h1 { font-size: 2em; }

One more example:

<b>An error occurred</b>

This looks right doesn?t it? But if you look up what <b> stands for you quickly find bold. But bold is
certainly design, so it still doesn?t belong in the HTML document. A better choice is <em> that stands
for emphasis or simply ?this piece of text is important?. So instead of saying ?this text looks like this?
you are saying ?this text is important? and you let the looks be decided by the CSS. Seems like a
minor change, but it illustrates how to select your tags. Use this instead:

In the HTML:
<em>An error occured</em>

In the CSS:
em {
font-weight: bold;
color: Red;
}

One last example:

<table>
<tr><td><a href="">first link</a></td></tr>
<tr><td><a href="">second link</a></td></tr>
...
</table>
Can CSS be used with other than HTML documents?
Yes. CSS can be used with any ny structured document format. e.g. XML, however, the method of
linking CSS with other document types has not been decided yet.
Can Style Sheets and HTML stylistic elements be used in the same document?
Yes. Style Sheets will be ignored in browsers without CSS-support and HTML stylistic elements used.
What are pseudo-classes?
Pseudo-classes are fictional element types that do not exist in HTML. In CSS1 there is only one
element type which can be classed this way, namely the A element (anchor). By creating three
fictional types of the A element individual style can be attached to each class. These three fictional
element types are: A as unvisited link, A as active link and A as visited link. Pseudo-classes are
created by a colon followed by pseudo-class's name. They can also be combined with normal classes,
e.g.:

A:link {background: black; color: white}


A:active {background: black; color: red}
A:visited {background: transparent; color: black}

<A HREF....>This anchor (or rather these anchors) will be displayed as declared above</A>

A.foot:link {background: black; color: white}


A.foft:active {background; black: color: red}
A.foot:visited {background: transparent; color: black}

<A CLASS=foot HREF....>This anchor and all other anchors with CLASS foot will be displayed as
declared above</A>
How do I design for backward compatibility using Style Sheets?
Existing HTML style methods (such as <font SIZE> and <b>) may be easily combined with style sheet
specification methods. Browsers that do not understand style sheets will use the older HTML
formatting methods, and style sheets specifications can control the appearance of these elements in
browsers that support CSS1.
As a reader, how can I make my browser recognize my own style sheet?
Netscape
It is not possible to do this in Netscape yet (as of version 4.0.)
Internet Explorer 3.0 (Win95/NT)
[It is possible to do this at least in Windows95/NT, but no user interface is provided. Unknown how
this might be accomplished on other operating systems.]

1. Open the Registry editor (Start..Run..regedit..ENTER)


2. Under the 'HKEY_LOCAL_MACHINE\Software\Microsoft\InternetExplorer\Styles' key,
Edit..New..String Value
3. The new value should be called 'StyleSheet Pathname'
4. For the value, type in the full directory path of your .css style sheet.

Internet Explorer 4.0 (Win95/NT)

1. Under the View menu, select 'Internet Options'.


2. Under the 'General' tab, choose the 'Accessibility' button.
3. Choose the 'Format documents using my style sheet' check box and 'Browse...' to the location of
your .css style sheet.
How do I get rid of the gap under my image?
Images are inline elements, which means they are treated in the same way as text. Most people kind
of know this - they know that if you use 'text-align:center' on an image it will be centred. What many
people don't realise is that this means you will have a gap underneath an image. This gap is for the
descenders of letters like j,q,p,y and g. To get rid of this gap you need to make the image block-level
- like this :

CSS
img {display:block;}

One problem that this can cause is when you want to have a few images next to each other - if they
are block-level, they won't be next to each other. To get around that, you can use float:left. Of
course, this might present another problem - maybe you don't want the image to float left. In this
case, you can use an unordered list like this :

CSS
ul, li {
list-style-type:none;
padding:0;
margin:0 auto;
}
ul {
width:150px;
}
li {
float:left;
}
HTML
<ul>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
</ul>
Why use Style Sheets?
Style sheets allow a much greater degree of layout and display control than has ever been possible
thus far in HTML. The amount of format coding necessary to control display characteristics can be
greatly reduced through the use of external style sheets which can be used by a group of documents.
Also, multiple style sheets can be integrated from different sources to form a cohesive tapestry of
styles for a document. Style sheets are also backward compatible - They can be mixed with HTML
styling elements and attributes so that older browsers can view content as intended.
What does the "Cascading" in "Cascading Style Sheets" mean?
Style Sheets allow style information to be specified from many locations. Multiple (partial) external
style sheets can be referenced to reduce redundancy, and both authors as well as readers can specify
style preferences. In addition, three main methods can be employed by an author to add style
information to HTML documents, and multiple approaches for style control are available in each of
these methods. In the end, style can be specified for a single element using any, or all, of these
methods. What style is to be used when there is a direct conflict between style specifications for an
element?
Cascading comes to the rescue. A document can have styles specified using all of these methods, but
all the information will be reduced to a single, cohesive "virtual" Style Sheet. Conflict resolution is
based on each style rule having an assigned weight according to its importance in the scheme of
things. A rule with a higher overall importance will carry a higher weight. This will be used in place of
a competing style rule with a lower weight/importance. A hierarchy of competing styles is thus formed
creating a "cascade" of styles according to their assigned weights. The algorithm used to determine
this cascading weight scale is fairly complex.
What is CSS rule 'at-rule'?
There are two types of CSS rules: ruleset and at-rule. At-rule is a rule that applies to the whole style
sheet and not to a specific selector only (like in ruleset). They all begin with the @ symbol followed by
a keyword made up of letters a-z, A-Z, digits 0-9, dashes and escaped characters, e.g. @import or
@font-face.
What is selector?
CSS selector is equivalent of HTML element(s). It is a string identifying to which element(s) the
corresponding declaration(s) will apply and as such the link between the HTML document and the style
sheet.
For example in P {text-indent: 10pt} the selector is P and is called type selector as it matches all
instances of this element type in the document.
in P, UL {text-indent: 10pt} the selector is P and UL (see grouping); in .class {text-indent: 10pt} the
selector is .class (see class selector).
What is CLASS selector?
Class selector is a "stand alone" class to which a specific style is declared. Using the CLASS attribute
the declared style can then be associated with any HTML element. The class selectors are created by a
period followed by the class's name. The name can contain characters a-z, A-Z, digits 0-9, period,
hyphen, escaped characters, Unicode characters 161-255, as well as any Unicode character as a
numeric code, however, they cannot start with a dash or a digit. (Note: in HTML the value of the
CLASS attribute can contain more characters).It is a good practice to name classes according to their
function than their appearance.

.footnote {font: 70%} /* class as selector */

<ADDRESS CLASS=footnote/>This element is associated with the CLASS footnote</ADDRESS>


<P CLASS=footnote>And so is this</P>
What is CSS declaration?
CSS declaration is style attached to a specific selector. It consists of two parts; property which is
equivalent of HTML attribute, e.g. text-indent: and value which is equivalent of HTML value, e.g. 10pt.
NOTE: properties are always ended with a colon.
What is 'important' declaration?
Important declaration is a declaration with increased weight. Declaration with increased weight will
override declarations with normal weight. If both reader's and author's style sheet contain statements
with important declarations the author's declaration will override the reader's.

BODY {background: white ! important; color: black}

In the example above the background property has increased weight while the color property has
normal.
What is cascade?
Cascade is a method of defining the weight (importance) of individual styling rules thus allowing
conflicting rules to be sorted out should such rules apply to the same selector.
Declarations with increased weight take precedence over declaration with normal weight:

P {color: white ! important} /* increased weight */


P (color: black} /* normal weight */
Are Style Sheets case sensitive?
No. Style sheets are case insensitive. Whatever is case insensitive in HTML is also case insensitive in
CSS. However, parts that are not under control of CSS like font family names and URLs can be case
sensitive - IMAGE.gif and image.gif is not the same fi
How do I make my div 100% height?
You need to know what the 100% is of, so the parent div must have a height set. One problem that
people often come up against is making the main page fill the screen if there's little content. You can
do that like this :
CSS
body, html {
height:100%;
}
body {
margin:0;
padding:0;
}
#wrap {
position:relative;
min-height:100%;
}
* html #wrap {
height:100%;
}

Here, the #wrap div goes around your whole page - it's like a sub-body.

You need to use 'min-height' rather than 'height' for Firefox because otherwise it will set it to 100% of
the viewport and no more. Internet Explorer, being well... crap, treats 'height' as it should be treating
'min-height' which it doesn't recognise. (You can target IE by preceding your code with ' * html ').

To make floated divs within this #wrap div 100% of the #wrap div... well that's more difficult. I think
the best way is to use the 'faux columns' technique which basically means that you put the
background in your body rather than your columns. If the body has columns and your floats don't then
it looks like your floated content is in a column that stretches to the bottom of the page. I've used this
technique in my layout demos.

The problem is often not that the columns aren't 100% height, but that they're not equal lengths.
Columns usually don't start from the top of the page and end at the bottom - there's often a header
and a footer or sometimes, more interesting designs don't have a recognisable columnar layout, but
do require div boxes to be equal heights. This can be done with the aid of a couple of images and
some css or with some javascript.
What is property?
Property is a stylistic parameter (attribute) that can be influenced through CSS, e.g. FONT or WIDTH.
There must always be a corresponing value or values set to each property, e.g. font: bold or font:
bold san-serif.
How do I write my style sheet so that it gracefully cascades with user's personal sheet ?
You can help with this by setting properties in recommended places. Style rules that apply to the
whole document should be set in the BODY element -- and only there. In this way, the user can easily
modify document-wide style settings.
What are pseudo-elements?
Pseudo-elements are fictional elements that do not exist in HTML. They address the element's sub-
part (non-existent in HTML) and not the element itself. In CSS1 there are two pseudo-elements: 'first-
line pseudo-element' and 'first-letter pseudo-element'. They can be attached to block-level elements
(e.g. paragraphs or headings) to allow typographical styling of their sub-parts. Pseudo-element is
created by a colon followed by pseudo-element's name, e.g:

P:first-line
H1:first-letter

and can be combined with normal classes; e.g:

P.initial:first-line

First-line pseudo-element allows sub-parting the element's first line and attaching specific style
exclusively to this sub-part; e.g.:

P.initial:first-line {text-transform: uppercase}

<P class=initial>The first line of this paragraph will be displayed in uppercase letters</P>

First-letter pseudo-element allows sub-parting the element's first letter and attaching specific style
exclusively to this sub-part; e.g.:

P.initial:first-letter { font-size: 200%; color: red}

<P class=initial>The first letter of this paragraph will be displayed in red and twice as large as the
remaining letters</P>
As a developer who works with CSS every day, I find one complication that continues to
bother me in my daily work. Support for CSS has always been good on the horizontal scope,
but vertical positioning has always been quite complicated. Alone the procedure to affix a
footer to the bottom of a screen in dependance of the amount of content is unnecessarily
difficult. The old table method provided much easier methods for this. What are your
thoughts on this and do you see improvement following in future CSS revisions?
Indeed, the CSS formatting model allows more control horizontally than vertically. This is due to
(typically) having a known width, but an unknown height. As such, the height is harder to deal with.
However, CSS2 fixed positioning allows you to place content relative to the viewport (which is CSS-
speak for window) instead of the document. For example, by setting position: fixed; bottom: 0 on an
element, it will stick to the bottom. This works in Opera, Safari and Mozilla-based browsers. IE6
doesn't support it, however. It remains to be seen if IE7 will support it.
How can I make a page look the same in e.g. NS and MSIE ?
The simple answer is, you can't, and you shouldn't waste your time trying to make it exactly the
same. Web browsers are allowed, per definition, to interpret a page as they like, subject to the
general rules set down in the HTML and CSS specifications. As a web author you can not have a prior
knowledge of the exact situation and/or medium that will be used to render your page, and it's almost
always rather counterproductive to try to control that process. There is no necessity for a well-written
page to look the same in different browsers. You may want to strive to ensure that it looks good in
more than one browser, even if the actual display (in the case of graphical browsers) comes out a bit
different. "Looking good" can be achieved by adopting sensible design and guidelines, such as not
fixing the size or face of your fonts, not fixing the width of tables, etc? Don't fight the medium; most
web users only use one browser and will never know, or bother to find out, that your page looks
different, or even "better", in any other browser.
Is there anything that CAN'T be replaced by Style Sheets?
Quite a bit actually. Style sheets only specify information that controls display and rendering
information. Virtual style elements that convey the NATURE of the content can not be replaced by
style sheets, and hyperlinking and multimedia object insertion is not a part of style sheet functionality
at all (although controlling how those objects appear IS part of style sheets functionality.) The CSS1
specification has gone out of its way to absorb ALL of the HTML functionality used in controlling display
and layout characteristics. For more information on the possible properties in CSS, see the Index DOT
Css Property Index.
Rule of Thumb: if an HTML element or attribute gives cues as to how its contents should be displayed,
then some or all of its functionality has been absorbed by style sheets.
Can I include comments in my Style Sheet?
Yes. Comments can be written anywhere where whitespace is allowed and are treated as white space
themselves. Anything written between /* and */ is treated as a comment (white space). NOTE:
Comments cannot be nested.
What is the difference between ID and CLASS?
ID identifies and sets style to one and only one occurrence of an element while class can be attached
to any number of elements. By singling out one occurrence of an element the unique value can be
declared to said element.

CSS
#eva1 {background: red; color: white}
.eva2 {background: red; color: white}

HTML - ID
<P ID=eva1>Paragraph 1 - ONLY THIS occurrence of the element P (or single occurrence of some
other element) can be identified as eva1</P>
<P ID=eva1>Paragraph 2 - This occurrence of the element P CANNOT be identified as eva1</P>

HTML - CLASS
<P class=eva2>Paragraph 1 - This occurrence of the element P can be classified as eva2</P>
<P class=eva2>Paragraph 2 - And so can this, as well as occurrences of any other element, </P>
How to make text-links without underline?
a:link, a:visited {text-decoration: none}

or

<a style="text-decoration: none" HREF="...">

...will show the links without underlining. However, suppressing the underlining of links isn't a very
smart idea as most people are used to having them underlined. Also, such links are not spotted unless
someone coincidentally runs a mouse over them. If, for whatever reason, links without underline are
required background and foreground colors can be instead declared to them so that they can be
distinguished from other text, e.g.;
a:link, a:visited {text-decoration: none; background: red; color: blue}

or

<a style="text-decoration: none; background: red; color: blue" HREF="...">

Both background and foreground colors should be specified as the property that is not specified can be
overridden by user's own settings.
How do you make a tool tip that appears on hover?
The most simple way is to use the 'title' attribute like this...

HTML
<span title="Example of the title attribute in use">like this</span>

CSS
a.tooltip {
position:relative;
cursor:help;
}
a.tooltip span {
display: none;
position:absolute;
top:1.5em;
left:0;
width:15em;
padding:0 2px;
}
a.tooltip:hover {
display:inline;
}
a.tooltip:hover span {
display:block;
border:1px solid gray;
background-color:white;
}

HTML

<a class="tooltip" href="#n">Karl Marx<span>-info goes here-</span></a>

Without this part... a.tooltip:hover {


display:inline;
}

..it won't work in IE.

The "#n" in the link is to prevent the page from jumping to the top if the link is clicked. The "href"
part is necessary as it won't work in IE without it.
Which characters can CSS-names contain?
The CSS-names; names of selectors, classes and IDs can contain characters a-z, A-Z, digits 0-9,
period, hyphen, escaped characters, Unicode characters 161-255, as well as any Unicode character as
a numeric code. The names cannot start with a dash or a digit. (Note: in HTML the value of the CLASS
attribute can contain more characters).
What browsers support style sheets? To what extent?
Microsoft's Internet Explorer version 3.0 Beta 2 and above supports CSS, as does Netscape
Communicator 4.0 Beta 2 and above and Opera 3.5 and above. Take note that the early
implementations in these browsers did not support ALL of the properties and syntax described in the
full CSS1 specification and beyond. Later versions have been getting much closer to full CSS1
compliance, but then comes the next hurdle - CSS2...it was such a big leap over CSS1 that it has
taken the browsers years to come close to supporting a majority of CSS2's features. Mozilla and
Opera's current versions both offer excellent CSS standards compliance. The Macintosh version of
Internet Explorer is said to be very impressive in its CSS capabilities as well, but PC IE lags behind
these implementations. Quite a few other implementations of CSS now exist in browsers that are not
as widely-used (such as Amaya, Arena and Emacs-W3), but coverage of features in these documents
currently only covers Internet Explorer, NCSA Mosaic, Netscape and Opera browsers.
What is cascading order?
Cascading order is a sorting system consisting of rules by which declarations are sorted out so that
there are not conflicts as to which declaration is to influence the presentation. The sorting begins with
rule no 1. If a match is found the search is over. If there is no match under rule no 1 the search
continues under rule no 2 and so on.

1. Find all declarations that apply to a specific selector/property and Declare the specified style if the
selector matches the element if there isn't any Let the element inherit its parent property if there isn't
any Use initial value

2. Sort by weight (! important) Increased weight take precedence over normal weight

3. Sort by origin Rules with normal weight declared in author's style sheet will override rules with
normal weight declared in user's personal style sheets Rules with increased weight declared in user's
personal style sheet will override rules with normal weight declared in author's style sheet Rules with
increased weight declared in author's style sheet will override rules with increased weight declared in
user's personal style sheets Author's and user's rules will override UA's default style sheet.

4. Sort by selector's specificity More specific selector will override less specific one: ID-selector (most
specific), followed by Classified contextual selectors (TABLE P EM.fot) Class selectors (EM.fot)
Contextual selectors - the "lower down" the more weight, (TABLE P EM), (TABLE P EM STRONG) -
STRONG has more weight than EM.

5. Sort by order specified If two rules have the same weight, the latter specified overrides ones
specified earlier. Style sheets are sorted out as follows: The STYLE attribute (inline style) overrides all
other styles The Style element (embedded style) overrides linked and imported sheets The LINK
element (external style) overrides imported style The @import statement - imported style sheets also
cascade with each other in the same order as they are imported
Why shouldn't I use fixed sized fonts ?
Only in very rare situations we will find users that have a "calibrated" rendering device that shows
fixed font sizes correct. This tells us that we can never know the real size of a font when it's rendered
on the user end. Other people may find your choice of font size uncomfortable. A surprisingly large
number of people have vision problems and require larger text than the average. Other people have
good eyesight and prefer the advantage of more text on the screen that a smaller font size allows.
What is comfortable to you on your system may be uncomfortable to someone else. Browsers have a
default size for fonts. If a user finds this inappropriate, they can change it to something they prefer.
You can never assume that your choice is better for them. So, leave the font size alone for the
majority of your text. If you wish to change it in specific places (say smaller text for a copyright notice
at the bottom of page), use relative units so that the size will stay in relationship to what the user
may have selected already. Remember, if people find your text uncomfortable, they will not bother
struggling with your web site. Very few (if any) web sites are important enough to the average user to
justify fighting with the author's idea of what is best.
How do you make a whole div into a link?
You can't put 'a' tags around a div, but you can do this with javascript :

HTML
<div onclick="javascript:location='http://bonrouge.com'" id="mydiv">
... stuff goes here ...
</div>

If you want to use an empty div with a background image as a link instead of putting your image into
the html, you can do something like this:

CSS
#empty {
background-image:url(wine.jpg);
width:50px;
height:50px;
margin:auto;
}
#empty a {
display:block;
height:50px;
}
* html #empty a {
display:inline-block;
}

HTML
<div id="empty"><a href="#n"></a></div>
How do I have links of different colors on the same page?
Recommending people to use classes in their 'a' tags like this :

CSS
a.red {
color:red;
}
a.blue {
color:blue;
}

HTML
<a href="#" class="red">A red link</a>
<a href="#" class="blue">A blue link</a>
This is a valid way to do it, but usually, this isn't what a page looks like - two links next to each other
with different colours - it's usually something like a menu with one kind of link and main body text or
another menu with different links. In this (normal) situation, To go higher up the cascade to style the
links. Something like this :

CSS
a{
color:red;
}
#menu a {
color:blue;
}

HTML
<ul id="menu">
<li><a href="#">A red link</a></li>
<li><a href="#">A red link</a></li>
</ul>
<div id="content">
<p>There's <a href="#">a blue link</a> here.</p>
</div>
What is shorthand property?
Shorthand property is a property made up of individual properties that have a common "addressee".
For example properties: font-weight, font-style, font-variant, font-size, font-family, refer to the font.
To reduce the size of style sheets and also save some keystrokes as well as bandwidth they can all be
specified as one shorthand property font, e.g.:

H1 {font-weight: bold;
font-style: italic;
font-variant: small-caps;
font-size: 160%;
font-family: serif}

can be all shorthanded to a space separated list:

H1 {font: bold italic small-caps 160% serif}

Note: To make things even simpler the line-height property can be specified together with the font-
size property:

H1 {font: bold italic small-caps 160%/170% serif}


How to use CSS building a standards based HTML template?
It should:
1. Contain: header, navigation, content, footer
2. Use well-structured HTML
3. Be error-free and encourage good coding

Let?s start with number one there:

HTML document split up in four parts all with different meaning, use the
-tag. Div is short for ?division? and isn?t header, navigation and so on ...

!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">


<html lang="en">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<title>Your own page title</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>

<div id="header">
<h1>The name of this page</h1>
</div>
<div id="navigation">
<h2>Navigation</h2>
<ul>
<li><a href="first.html">First</a></li>
<li><a href="second.html">Second</a></li>
<li><a href="third.html">Third</a></li>
</ul>
</div>
<div id="content">
<h2>Content</h2>
<p>Some sample content, add your own here</p>
</div>
<div id="footer">
<p>This page is written by [Your name] and builds
n a <a href="http://friendlybit.com">
Friendlybit template</a>.</p>
</div>

</body>
</html>

body {
background-color: Green;
}
div {
border: 3px solid Black;
padding: 7px;
width: 600px;
}
h1, h2, h3, h4, h5, h6 {
margin: 0;
}

#navigation {
float: left;
width: 150px;
}
#content {
float: left;
width: 430px;
}
#footer {
clear: both;
}
How do I get my footer to sit at the bottom...?
Need a div which makes space at the bottom of the main page (inside the #wrap div). Then, the
footer (being inside #wrap) can be placed in that space by using absolute positioning. Like this :

CSS body, html {


height:100%;
}
body {
margin:0;
padding:0;
}
#wrap {
position:relative;
width:780px;
margin:auto; min-height:100%;
}
* html #wrap {
height:100%;
}
#clearfooter {
height:50px;
overflow:hidden;
}
#footer {
position:absolute;
bottom:0;
width:100%;
height:50px;
}

HTML
<div id="wrap">
...content goes here...
<div id="clearfooter"></div>
<div id="footer">Footer</div>
</div>
Can I attach more than one declaration to a selector?
Yes. If more than one declaration is attached to a selector they must appear in a semi colon separated
list, e.g.;
Selector {declaration1; declaration2}
P {background: white; color: black}
Border around a table?
Try the following:

.tblboda {
border-width: 1px;
border-style: solid;
border-color: #CCCCCC;
}
/*color, thickness and style can be altered*/

You put this style declaration either in


an external stylesheet, or you can stuff it in
the <head></head> section, like:

<style type="text/css">
(here you can place your styles)
</style>

and apply it to the table as follows:

<div class="tblboda">
<table yaddayadda>
<tr>
<td>Content text and more content</td>
</tr>
</table>
</div>

That should give you a grey thin border around this table.

If you want the border to 'shrink wrap' around the table, then you have to use the <span> tag instead
the
tag. But that is not quite proper CSS or HTML, because a is for inline elements. A table is not an inline
element, therefore the correct tag is a <div>. If you play around with it a bit then you have a good
chance to achieve what you want and still have correct HTML/CSS.

The other way would be that you apply the class .tblboda directly to the table (for IE and other
contemporary browsers), like <table ... class="tableboda"> and you define another class for each
stylesheet: .tblboda2

In the NN4.xx stylesheet, you use the same properties as above, and in the IE and other
contemporary browsers you carefully set all those properties to default, like {border-style: none;}

Then you wrap the table in the <div> with the class .tblboda2 (NN4.xx does that) (IE a.o.c.b. don't do
anything, because the border-style is set to "none" = no border at all).
This way you have a table that is wrapped in a nice little border: .tblboda2 for NN4.xx, .tblboda for IE
and other modern browsers.
How do you target a certain browser?
IE can be targetted by preceding your properties with '* html'. For example...

#nav {
position:fixed;
}
* html #nav { /* this will target IE */
position:absolute;
}

Another way to target IE is with conditional comments. Put this (below) in the head - just before the
closing tag - and put anything you want to be directed only at IE in another stylesheet.
<!--[if IE]>
<link href="ieonly.css" rel="stylesheet" type="text/css">
<![endif]-->

If you need to target IE5x...

#wrap {
width:760px; /* for IE5x */
w\idth:780px; /* for all other major browsers */
}

Das könnte Ihnen auch gefallen