C# INTERVIEW QUESTIONS - Part 2

What’s the implicit name of the parameter that gets passed into the class’ set method?
Value, and its datatype depends on whatever variable we’re changing.

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

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

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

Are private class-level variables inherited?
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

Describe the accessibility modifier protected internal. It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).
C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one.

How many constructors should I write?
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

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

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

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

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

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

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

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

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

When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?
When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

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

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

Can you inherit multiple interfaces?
Yes.

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

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

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

If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

What’s the difference between System.String and System.StringBuilder classes?
System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

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 and XML documentation tag?
Single line code example and multiple-line code example.

Is XML case-sensitive?
Yes, so and 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.

ASP.NET Interview Questions

Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

What’s the difference between Response.Write() andResponse.Output.Write()?
Response.Output.Write() allows you to write formatted output.

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

When during the page processing cycle is ViewState available?
After the Init() and before the Page_Load(), or OnLoad() for a control.

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

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

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

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

Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler?
Add an OnMouseOver attribute to the button.
Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");

What data types do the RangeValidator control support?
Integer, String, and Date.

Explain the differences between Server-side and Client-side code?
Server-side code executes on the server. Client-side code executes in the client's browser

What type of code (server or client) is found in a Code-Behind class?
The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.

Should user input data validation occur server-side or client-side? Why?
All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user.

What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.· A DataSet is designed to work without any continuing connection to the original data source.· Data in a DataSet is bulk-loaded, rather than being loaded on demand.· There's no concept of cursor types in a DataSet.· DataSets have no current record baller You can use For Each loops to move through the data.· You can store many edits in a DataSet, and write them to the original data source in a single operation.· Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.

What is the Global.asax used for?
The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.

What are the Application_Start and Session_Start subroutines used for?
This is where you can set the specific variables for the Application and Session objects.

Can you explain what inheritance is and an example of when you might use it?When you want to inherit (use the functionality of) another class.
Example: With a base class named Employee, a Manager class could be derived from the Employee base class.

Whats an assembly?
Assemblies are the building blocks of the .NET framework.

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

Explain what a diffgram is, and a good use for one?
The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.

Whats MSIL, and why should my developers need an appreciation of it if at all?
MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.

Which method do you invoke on the DataAdapter control to load your generated dataset with data?
The Fill() method.

Can you edit data in the Repeater control?
No, it just reads the information from its data source.

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

How can you provide an alternating color scheme in a Repeater control?
Use the AlternatingItemTemplate.

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

What base class do all Web Forms inherit from?
The Page class.

Name two properties common in every validation control?
ControlToValidate property and Text property.

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

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

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

What is the transport protocol you use to call a Web service?
SOAP (Simple Object Access Protocol) is the preferred protocol.

What does WSDL stand for?
Web Services Description Language.

Where on the Internet would you look for Web services?
http://www.uddi.org/

To test a Web service you must create a Windows application or Web application to consume this service?
False, the web service comes with a test page and it provides HTTP-GET method to test.

What is ViewState?
ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.

What is the lifespan for items stored in ViewState?
Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page).

What does the "EnableViewState" property do? Why would I want it on or off?
It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.

What are the different types of Session state management options available with ASP.NET?
ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.

What are the Application_Start and Session_Start subroutines used for?
This is where you can set the specific variables for the Application and Session objects.

Can you explain what inheritance is and an example of when you might use it?When you want to inherit (use the functionality of) another class.
Example: With a base class named Employee, a Manager class could be derived from the Employee base class.

Whats an assembly?
Assemblies are the building blocks of the .NET framework.Describe the difference between inline and code behind.Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

Explain what a diffgram is, and a good use for one?
The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.

Whats MSIL, and why should my developers need an appreciation of it if at all?
MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.

How can you provide an alternating color scheme in a Repeater control?
Use the AlternatingItemTemplate.

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

Name two properties common in every validation control?
ControlToValidate property and Text property.

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

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

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

Beginners Guide to Javascript

