Use of Proper File Extensions


Never put ASP or other server side scripting code in files other than .ASP. Code in non-ASP files (e.g., .inc) exposes the site to several security holes. If using the FrontPage Server Extensions, put include files in the "_private" directory for added security. If there are not any server side scripts in a file, name the file .HTM. The web server will skip ISAPI calls, thus serving up the page more quickly. Global.ASA specifically is as safe as an ASP file. Dead files can lead to places for people to hack. This is especially true for files other then .HTM or .ASP. .LOG files (for example generated by FTP) can provide details of your file structure and file names best not shared with the world. It is strongly recommended that all dead files should be removed from the web server

Type Notation

Use proper Hungarian notation for variables and objects. The purpose of Hungarian notation is to be able to interpret the type and purpose of a variable. For local and public variables use mixed case of an initial lowercase Hungarian prefix followed by at least one uppercase letter. See table of prefixes below:
In general programmers should choose and consistently follow either the long or short Hungarian notation as below:
1 letter 3 letter
S str string sLastName, strFirstName
I int Integer iLoopVar, intQuantity
L lng Long lCountofRows, lngRecordsAffected
B bln Boolean bSold, blnFileClosed
D dbl Double dNationalDebt, dblStarsinUniverse
C cur Currency cAmount, curPrice
T dt DateTime tDOB, dtApproved
O obj Objects oRS, objConnection
X x Structures or other xOblique, xFiles
Hungarian notation can also be used with form objects to make forms more clear, although many programmers choose to use all uppercase meaningful names for POST type forms and very short uppercase names for GET type forms as most of the HTML form elements are variations on <INPUT&gt.
Prefix Form Component
txt Input Box
chk Checkbox
opt Option/Radio Control
cmd Button
img Image
hdn hidden Input
Use 'c' + all upper case for constants. Constants should be used whenever possible as they have lower overhead then variables. Some expmles of constants:
Const conPI = 3.14159
Const conSITENAME = "my site"
Meaningful Variable and Object Names Variable names should be meaningful. Combined with the use of Hungarian notation, this leads to clear, self documenting code where the purpose and type of each variable is obvious from inspection.
Clear code will speed up the process of maintenance and 'feature' debugging.
Examples:
Good Bad
strCompanyName com
intCartCount CT
lngCustomerID cID
blnLogedIn ShpC
dblGrossWeight gWt
curGrandTotal t
objCookieCart oCook
Likewise, it is good to use prefixes for filenames of pages with similar functions. For example, all of the customer maintenance pages could start with the prefix 'cust' e.g. custNew.ASP and custUpdate.ASP.

Use of Scope

For IIS5 avoid the use of Public except when data needs to be transferred between page invocations use Dim instead to save processing overhead and memory. Use 'option explicit'. Keep variables local (inside a sub or function) whenever possible for speed and efficient memory usage. The speed is gained as the variables will be found within the current scope limiting searching of the entire name space. Declare (and comment) all variables at the top of each scope range. Groups of declarations at the beginning of the scope is more efficient. Remember to initialize values before using them to set their type and avoid unpleasant involuntary type conversion issues. Likewise, it is good practice to explicitly convert one type to another using the provided conversion functions.
Application Scope Use arrays to store cached information that changes very infrequently. For example locale information or shipping methods. Since this data can be loaded in Application_OnStart() and is very unlikely to change from DB this gives an immediate performance boost. Be wary however, as very large array objects are copied from application scope to page scope when referenced and this operation can take time. Do not persist the dictionary object , VB collections, property bags and other such objects in application scope. In general though these objects offer a great deal of flexibility and offer handy methods they are:

Not stable in application scope (particularly the dictionary object) and can cause sites to run slowly or crash.

Significantly more resource intensive when compared to arrays. The ratio of stored bytes to overhead bytes is generally poor for the kind of data most frequently persisted in most applications. In general, with the exception of special objects which is specifically designed to run in application scope, objects should not be persisted in application scope. This does not mean that local variables can't be created in order to generate (for example) arrays used to store information retrieved from various COM objects. Many COM objects not designed to be run in application scope (apartment threaded instead of both threaded) can cause thread contention problems and reduce performance. For best result COM objects that must be instantiated in application scope should be done on a "just in time" basis, used and then immediately explicitly disposed (ADO objects are good examples of this.). Remember that VB objects should not be persisted in application scope as they are compiled as Single Threaded Apartments (STA) and thus will exhibit the same scalability difficulties as if Sessions were used (e.g. thread affinity, serialization to that thread, and context switching for each instance).
Sessions are very strongly discouraged IIS4 the default state is sessions are enabled. In IIS5 the default state is that sessions are disabled. Sessions are generally discouraged. Sessions have thread affinity, hence processor affinity. Thus once a session is attached to a thread running on a specific CPU, CPU utilization can become lopsided, defeating the CPU balancing features in IIS.

Sessions can fail when confronted with certain types of proxy servers e.g. AOL.
When a site is scaled by adding servers and using (for example) Cisco Local Director to load balance your site; sessions present a problem. Sessions are machine specific. Information in sessions stored on one machine is not available if Local Director switches an incoming request to a different machine then the original request. If this is kludged around in code by dynamically generating links to point to the specific machine, load balancing is essentially defeated.

Likewise, using the Cisco Local Director sticky bit is defeated by some proxy server implementations, e.g. AOL, so that workaround is not a good one.

Servers in a farm cannot be brought out of service for maintenance without causing loss of sessions.

The memory usage patterns differ between the implementation of sessions and IIS causing resource conflicts.

Sessions enabled on the server use resources even if they are not used.

Session-less sites are more conducive to book marking as the bookmarks will refer to the "site" rather then a specific server. Thus if a server is taken out of service the bookmark will still work.

Data placed in the session scope is not de-allocated until the session is terminated or times out. This results in poor resource allocation.

Session state may be turned off on a page by page basis by embedding:

<% @EnableSessionState = False %>

The performance gain can be significant on pages containing <FRAMESET> elements as internet explorer will allocate a thread or process for each frame in parallel. Having session state enabled forces IIS to respond to the requests serially thus offsetting the advantages IE gave the frame set. Sessions can be disabled on an entire server if desired, this can cause additional resources to be available. Alternatives to sessions include