JavaScript – History

  • Developed by Netscape Corporation known as “Live Script”
  • It was later renamed to its present name by Netscape, which had a joint venture with Sun Microsystems
  • JavaScript supports server-side scripting also, separately known as Livewire
  • First supported in Netscape Navigator 2.0.
  • Now - Internet Explorer from Microsoft, Personal Web Client 3.0 from Lotus and Mosaic 2.0 and so on.
  • JavaScript was also referred to as ECMA Script. ECMA is the short form for European Computer Manufacturer’s Association.

JavaScript Vs Java

  • JavaScript has nothing to do with Java language
  • Java is purely an object-oriented language, JavaScript is just a scripting tool
  • JavaScript is not compiled and executed; the client directly interprets it
  • JavaScript is a freely typed language whereas Java is a strongly typed one
  • Object references must exist at compile-time in Java (static binding) whereas they are checked only at runtime in JavaScript (dynamic binding)

JavaScript Characteristics

  • JavaScript adopts an object-based technology
  • It is not purely object-oriented
  • Using JavaScript, we can create objects of our own
  • JavaScript is platform independent. We will be coding our scripts inside a HTML page, and they are not dependent on any specific platform. They rely on user agents. In most of the cases, browsers play a role as user-agents.
  • It is based on an event-driven model


JavaScript Advantages

  • control the frame navigation
  • include a plug-in or a Java applet inside a page
  • Form Validation in the client’s place itself, thereby reducing the burden on the server
    images can swap when the user moves a mouse over them,
  • calculations can be made without having to resort to a CGI script
  • JavaScript timer on the client to check how much time he/she takes to fill a form.
  • Apart from all these advantages, JavaScript is very easy to learn.

JavaScript Versions

  • JavaScript 1.0
    Mathematical calculations, provide programming structures like statements and functions and do things to HTML elements
    Can read out or write into form elements, load new pages into another frame or window, on the page and do calculations with date and time

  • JavaScript 1.1
    Support for changing images, the mouse over script, and the support of window focus. Graphical effects were also possible.

  • JavaScript 1.2
    Support of DHTML

  • JavaScript 1.3,
    Level 1 DOM has been implemented in all browsers

JavaScript Compatibility

  • 1995-1996
    JavaScript 1.0
    Netscape Navigator 2.0, Microsoft Internet Explorer 3.0,

  • 1996
    JavaScript 1.1
    Netscape Navigator 3.0, Hot java 3, Opera 3

  • 1997
    JavaScript 1.2
    Netscape Navigator 4.0, Microsoft Internet Explorer 4.0, Netscape 4, Explorer 4, Opera 4, Omni web, Opera 5

  • 1998-1999
    JavaScript 1.3
    Netscape Navigator 4.5+, Microsoft Internet Explorer 5+

User Interactivity through JavaScript

Functions used to interact with the client
alert()
prompt()

The alert method displays a dialog box in the browser with the text string passed as an argument

The prompt method is used get some information from the user
It displays a prompt dialog box and captures the value entered by the user.
We can store the value entered by the user in a variable

Programming JavaScript

Data Types
Number
4.5, 8.2, 7
Any number either it’s a positive, negative or zero or decimal

Boolean
true, false
A logical true or false

String
“Center”, “Ship!”
Any string inside the quotation marks. Special characters are also allowed.

Object
Car, book
Any “thing” that has got methods and properties

Function
alert(), confirm()
Definition of a function

Variables

Variables can be created using var keyword
var temp
var onemoretemp, strtemp

Assigning values to variables
temp = 45
onemoretemp = temp
strtemp= ”temp value”

Operators

Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
String concatenation operator is “+”
Pre-increment operator and post-increment operators (++)
Pre-decrement and post-decrement operators (--)
NOT ( ! )
Bit wise XOR ( ^ )
AND ( && )
Shift Left ( << ) OR ( ) Shift Right Zero fill ( >>> )
Bit wise AND ( & )
Shift Right with Sign ( >> )
Bit wise OR ( )
Identity ( === )
Bit wise NOT ( ~ )
Non identity (!= )

Arrays

Used to store multiple data, based on an index, in one storage structure
The index starts from zero
var k=new Array();
var t=new Array(“rama”, “rahim”, “Robert”,5,8);
document.write(t[0]);
JavaScript supports multi-dimensional arrays also.