Form Hidden Fields are also a good method, the disadvantage of which is that they are only persisted when page transitions happen via the posting mechanism.

QueryString variables can also be used to pass information. The disadvantage to passing query strings is that the information passed can not exceed 216 characters including the URL on some browsers and through some proxy servers, and the information passed is very visible to the user. The advantage of passing in a query string is that the passing can happen either by a hyperlink, form post or both.

Other cookies can be generated by Response.Cookie() and retrieved by Request.Cookie(). Be aware, ASP provides no encryption of cookies so the habit of storing credit card information in plain text in a cookie is an anathema.

You can encode data into XML using ADO. The resulting XML stream can be written to the page in between comments, stored in a DB, or written to the client in a series of cookies. The XML can be turn back into a recordset and used in your pages. You can also use an XML DOM object to make and iterate XML documents.
Logical Design Use a function when there is a single result and the the result is meant to be used or tested in line. E.g. The vbScript function trim() is usually used in line and has no effect when used as a statement as the trim function has no output arguments.For routines that have success/failure indicators, converting them to functions that return a Boolean or Integer success or failure indicator allows the code to be called from with in an IF statement, thus making the code more clear.'Sample function declaration, implicitly returning success/failure as a long integer

'Any non-zero number is an error, 0 = Success

Function DoProcessingofOrder()


'This can be used as follows

If DoProcessingofOrder() > 0 Then

'Redirect to somewhere else

End if
Use a procedure when multiple output arguments are required and/or no return is desired. Use functions and subs to create re-usable code blocks and to chunk your logic into reasonable blocks of functionality Good chunking of code into subroutines and functions will make the code more maintainable and speed debugging (as you can step over an entire subroutine if it is known to work.) Chunking also allows the clever use of includes to share code across pages while maintaining a single version.
Use of Includes Server side includes are preferred over FrontPage includes as they are faster and more stable. FrontPage includes have additional functionality that can be handy such as stripping out unneeded HTML elements e.g. <BODY> and <HEAD> from HTML includes. For all server side notations e.g. #INCLUDE are processed before any of the script on the page, hence the following code will not have the results one might expect:


If blnLogedIn Then
%><!-- #INCLUDE FILE='IsCust.Asp' --><%
Else
%><!-- #INCLUDE FILE='DoLogin.Asp' --><%
End If


Both files are included and then the script is processed!
Server side includes are a powerful tool for organizing code into libraries, however moderation is urged as each server side include consumes CPU resources as the pages are "composed" by merging the includes into the main document. Some reasonable (1-3) number of includes is OK, too many (>5) can seriously degrade performance. Since it is hard to debug included code and even harder to debug code in nested includes the use of nested includes should be minimized. In some circumstances the interpreter/compiler may have difficulty resolving deeply nested includes properly. In general, here are some good guidelines:

Avoid making huge utility includes, this avoids the amount of code that must be parsed for each page.

Only put code into an include that will be shared between multiple files. The practice of building an entire site using includes to hold all of the code results in poor performance and scalability.

Avoid nesting entirely if possible.

Object References

When possible, refer to objects or members of a collection only once. Each object or collection reference is expensive in terms of computation when compared to referencing the same data in a variable.

Slow:

if ObjCustomer.Address2 <> "" then
Response.Write ObjCustomer.Address2
end if


Faster, use the reference on once :

strCustAddress2 = ObjCustomer.Address2

if strCustAddress2 <> "" then

Response.Write strCustAddress2

end if


Faster Still, use the reference only once and use the Len() function to test:

strCustAddress2 = ObjCustomer.Address2
if Len(strCustAddress2) > 0 then

Response.Write strCustAddress2

end if


For example, form and query string collection values stored in the request object should be copied into a variable for use:

For Request objects particularly, this is handy as it makes it so if the name of the control on the form changes, the code need only be modified in one location.


dim strLastName 'Customer Last Name

strLastName = Request.Form("txtLastName")
If possible and the object supports it use <OBJECT> elements instead of Server.CreateObject() as IIS delays creating the object until it is first used, where as CreateObject() causes the object to be created whether is is subsequently used or not. The reason this is not done, is that <OBJECT> tags are very hard to debug and can not be error trapped by the programmer. A low level IIS error is generated instead that causes a 40x error of some sort depending on the machines configuration.
So in practice <OBJECT> tags are only used if 1) the object is internal or 2) there is a high degree of confidence that the object can be created without error. The <OBJECT> tag is usually not used for connection oriented objects such as ADO or objects that reside in MTS.
All objects created in a page should be explicitly disposed. While IIS will "cleanup" allocations as the page passes out of scope, disposing of objects as soon as possible will result in resources being made available sooner.
Particularly for objects residing in MTS or for ADO objects, which are cached by the server, a strategy of "just in time" instantiation is recommended, creating objects shortly before they are needed, using them and then explicitly disposing them. This is effective in minimizing resource use because the "expense" of object creation is moderated by IIS/MTS caching frequently used objects thus proving a pool of frequently used objects that need not be created from "scratch" when needed. In general create object late and dispose of them early.
If an object has a method to open it e.g., .OPEN, the corresponding close method, e.g., .CLOSE should be invoked before it is disposed. This is particularly important for ADO objects. In theory, the ADODB implementation is proof against data corruption caused by sudden de-allocation, however explicit use of close provides for an orderly object shutdown, particularly for objects that are in a transaction or are updateable. The Server Side Variables collection is built dynamically by IIS the 1st time it is referenced on a page. If you can capture value of key server side variables (such as browser type etc) on your page once and then propagate them via another method, you can gain a performance increase. Likewise the MapPath() method is expensive. Consider, capturing the path of the root web in an application variable for re-use on all of your pages. The MapPath() call implicitly causes the Server Variables collection to be built.
Object Validity
Never assume an object is valid.
Test all objects after creation for being nothing:

Set objRS = Server.CreateObject("ADODB.RecordSet")

If objRS is Nothing Then

'Take steps, redirect, etc.

End if

Some cases an application should handle gracefully are:

DB is unavailable

DLL is creatable

Method calls to DLL succeed

Objects are still in scope

Collection items exist

ASP Coding Style


Use 'option explicit' to catch undeclared and misspelled variables. This prevents errors as follows:

dim colObject 'as Integer
colObjects=0
For Each Object in Collection
colObject=colObjects + 1
Next

Notice mixing of singular and plural as variable is misspelled in two places. This results in the wrong count being returned from the loop.
In addition, use of option explicit can cause ASP pages to run faster.
Explicitly using < @LANGUAGE = vbScript %> is not required on web servers as it is always set to that as the default. Explicitly declaring it is an expensive call as ASP must stop and check the default language for scripting calls. If the programmer does not have explicit control over the server on which the pages are running e.g. the site is hosted by a 3rd party, the use of @Language is still recommended as forces the script on the pages to run correctly.
Use good script coding style:


o Indent blocks of code

o Use blank lines around blocks

o Declare one variable per line (faster) and document variables

o Use comments when required to document tricky or unusual code sections

Put ASP delimiters '<' and '>' in the left hand margin to make code blocks easy to spot (except for inline blocks e.g. < = strVar >).
Combine multiple sequential Response.Write lines into one larger single statement when it makes sense to do so. This performance gain can be offset if extensive string concatenations are required.


Slower: (one per line)

Response.Write Name & "<br>"

Response.Write Street & "<br>"

Response.Write City & ", " & State & ", " & Zip & "<br>"



A little faster (de-reference the object) :

With Response

.write Name & "<br>"

.write Street & "<br>"

.write City & ", " & State & ", " & Zip & "<br>"

End With



Faster: (Concatenate strings)

Dim strHTML

strHTML = strHTML & Name & "<br>"

strHTML = strHTML & Street & "<br>"

strHTML = strHTML & City & ", " & State & ", " & Zip & "<br>"

Response.Write strHTML



Faster Still (Use continuation character):

Response.Write Name & "<br>" & _

Street & "<br>" & ", " & _

State & ", " & _

Zip & "<br>"



Even Faster (all on one line):

Response.Write Name & "
" & Street & "
" & ", " & State & ", " & Zip & "<br>"


Avoid extensive string concatenations, especially in loops. The total cost of string concatenations is given by the formula:

Cost = N(N+1)/2
Likewise, use of the ReDim operator should be limited. Resizing an array is done by allocating a new block of memory of the size desired and then copying the bytes to the new array and finally, de-allocating the old array after reassigning the variable pointer to the new array. If an array must be grown dynamically, growing an array by jumps of multiple elements and keeping a variable to serve as the actual number of elements in use may prove more efficient:

Const cGROWBY = 10 'Number of elements to grow by at one time

Dim intArrayMax 'Actual Number of Element in Use

Dim myArray(cGROWBY)


'... processing a data stream whose current value is in myValue



intArrayMax = intArrayMax + 1 'One More Array Element is Needed

if intArrayMax > UBound(myArray) then

ReDim Preserve myArray(UBound(myArray) + cGROWBY)

end if



myArray(intArrayMax) = myValue


'.... and so on


In this example the array is grown by 10 each time, some experimentation should be done to determine the best amount to grow by each time. In addition, the initial size of the array can be tuned to make the number of allocations minimized while not wasting memory on unused elements. Again, the best strategy is to attempt to compute how much memory is required in advance, if possible.
Arrays are the one of the most efficient storage mechanisms, in general they use much less memory then dictionary objects, collections, or property bags. In addition, a clever design using arrays will usually be faster.

Avoid context switching.




Context switching occurs every time the switch is made between vbScript and HTML code blocks. Each context switched requires a significant amount of time and resources on the server.

Following the previous rule extensive use of < =VariableName > should be avoided as well.

Pool or combine small blocks together to make larger blocks of HTML and script.

Avoid switching script types e.g. between vbScript and jScript as this context swap is very expensive as the number of precompiled pages in the cache is limited.
While making pages out of process can provide protection against bad page behavior and be helpful in debugging, running pages in process with IIS can result in performance gains. A careful analysis of trade-offs should be done before deciding if a page or set of pages should be run in process or out of process.
Never assume that data returned from the browser is correct. Always check order numbers, prices, SKUs, etc against to make sure data is correct. For example:


orderhistory.asp?orderid=1234

Does Order 1234 belong to the current customer? It should be checked against . Checking the referring URL is inadequate as that URL may be a) a proxy server "fronting" for 100s of people 2) spoofed 3) wrong for other reasons.
Use of white space and indenting significantly improves the maintainability of the code, while costing almost nothing in resources.
Use the Len() function to test for empty strings. Much faster.
Slow:


If strX <> "" then


Faster:
If len(strX) > 0 then


If you are using IIS 5 use Server.Transfer or Server.Execute rather then Response.Redirect. Response.Redirect generates a client side redirection header while, the other two calls perform server side redirection which is much faster.
For IIS4 (where buffering is off by default) Use Response.Buffer = True on all ASP pages.

Buffering increases performance by decreasing the number of "writes" to the client

Allows the page to be redirected in case of an error.

However, be wary of un-moderated buffering on time consuming pages with large outputs (such as large tables).

In buffered output you can use Response.IsClientConnected after the first Response.Flush to test to see if the client is still there, and abort by using Response.End if not. Warning: for IIS4 and below the IsClientConnected call may return incorrect values unless some information has been flowed to the client.

Strategic use of Response.Flush can keep pages from timing out. For large tables, it may be necessary to additionally end and restart the table. For example:


lngRowCount = 0

Response.Write "<table width='100%'>"

while not rs.eof

lngRowCount = lngRowCount + 1

if lngRowCount Mod 100 = 0 then

Response.Write "</table>"

Response.Flush

Response.Write "<table width='100%'>"

end if



'Write out row



wend


Dead Code/comment Removal


Remove all dead code. ASP is interpreted, so dead code, even commented out makes the page "heavy" e.g. uses more memory in the page cache, takes longer to load and thus is more processor intensive.
Sadly, this rule applies to excessive HTML comments as well as these are flowed to the client browser.
In general comments should be stripped from production code to save "weight" and to avoid reveling secrets about the way the code works.