Data Type Conversions

JavaScript is a dynamically typed language
var answer = 42
answer = "Thanks for all the fish..."


We can convert a number in to string and vice versa

parseInt method - used to convert a string value, which is holding a number data type
temp = parseInt(“42”)
anoth = parseInt(“54.34”)
Str=””+2500;
Str=””+temp;

Simply adding an empty quote to a number value will convert a number into string data type.

Decision Constructs

If…else

If (condition)
{
statements, if it is true
}
else
{
statements if it is false
}

For Multiple Conditions

if(condition){
Statements
}
else if (condition) {
statements
}


Sample Program

var type;
type=prompt("enter the user type","");
if(type=="admin")
document.write("Welcome Administrator");
else if(type=="user")
document.write("Welcome user");
else
document.write("Sorry…");


Switch…case
Used for multiple conditions

Sample Program

var type;
type=prompt("Enter the user type","");
switch(type)
{
case "admin": document.write("Welcome Administrator"); break;
case "user": document.write("Welcome user"); break;
default: document.write("Sorry…");
}


Loops

The while and for statements are used to execute a block of code for as long as a certain condition is valid

while(expression)
{
Statements
}

for(initialization; condition; increment/decrement)
{
one or more statements
}

The break statement is used to exit a loop such as from for or while blocks


Sample Program