Form Design Issues


Forms should post to themselves. This has several advantages:

when data entered is incorrect (user data entry error) as the fields on the form can be marked as being incorrect or missing easily.

secondly, the number of redirects are minimized

lastly, all of the business logic related to a single function is contained in the page.
Data entry items on a form should have the correct tab order and be arranged in an order that makes sense to data enter.
Data entry fields should be aligned to each other as much as possible to make the data entry experience as pleasant as possible.
Use client side scripting (JavaScript for maximum compatibility) to validate user input. This has the effect of reducing round trips to the server. However, it should never be assumed on the server side that the data is correct when it is received. Client side validation supports but does not replace good data validation on the server.
Check HTML for Correctness
An automated HTML checking tool should be applied to all pages to make sure that the HTML on the page is correct.
Particularly troublesome items include

Missing form elements

Malformed tables, particularly incorrect spans

Missing end tags for matched elements e.g. missing </tr> or </td>

Incorrect target references for frames

Invalid nesting of tags

Invalid HTML can cause slow loading pages as browsers struggle to interpret "do as I mean, not as I say" code.
It is very helpful to reformat pages so that the following HTML standards are followed:

Use all lowercase HTML tags. This is a change over old advice that called for all uppercase HTML elements. The new standard is based on the new xHTML standard that makes all uppercase takes depreciated. So it would be good to get into the habit of using all lower case elements now.

ASP Code should be title cased

vbScript code should use the correct mixed case as in the sections above
Error Handling
In general, error prevention is much better than error handling. The error trapping mechanism is computationally expensive.
There are certain occasions where explicit error handling is strongly recommended:

When using the file system objects

When invoking 3rd party objects such as controls or applets

When opening ADO connections or recordsets
When setting an error trap using On Error Resume Next make sure to turn it off as soon as possible with On Error Goto 0
Setting an error trap without checking Err.Number after calls is not recommended. Once a page has an error it is usually disadvantageous to continue processing.

ADO


Use GetString(), GetRows(), or disconnected recordsets. These methods reduce the number of trips across the network required to retrieve database data. If your recordset does not need formatting (consider doing that sort of work in the query or in a stored procedure) using GetString cleverly to output tables quickly for tables containing few rows (About 50, if there are many more rows the size of the string variable created becomes an issue, test typical outputs using various techniques to see which is faster in your case).

Response.Write "<table border='1'><tr><td>"
S = rs.GetString( , , "</td><td>","</td></tr><tr><td>", " " )
S = Left( S , Len(S) - 8) 'Remove extra <tr><td>
Response.Write S & "<</table>"
Reduce time that database connections are open. Don't open database connections until immediately before you need them, and close then dispose them as soon as possible. This returns the connection resources to IIS which maintains a pool that can be rapidly be reused.
Use connectionless fire hose cursors when possible: Client Side, No Locks, Not Updateable. In general use the very fewest connection features possible to make the "cheapest" cursors.
Do not re-use ADO command objects in the same page. There is a bug that can cause your pages to crash. Dispose and re-create your command objects or better yet use the techniques below.
If you need to fetch records from multiple queries serially, then use the following technique:

mySQL = "Select * From A;Select * From B" 'Notice the two queries separated by a semi-colon (;)

Create your record set... The recordset object will point to the 1st cursor. Then use

rs.NextRecordset

This moves to the next cursor. You can not go back to make sure you have done all that you need to with the 1st cursor. This technique is much faster and more resource efficient then using multiple recordsets or the same one serially.

Use stored procedures


Stored procedures represent server side business logic and can be used from VB or ASP.
Stored procedures are much faster then constructing queries "on the fly"
Stored procedures can be modified/tested with out recompiling the program or editing the script

How to run stored procedures from VB/ASP


The general strategy for performance is to avoid the command object unless you need to create stored procedures on the fly with dynamic parameters or you are pushing a larger number of parameters at the servers..

Dim lngRecordsAffected

Dim strSQL

Dim objADORS 'ADODB.Recordset

Dim objADOConnection 'ADODB.Connection




'... create and open connection and create recordset object



Instead of creating a command object build a command string that includes the stored procedure and all of its parameters.



strSQL = "usp_DoIt2It " & para1 & "," & para2 'or whatever is required.



For stored procedures that do not return rows:

Add the 'call' verb and braces:

strSQL = "{Call " & strSQL & "}"
objConnection.Execute strSQL, lngRecordsAffected , adCmdStoredProc

'You can check lngRecordsAffected to see how many rows were affected

'For stored procedures that return rows:


Set rs = objCN strSQL, lngRecordsAffected , adCmdStoredProc

As the name indicates this inbuilt javascript function is used to return the type of the datatype. It returns a string value and accept variable as the parameter

Syntax of typeof is

typeof(varablename)

This function returns the following values

number

string

boolean

function

Also it returns undefined as the value when we are trying to use type of with an undefined variable or function.

Number

<script type="text/javascript">

var num=12;

alert(typeof(num));

</script>

string

<script type="text/javascript">

var str="23";

alert(typeof(str));

</script>

boolean

<script type="text/javascript">

var bln=true;

alert(typeof(bln));

</script>

function

<script type="text/javascript">

function test()

{

}


alert(typeof(test));

</script>


undefined

<script type="text/javascript">

alert(typeof(num2));

</script>

last one can be a pretty useful one while coding. We can check whether a variable is defined within a particular scope using this

Say

<script type="text/javascript">

if(typeof(num)!="undefined");

{

//Some code } </script>

That means prototype helps us to extend the basic built in types by adding additional properties depending on our need.


For example for strings you may want to define a new method for converting a string into new type of html font tag not already defined by javascript object.



<html>

<head>

    <title>Javascript Prototype Object</title>

<script type="text/javascript">

function GetFontHTM()

{

return "<font color='blue'>"+this.toString()+"</font>";

}

String.prototype.gethtm=GetFontHTM;


</script>

</head>

<body>

<div id="test">


</div>

<script>

var divid=document.getElementById("test");

divid.innerHTML="Test".gethtm();

</script>


</body>


</html>





 




Another example is shown below


Even though a Car class does not define a property named mileage, we were able to create

one for the mySUV object simply by assigning a value to it. Since we applied this property to

the mySUV object and not the Car class, other objects derived from the Car class will not have

a mileage property


Extend an Existing Object


Just as a class can be extended using the prototype property, objects themselves can have new

properties and methods attached to them.





function Car (make, model, year, color) {

this.Make = make;

this.Model = model;

this.Year = year;

this.Color = color;

this.FullName = this.Year + " " +

"<b>" + this.Make + "</b> " +

this.Model;

}




var mySUV = new Car("Toyota", "4Runner SR5",2001, "Thundercloud");

mySUV.mileage = 12323;

document.write(mySUV.FullName + " has traveled " +mySUV.mileage + " miles.<br><br>");

 



 

Arrays are ordered collections of values referred to by a single variable name. For instance, if you have an array named student, you might have the following ordered values:



   student[0] = "Bob"


    student[1] = 10


    student[2] = 75


 



Array elements are referred to by their indexes-the numbers in brackets. In JavaScript, arrays start with index zero.


Arrays in JavaScript are created using the Array() constructor object. You can create an array of undefined length by using the r">new keyword:



    arrayName = new Array();



The length of the array changes dynamically as you assign values to the array. The length of the array is defined by the largest index number used.


For instance



    var sampleArray = new Array();


    sampleArray[49] = "50th Element";



creates an array with 50 elements. (Remember, indexes start at zero.)


It is also possible to define an initial length of an array by passing the length to the Array() object as an argument:



    var sampleArray = new Array(100);



In addition, you can create an array and assign values to all its elements at the time it is defined. This is done by passing the value for all elements as arguments to the Array() object. For instance,



    var sampleArray = new Array("1st Element", 2, "3rd Element);



creates a three-element array with the values



    sampleArray[0] == "1st Element"


    sampleArray[1] == 2


    sampleArray[2] == "3rd Element"



As objects, arrays have several methods, including


    * join() returns all elements of the array joined together as a single string. This takes one argument: a string used as the separator between each element of the array in the final string. If the argument is omitted, join() uses a comma-space as the separator.


    * reverse() reverses the order of elements in the array.


 


Reading and Writing Array Elements


You access an element of an array using the [] operator. A reference to the array should appear to the left of the brackets. Inside the brackets should appear an arbitrary expression that has a non-negative integer value. You can use this syntax to both read and write the value of an element of an array. Thus, the following are all legal JavaScript:



value = a[0];


a[1] = 3.14;


i = 2;


a[i] = 3;


a[i + 1] = "hello";


a[a[i]] = a[0];


 



In some languages, the first element of an array is at index 1. In JavaScript, as well as C, C++, and Java, however, the first element of an array is at index 0.[1]


    Adding New Elements to an Array


In languages like C and Java, arrays have a fixed number of elements that must be specified when you create the array. This is not the case in JavaScript--arrays can have any number of elements, and you can change the number of elements at any time.


To add a new element to an array, simply assign a value to it:



a[10] = 10;



Arrays in JavaScript are sparse. This means that array indexes need not fall into a contiguous range of numbers, and that memory is allocated only for those array elements that are actually stored in the array. Thus, when you execute the following lines of code, JavaScript allocates memory only for array indexes 0 and 10,000, not for the 9,999 indexes between.




a[0] = 1;


a[10000] = "this is element 10,000";



Removing Elements from an Array


Once an element of an array has been defined, you can set its value to null or anything else, but there is no way to actually undefine that element, short of actually truncating the array, which (as we'll see later in the chapter) is possible in Navigator 3.0.


The Select.options[] array is an exception to this rule. It represents HTML elements in client-side JavaScript and has special behavior in Navigator 3.0, including the ability to delete individual elements. See the entry in the reference section of this book for more.


Multidimensional Arrays


JavaScript does not support true multidimensional arrays, but it does allow you to approximate them quite nicely with arrays of arrays. To access a data element in an array of arrays, simply use the [] operator twice. For example, suppose the variable matrix is an array of arrays of numbers. Every element matrix[x] is an array of numbers. To access a particular number within this array you would write matrix[x][y].


Instead of using arrays of arrays, you can also use associative arrays to simulate multidimensional arrays. Because an associative array allows an arbitrary string as its index, it is easy to use them to simulate multidimensional arrays--i.e., to look up a value based on more than one index. You could use the following function, for example, to simulate reading a value from a three-dimensional array:


 Array Length Property


As we saw in the previous section, the Array() constructor method automatically initializes a length property for the array you create. When you create an array with this constructor (available only in Navigator 3.0 and later) this length property is automatically updated by JavaScript so that it is always one greater than the largest element number in the array. The following code illustrates this:



a = new Array();       // a.length == 0  (no elements defined)


a = new Array(10);     // a.length == 10 (empty elements 0-9 defined)


a = new Array(1,2,3);  // a.length == 3  (elements 0-2 defined)


a[5] = -1;             // a.length == 6  (elements 0,1,2, and 5 defined)


a[49] = 0;             // a.length == 50 (elements 0,1,2,5, and 49 defined)


 



The length property of a Navigator 3.0 array is not read-only. You can set length to a value smaller than its current value; the array will then be shortened to the new length--elements will be truncated from the end of the array, and their values will be lost. If you change the length property so that it is larger than its current value, the array will be made larger--new, undefined, elements will be added at the end to increase it to the newly specified size.


We've said that arrays are the same data type as objects are, and that any object can have array elements. This is true, but in Navigator 3.0, arrays created with the Array() constructor have features that other objects do not have. One of these features is the length property. If you create an object with the Object() constructor (or a constructor you define yourself) you can assign array elements to that object, but that object will not have the special length property described in this section.


Because the Array() constructor and the array length property are not available in Navigator 2.0, JavaScript programs written for Navigator 2.0 often define custom array constructor functions that attempt to simulate the length property. (To avoid confusion with the "real" length property of arrays in 3.0, I prefer to name the property size in 2.0.) We saw such an array constructor in Example 8.1, and will learn more about arrays in Navigator 2.0 later in this chapter.



function index3(arr, x, y, z)


{


    return arr[x + "," + y + "," + z];


}


 



This example works because it combines the x, y, and z index values into a single, unique string that acts as a property name in the associative array (or object).


Array Methods


In the previous section we saw that--in Navigator 3.0 and Internet Explorer 3.0--arrays created with the Array() constructor have a length property. In Navigator 3.0, but not in IE 3.0, these arrays also support three methods that can be used to manipulate the array elements. These methods will be implemented in a future version of IE.


The Array.join() method converts all the elements of the array to a string, and concatenates them, separating them with an optionally specified string passed as an argument to the method. If no separator string is specified, then a comma is used. For example, the following lines of code produce the string "1,2,3":



a = new Array(1,2,3);  // Create a new array with these three elements.


s = a.join();          // s == "1,2,3"


And the following lines specify the optional separator to produce a slightly different result:


a = new Array(1,2,3);


s = a.join(", ");   // s == "1, 2, 3". Note the space after the comma.



In some ways, the Array.join() method is the reverse of the String.split() method which creates an array by breaking a string up into pieces.


The Array.reverse() method reverses the order of the elements of an array. It does this "in place"--i.e., it doesn't create a new array with the elements rearranged, but instead rearranges them in the already existing array. For example, the following code, which uses the reverse() and the join() methods, produces the string "3,2,1":



a = new Array(1,2,3);   // a[0] = 1; a[1] = 2; a[2] = 3;


a.reverse();            // now a[0] = 3; a[1] = 2; a[2] = 1;


s = a.join()            // s = "3,2,1"




The final array method is Array.sort(), which sorts the elements of an array. Like the reverse() method, it does this "in place". When sort() is called with no arguments, it sorts the array elements in alphabetical order (temporarily converting them to strings, to perform the comparison, if necessary):


a = new Array("banana", "cherry", "apple");


a.sort();


s = a.join(", ");   // s == "apple, banana, cherry".



You can also pass an argument to the sort() method if you want to sort the array elements in some other order. To allow this method to be a fully general sorting algorithm, the optional argument should be a function. This function will be passed two arguments that it should compare. If the first argument should appear before the second in the sorted array, then the function should return a number less than zero. If the first argument should appear after the second in the sorted array, then the function should return a number greater than zero. And if the two values are equivalent (their order is irrelevant), then the function should return 0. So, for example, to sort array elements into numerical, rather than alphabetical order, you might do the following:



a = new Array(33, 4, 1111, 222);


a.sort();                        // alphabetical order:  1111, 222, 33, 4


function numberorder(a,b) {


    return a-b;


}



a.sort(numberorder);             // numerical order: 4, 33, 222, 1111


You can probably think of other comparison functions that will sort numbers into various esoteric orders: reverse numerical order, odd numbers before even numbers, etc. The possibilities become more interesting, of course, when the elements you are comparing are objects rather than simple types like numbers or strings.







 

concat Method




The concat method joins two or more Array objects producing one new one. The original Array objects are unaffected by this but, if one copy of a string or number is altered, it is not reflected in the other, whereas a change to an object reference can be seen in both copies.

 

Syntax: Array.concat(arrayName2, arrayName3, ..., arrayNameN)

 

pop Method Netscape Only Feature

The pop method is used to remove and return the last element of an array. This affects the length of the array.

 

Syntax: Array.pop()

 

push MethodNetscape Only Feature


The push method is used to add one or more elements to an array, returning the new length of it. This affects the length of the array.

 

Syntax: Array.push(element1, ..., elementN)

 

reverse Method

The reverse method, as the name implies, reverses the order of the elements in an array making the first last and the last first. Syntax: Array.reverse()

 

shift Method Netscape Only Feature

The shift method removes and returns the first element of an array. This affects the length of the array.

 

Syntax: Array.shift()

 

slice MethodNetscape Only Feature

The slice method creates a new array from a selected section of an array.

 

Syntax: Array.slice(begin[,end])

 

splice MethodNetscape Only Feature

The splice method is used to add and/or remove elements of an array.

 

Syntax; Array.splice(index, howMany, [element1][, ..., elementN])

 

toSource Method Netscape Only Feature

The toSource method is inherited from the Object object and returns the source code of the array. For details see the Object.toSource method.

 

Syntax: Array.toSource()

 

toString Method

The toString method is inherited from the Object object and returns a string representing the specified array and its elements. For more details see the Object.toString method.

 

Syntax: Array.toString()

 

unshift Method Netscape Only Feature

The unshift method adds one or more elements to the beginning of an array and returns the new length.

 

Syntax: Array.unshift(element1,..., elementN)

 

valueOf Method


The valueOf method is inherited from the Object object and returns a primitive value for a specified array. For details see the Object.valueOf method.

 

Syntax: Array.valueOf()




Array Summary


JavaScript array creation, usage, and compatibility techniques can be confusing. Here are the main points of this chapter in review:


    * Arrays and objects are the same thing in JavaScript. Any object can have array elements, and any array can have object properties.


    * In Navigator 3.0, there are three methods that can be used to manipulate arrays:


         1. You can can convert an array, and all of its elements into a single string with the Array.join() method.


         2. You can reverse the order of elements in an array with the Array.reverse() method.


         3. You can sort the elements of an array with the Array.sort() method.


    * In Navigator 3.0 and Internet Explorer 3.0, array elements and object properties do not overlap and cannot overwrite each other. There is an Array() constructor, and arrays created with this constructor have a (read-only in IE 3.0) length property that is automatically maintained so that it always contains a value one greater than the largest index of the array.


    * In Navigator 2.0, object properties and array elements overlap; when you create a new property, it is as if you added a new array element one higher than the highest existing element. There is no built-in Array() constructor, but you can write your own. Also, there is no automatically maintained length property, but it is common to reserve element 0 of an array for a size property (which you update yourself as the array grows).


    * For many algorithms, the size of an array is maintained in a variable externally to an array, and there is no need for a length or size property.


    * All arrays in JavaScript are implemented as associative arrays, and can be "sparse"--i.e., they can contain non-contiguous elements. Usually, though, you'll use arrays as if they were non-associative, fixed-size arrays like those found in C, C++, and Java.

As the ASP.NET code executes on the server, there is no way to show a new window from your server side code. You can add URL hyperlinks to a page that will open in a new window by setting the target attribute of the anchor tag to _blank, but this still doesn't give you the ability to control the window size or style.



The possibe solution is to use client-side javaScript code to open the new window. The new window itself could be an HTML page, an image file, or any other type of resource that can be opened in the client's browser. To open a secondary window, you use the window.open function and specify three parameters.

The first parameter is the link for the new page.

the second is the frame name of the window.

the third is a comma- separated string of attributes that configure the style and size of the pop-up window. These attributes can include the following:



The height and width attributes, which are set to pixel values.

The toolbar, menuBar, and scrollbars attributes, which can be set to yes or no depending on whether you want to display these elements.



The resizable attribute, which can be set to yes or no depending on whether you want a fixed or resizable window border.



The following example shows how you can configure an ASP.NET Button so that it opens a second ASP.NET page in a pop-up window when clicked. Typically, you would add this code to the Page.Load event handler.



popupScript = "window.open('terms.html', " +
"'newswindow', " +
"'width=400, height=400, menubar=yes, resizable=no')";




cmdPopWin.Attributes.Add("onClick", popupScript);


Here's the code you would use to show a pop-up window automatically when the page is displayed. This code would also go in the Page.Load event handler.




string popWInScript = "<script language='javascript'>" +
"window.open<'terms.html', " +
"'newswindow', " +
"'width=400, height=400, menubar=yes, resizable=no'>" +
"</script>";




Page.RegisterStartupScript("popWInScript", popWInScript);


OR



We can call a funtion which containts the above code on server control's onclientclick property(Asp.net 2.0 Version)

You may have tried using ctrl+alt+del key to lock the PC that u are connected using remote desktop .That inturn must have poped up the task manager window

Here instead of del key use end key , So the combination becomes ctrl+alt+end key

C++ FAQs

10:45 AM | , | 0 comments »

What are inline functions and macros in c++?



Ans : The inline keyword tells the compiler to substitute the code within the function definition for every instance of a function call. However, substitution occurs only at the compiler's discretion. For example, the compiler does not inline a function if its address is taken or if it is too large to inline. The use of inline functions generates faster code and can sometimes generate smaller code than the equivalent function call generates. Although inline functions are similar to macros (because the function code is expanded at the point of the call at compile time), inline functions are parsed by the compiler, whereas macros are expanded by the preprocessor. As a result, there are several important differences: Inline functions follow all the protocols of type safety enforced on normal functions. Inline functions are specified using the same syntax as any other function except that they include the inline keyword in the function declaration.

What is the difference between malloc() and calloc() function?



Ans : The calloc() function also allocates memory. Rather than allocating a group of bytes as malloc() does, calloc() allocates a group of objects. The function prototype is void *calloc(size_t num, size_t size); Remember that size_t is a synonym for unsigned on most compilers. The argument num is the number of objects to allocate, and size is the size (in bytes) of each object. If allocation is successful, all the allocated memory is cleared (set to 0), and the function returns a pointer to the first byte. If allocation fails or if either num or size is 0, the function returns NULL.
8

What is the difference between an abstract class and an interface. where exactly would you use an abstract class and an interface.



Ans : Interface is like a class itself that has variables and methods but it contain final variables and abstract methods that is methods are just declared inside the interface, they are defined in a class that implements the interface. Abstract class is a class containing one or more abstract methods, this class can contain non abstract methods as well and it may or may not contain final variables. You cannot create an object of abstract class directly.

What is "this" keyword?



Ans : The keyword this represents within a class the address in memory of the object of that class that is being executed. It is a pointer whose value is always the address of the object. It can be used to check if a parameter passed to a member function of an object is the object itself.

What is difference between #define and typedef?



Ans.#define is a preprocessor directive which defines constant value to a symbol. For eg: #define MAX 100; The symblo MAX will be replaced by 100. Typedef statement is used to give new names to existing data types. Eg: typedef unsigned long ulong; declares ulong to be a new type equivalent to unsigned long.

What is the concept of smart pointers?



A smart pointer is a C++ class for wrapping pointers. By wrapping a pointer in a class(and
specifically, a template), you can make sure certain operations are taken care of
automatically instead of deferring mundane, boilerplate-type operations to the client. One
good example of such an operation is to make sure pointers are initialized correctly so that
embarrassing crashes due to randomly assigned pointers don't occur. Another good example
is to make certain that boilerplate code is executed before function calls are made through a
pointer.

What is the difference between encapsulation and abstraction?



The idea of encapsulation comes from (i) the need to cleanly distinguish between the specification and the implementation of an operation and (ii) the need for modularity. Modularity is necessary to structure complex applications designed and implemented by a team of programmers. It is also necessary as a tool for protection and authorization. There are two views of encapsulation: the programming language view (which is the original view since the concept originated there) and the database adaptation of that view. The idea of encapsulation in programming languages comes from abstract data types. In this view, an object has an interface part and an implementation part. The interface part is the specification of the set of operations that can be performed on the object. It is the only visible part of the object. The implementation part has a data part and a procedural part. The data part is the representation or state of the object and the procedure part describes, in some programming language, the implementation of each operation. The database translation of the principle is that an object encapsulates both program and data. In the database world, it is not clear whether the structural part of the type is or is not part of the interface (this depends on the system), while in the programming language world, the data structure is clearly part of the implementation and not of the interface. Consider, for instance, an Employee. In a relational system, an employee is represented by some tuple. It is queried using a relational language and, later, an application programmer writes programs to update this record such as to raise an Employees salary or to fire an Employee. These are generally either written in a imperative programming language with embedded DML statements or in a fourth generation language and are stored in a traditional file system and not in the database. Thus, in this approach, there is a sharp distinction between program and data, and between the query language (for ad hoc queries) and the programming language (for application programs). In an object-oriented system, we define the Employee as an object that has a data part (probably very similar to the record that was defined for the relational system) and an operation part, which consists of the raise and fire operations and other operations to access the Employee data. When storing a set of Employees, both the data and the operations are stored in the database. Thus, there is a single model for data and operations, and information can be hidden. No operations, outside those specified in the interface, can be performed. This restriction holds for both update and retrieval operations. Encapsulation provides a form of ``logical data independence: we can change the implementation of a type without changing any of the programs using that type. Thus, the application programs are protected from implementation changes in the lower layers of the system. We believe that proper encapsulation is obtained when only the operations are visible and the data and the implementation of the operations are hidden in the objects. However, there are cases where encapsulation is not needed, and the use of the system can be significantly simplified if the system allows encapsulation to be be violated under certain conditions. For example, with ad-hoc queries the need for encapsulation is reduced since issues such as maintainability are not important. Thus, an encapsulation mechanism must be provided by an OODBS, but there appear to be cases where its enforcement is not appropriate.

8 . What is garbage?



Garbage is data that has been placed in random access memory space obtained from the operating system that is no longer needed. Freeing the space for reuse is called "garbage collecting." In the past, programmers have had to write programs that explicitly requested storage and then returned it to the system when it was no longer needed. Java is a newer programming language that, like LISP, handles garbage-collecting for the program, freeing the programmer from being concerned about it.

What is the difference between heap and stack?



A heap is an area of pre-reserved computer main storage (memory) that a program process can use to store data in some variable amount that won't be known until the program is running. For example, a program may accept different amounts of input from one or more users for processing and then do the processing on all the input data at once. Having a certain amount of heap storage already obtained from the operating system makes it easier for the process to manage storage and is generally faster than asking the operating system for storage every time its needed. The process manages its allocated heap by requesting a "chunk" of the heap (called a heap block) when needed, returning the blocks when no longer needed, and doing occasional "garbage collecting," which makes blocks available that are no longer being used and also reorganizes the available space in the heap so that it isn't being wasted in small unused pieces. The term is apparently inspired by another term, stack. A stack is similar to a heap except that the blocks are taken out of storage in a certain order and returned in the same way.

What is difference between Template and function in c++ and why we use templates?



Template - a parameterized type. A template can accept type parameters that are used to customize the resulting type. Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones: template function_declaration; template <typename indetifier> function_declaration; the only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way. For example, to create a template function that returns the greater one of two objects we could use: template <class GenericType> GenericType GetMax (GenericType a, GenericType b) { return (a>b?a:b); } As specifies the first line, we have created a template for a generic data type that we have called GenericType. Therefore in the function that follows, GenericType becomes a valid data type and it is used as type for its two parameters a and b and as return value for the function GetMax. GenericType still does not represent any concrete data type; when the function GetMax will be called we will be able to call it with any valid data type. This data type will serve as pattern and will replace GenericType in the function. The way to call a template class with a type pattern is the following: function <pattern> (parameters); Thus, for example, to call GetMax and to compare two integer values of type int we can write: int x,y; GetMax <int> (x,y); so GetMax will be called as if each appearance of GenericType was replaced by an int expression.

What is name Mangling? How is it handled in c++ and in com



Both C++ and Java provide overloaded function and methods, which are methods with the same types but different parameter lists. Selecting the correct version is done at compile time. Though the overloaded functions have the same name in the source code, they need to be translated into different assembler-level names, since typical assemblers and linkers cannot handle overloading. This process of encoding the parameter types with the method name into a unique name is called name mangling. The inverse process is called demangling. It is convenient that C++ and Java use compatible mangling schemes, since the makes life easier for tools such as gdb, and it eases integration between C++ and Java. Note there is also a standard "Java Native Interface" (JNI) which implements a different calling convention, and uses a different mangling scheme. The JNI is a rather abstract ABI so Java can call methods written in C or C++; we are concerned here about a lower-level interface primarily intended for methods written in Java, but that can also be used for C++ (and less easily C). Method name mangling C++ mangles a method by emitting the function name, followed by __, followed by encoding of any method qualifiers (such as const), followed by the mangling of the methods class, followed by the mangling of the parameters, in order. For example Foo::bar(int, long) const is mangled as `bar__C3Fooil. For a constructor, the method name is left out. That is Foo::Foo(int, long) const is mangled as `__C3Fooil.

What is namespace in C++ ?


C++ supports the concept of a namespace, to help avoid naming conflicts that inevitably occur in software development. A problem that people ran into when writing software was that two different pieces of code might logically want to use the same identifier names. A namespace allows you to enclose all of your identifiers inside of a named entity. So, for example, if you had a function named bar in the foo namespace, to access it you would use the fully qualified name foo::bar. The namespace is separated from the identifier by a double colon. By using a namespace, you have at most one conflict: your namespace name, which is much easier to change than hundreds or even thousands of other identifiers

What is the difference between namespaces and structures?
A namespace declaration identifies and assigns a name to a declarative region. The syntax is : Namespace [identifier] {namespace-body} The identifier in a namespace declaration must be unique in the declarative region in which it is used. The identifier is the name of the namespace and is used to reference its members. The declarative region of a namespace declaration is its namespace-body. A structure type is a user-defined composite type. It is composed of "fields" or "members" that can have different types. In C, you must explicitly use the struct keyword to declare a structure. In C++, this is unnecessary once the type has been defined.

What is lvalue and rvalue?


C and C++ have the notion of lvalues and rvalues associated with variables and constants. The rvalue is the data value of the variable, that is, what information it contains. The "r" in rvalue can be thought of as "read" value. A variable also has an associated lvalue. The "l" in lvalue can be though of as location, meaning that a variable has a location that data or information can be put into. This is contrasted with a constant. A constant has some data value, that is an rvalue. But, it cannot be written to. It does not have an lvalue. Another view of these terms is that objects with an rvalue, namely a variable or a constant can appear on the right hand side of a statement. They have some data value that can be manipulated. Only objects with an lvalue, such as variable, can appear on the left hand side of a statement. An object must be addressable to store a value. Ex: int x; x = 5; // Here, 5 is an rvalue, x can be an lvalue