var i;
document.write("

");
for(i=1;i<=15;i++){ document.write(" ");}
document.write("
",i,"",i*i,"
");


Functions or Methods

Group of code that handles actions invoked by event handlers (more on this, later) or by simple statements
reduces the writing of the code again and we can reuse the same

Two types:-

built-in functions and user-defined functions

Built-in functions - functions which are already existing in the language itself
E.g., parseInt, alert, prompt etc.,
User-defined functions - written by the user to make our scripts scalable
Syntax for a function is as follows.

function functionname(arg1,arg2….)
{
Body
}

Sample Program

function givehalfvalue(k)
{
return k/2;
}

function displayargs()
{
document.write("
","Arguments passed to this function are:-
");
for(i=0;i");
}


var i;
i=prompt("Enter either 1 or 2","");
if (i==1)
{
alert("You have chosen givehalfvalue function");
i=givehalfvalue(i);
document.write(i);
}
else if (i==2)
{
alert("You have chosen display args function");
tot=prompt("How many arguments are you going to enter","Enter a number please");
var args=new Array();
for(i=0;iConfirm() Method

Similar to the alert method
Displays a dialog box and asks the user to proceed further or not
Returns either TRUE or FALSE based on the selection during the method call
Method brings up a dialog box that prompts the user to select either 'o.k.' or 'cancel', the first returning TRUE and the latter, FALSE


Sample Program

var opt;
opt=confirm("Do you want to delete all the records?");
if(opt)
alert("Your Records will be deleted !!!");
else
alert("No deletion of the records !!!");


Events & Event Handlers

JavaScript is based on event-driven model
Predetermined events and event handlers that deal with those events
Event handlers fire those events whenever that event happens.

Events

Blur : Occurs when the focus is removed
Focus : Occurs when the user gives input or focus to an element in the form
Change : ccurs when the user changes some value of a field
Click : Arises when the user clicks on a link or an element in the form
Double Click : Occurs when the user double clicks
Key Down : Occurs when the key makes its first contact
Key Up : When the contact with the key is released
Load : Occurs when the page is loaded
UnLoad : Occurs when the current window is cleared from view
Error : Occurs when there is a transfer error
Mouse Down : Occurs when the user presses any of the buttons of a mouse
Mouse Up : Occurs when the user releases the button.
Mouse Over : Occurs whenever the cursor rolls into the rectangular space of the object in the screen
Mouse Out : Occurs when the cursor is moved outside the rectangle space
Submit : When the user submits a form of a page
Reset : Whenever the form is reset
Select : Occurs when the option is selected
Resize : If the user resizes the window

Events & Objects

Each and every element of the form will have some restricted events associated with it

Blur - Button, Checkbox, File Upload, Frame, Layer, Password, Radio, Reset, Select, Submit, Text, Text area, Window
Focus - Button, Checkbox, File Upload, Frame, Layer, Password, Radio, Reset, Select, Submit, Text, Text area, Window
Change - FileUpload, Select, Text, Text area
Click - Button, Checkbox, Document, Links, Radio, Reset, Submit
Double Click - Area, Document, Links
Key Down - Document, Image, Links, Text area
Key Up - Document, Image, Links, Text area
Load - Document, Image, Layer, Window
UnLoad - Document, Window
Error - Window, Image
Mouse Down - Button, Document, Link
Mouse Up - Button, Document, Link
Mouse Over - Area, Layer, Link
Mouse Out - Area, Layer, Link
Submit, Reset - This is for a page
Select - Text, Text Area
Resize - Frame, Window

JavaScript Object Model

Models HTML documents in a very consistent and intuitive way
Provides an interface to access, navigate, and manipulate web page
DOM allows you to access and update the content, structure, and style of a document
To provide more interactive content on the Web
DOM allows HTML to be manipulated dynamically
Each HTML tag can be accessed and manipulated via its ID and NAME attributes
Each object has its own properties, methods, and events
The Object Model allows you to navigate along the document tree, up and down, and to the sides
You can use the child, parent, and sibling relationships to go from a particular point to any other point on your page tree

Model is divided into three sub-groups
Language objects
Form-field objects
Browser objects

Browser Objects
navigator
window
document
location
history
anchor
link
frame
image

Form-Field Objects
Button
Checkbox
Radio
Text
Reset
Text Area
Password
Select
Submit
Hidden

Language Objects
Date
Array
Math
String

JavaScript Object Model



Language Objects

The Date Object

All information related to date and time can be accessed
Built-in methods of JavaScript allow us to access the date and time values that are stored in a date object
getDate() Gets the number of the day (between 1 and 31)
getDay() Gets the day of the week (0 through 6, 0 is for Sunday)
getMonth() Gets the number of the month (0 through 11, 0 is for January)
getYear() Returns the year part of the date object.
getSeconds() Returns the seconds portion of the date object
getminutes() Gets the number of minutes ( 0 through 59)
getHours() Returns the hour part of the Date object
goGMTString( ) Returns the string in representing the universal date time of date object.
goLocalString() Returns the date in the local system’s format
setDate(), setMonth(), setYear(), setHours(), setMinutes(), setSeconds() and setTime() methods to assign values to the Date object

Sample Program:

date = new Date();
document.write(date.getMonth());

The Math Object

Commonly used methods of the Math object
abs(number) -- Returns the absolute value
ceil(numb) -- Returns the smallest integer greater than or equal to the number
floor(number) -- Returns a largest number less than or equal to the number
sin(numb) -- Returns the sine of the number
cos(numb) -- Returns the cosine of the number
tan(number) -- Returns the tangent of the number
acos(number) -- Returns arccosine of the number
asin(number) -- Returns arcsine of the number
atan(number) -- Returns arctangent of the number
sqrt(number) -- Returns the square root of the number
round() -- Returns a number to its nearest integer
max(num1,num2) -- Returns the largest of two arguments
min(num1,num2) -- Returns the smallest of two arguments
log(num) -- Returns the natural logarithm(base E) of the number
exp(num) -- Returns exponential value of the number
random() -- Returns a random number between 0 and 1
pow(x,y) -- Returns the x to the power of y value

The String Object

Although JavaScript is not a “strongly typed” language, we still need to be aware of their impact on the way we work in the Forms
Length is the main property of the String object
It gives us the total number of characters in the string.

Commonly used methods of the String object

charAt(index) -- Returns one-character from the string based on the specified index
lastIndexOf(searchstring) -- Returns the index value of the last character within the string where the searchstring begins
indexOf(searchstring) -- Returns the index value of the first occurrence of the searchstring
concat(string) -- Returns the combined string
replace(expression, replacestr) -- Replaces all that matched expressions with the replacestr and returns the replaced string
search(expression) -- Returns the offset integer of the matching expression
slice(startindex) -- To extract a portion of one string and to create a new string as a result (without modifying the original string)
split(delimeter) -- Splits the string based on the delimiter specified and return an array of delimited items.
substring(i1,i2) -- To extract a copy of a substring starting from index i1 till i2 from the original string.
toLowerCase(),toUpperCase() -- Converts the string to lowercase and uppercase characters.

Methods used to format the strings in JavaScript

String.bold() -- Makes the string in to bold face
String.fontcolor(color) -- Converts the string to the color specified
String.italics() -- Makes the string italicized
String.big(),String.small() -- Increases or decreases the weight of the font
String.fontsize(number) -- Converts the string with the font number specified
String.link(URL) -- Links the string to the specified URL

Browser Objects

Window Object

Creating a Window

Its not possible to create the main window of the browser
Once the main window is open, we can generate as many sub-windows as possible through JavaScript.
window.open() is the method used to create the new window

Paremeters required
URL of the document to load
the name of the document
the physical properties of the window

Third parameter - the physical properties of the window is used to position the new window in the screen.
left - Specifies the left x coordinate on the screen, to open the window.
top - Specifies the top y coordinate on the screen, to open the window.
scrollbars - Creates scroll bars when the page grows beyond the current screen.
location - Creates location field.
toolbar - Displays the standard toolbar.
menubar - Creates menu at the top of the window.
resizable - Enables/disables resizing of the window by the user.
width, height - Specifies the width and height of the window in pixels.
statusbar - Displays the status bar of the window.

Closing a Window
windowname.close() is used to close a particular window


Sample Program :

1) var nwindow = window.open("clock.htm","first","height=300,width=200");

2) var nwindow = window.open("clock.htm","first","height=300,width=200, scrollbar=no, location=no, resizable=no,menubar=no");

3) document.write("Close");


Location Object

Represents the URL loaded into the window
Used to navigate to a page in our own site or any other page in the Internet

location.href = “http://www.shyamsrinivas.info/

newwin.location.href = “./bankbalance.asp”

Sample Program :

var nwindow = window.open("clock.htm","first","height=300,width=200");
location.href = "http://www.shyamsrinivas.info/";
nwindow.location.href = http://www.shyamsrinivas.info/;


History Object

Every time we visit a page, it will get stored in the history list
Whenever we press the forward or back buttons in our browser we are accessing the history.back() and history.forward() methods of the history object

forward()
Sends the user to the next page, according to the history list
back()
Sends the user to the previous page, according to the history list

Document Object

The document object we can access each and every element inside the HTML page

Sample Program :

document.write("Foreground Color = ",document.fgColor)
document.write("
")
document.write("Background Color = ",document.bgColor)
document.write("
")
document.write("Active Links Color = ",document.alinkColor)
document.write("
")
document.write("Visted Links Color = ",document.vlinkColor)
document.write("
")
document.write("Link Color = ",document.linkColor)
document.write("
")
document.write("File Creation Date = ",document.fileCreatedDate)
document.write("
")
document.write("File Modified Date = ",document.fileModifiedDate)
document.write("
")
document.write("Total File Size =",document.fileSize)
document.write("
")
document.write("Last Modified Date = ",document.lastModified)
document.write("
")
document.write("Total Anchors = ",document.anchors.length)
document.write("
")
document.write("Total Form Elements = ",document.forms.length)


Methods of the document Object
write() Writes the text of content to the document
clear() Clears the document window

Image Object

We can manipulate the properties of the images using this object
All the images inside a particular document are stored in the images array
document.images[0].src=”first.jpg”


Form Object

Provides us an opportunity to access the forms inside a document
All the forms are contained in an array, which starts from 0
We can give the form name itself as a parameter to access a particular form
document.forms(“myform”) or document.forms(0)


Form-Field Objects

Accessing Form Fields

To access a form object, we can refer it either by its name or by its index number in the form elements array

document.forms[0].elements[0].value or
document.myform.userid.value

The form array will hold all the elements in the form including submit and reset button, if available