Business Website Links, LLC Company Logo

Visit us often.  Computer tips updated daily. Click here to--> "Tell a friend" so they can get updated computer tips, too.  Please visit our clients, as they support the computer tips page.

If you would like to submit a tip send us an email with your tip to info@businesswebsitelinks.com.

_________________________________________

Business Website Links showing a picture of a Active Server room and Computer Tips for Active Servers belowActive Server Tips




Tip: Introduction to Web Accessibility - Content Insertion

  • Another serious problem can occur when HTML is inserted dynamically into the page, such as with delay-loaded menus or content loaded asynchronously in response to a user event. If the inserted HTML is not placed in the document at the point at which it visually appears, a keyboard user may have to tab through the entire document in order to get to the inserted content.
  • An example of content created and inserted into the page after it has loaded, is the Popup Dialog Sample. The dialog box is inserted into the empty div container element in the main page, and is created on-the-fly with JavaScript code only when the Options button is clicked. It is then deleted as soon as the dialog box closes.

Tip: Introduction to Web Accessibility - Tab Order

  • There is a tendency, especially if the developer comes from a Windows-based programming background, to set tab index on all objects for which tab stops are desired. If semantic HTML is being used, this is generally unnecessary because most web page elements have tab positions in the page by default.
  • The more serious accessibility problem is that explicitly setting tab stops using the tabindex attribute, especially if using non-zero values to specify an order, can create a variety of unexpected behaviors. This may result in the tab order going from the initial elements then out to the browser shell, then back into the document to additional tab stops.

Tip: Introduction to Web Accessibility - Colors

  • There are two important considerations with colors, one for users unable to differentiate between colors ("color blindness"), and the other related to how the web application is displayed with various High Contrast mode settings. Any information that is conveyed by using color must also be conveyed by using text and additional graphic treatments, and there are two groups of users to consider here.
  • First, those who can see the screen but cannot see colors, and second those who cannot see the screen. For the first group, distinguish the colored object visually in some other way, such as bolding, outlining, positioning, adding icons, underlining, and so on, or by adding visible text explaining the meaning of the color change. For those who cannot see, add text, either visible or via an alt attribute on a colored image, or a title attribute (ToolTip) on colored text.
  • For a working sample, see the Colors Sample.
  • Table with Color and Text
  • Table with Color and Image
  • HTML
  • Copy the following HTML CodeTable with colors and text
  • If a background-color is specified the text color also needs to be specified, and vice-versa, as well as link colors. This is because there are some system color modes where CSS colors are not overridden, but non-specified colors are overridden. For example, if the background color is set to white and text color is not specified, with the system set to white on black high contrast, the user could end up with white text on a white background.
  • The High Contrast mode in Windows overrides most colors specified by the developer, and removes backgrounds, including the CSS background-image. Images that are meaningful, especially clickable images and icons, must be created using the img alt="" element, with an appropriate alt description.

Tip: Introduction to Web Accessibility - Text Scaling

  • Prior to the broad adoption of zoom as the means for browsers to increase text size (as well as the size of all other elements, such as images), using Internet Explorer's View > Text Size was the primary way that a user could increase the font size in an HTML document (other than system Large Fonts or High Contrast settings). There were two common problems with this.
  • Fonts specified in absolute CSS units such as "px", did not change size. If you develop for an environment that includes older browsers such as Microsoft Internet Explorer 6, be sure to specify font size in a relative unit. Microsoft recommends using percentage - "%".
  • The other issue was that sometimes containers, such as div elements, had their height specified in pixels, so that when the font size increased with View > Text Size, the text within that element either would get cropped or would overflow. Microsoft recommends setting container dimensions in em units if you support older browsers.

Tip: Introduction to Web Accessibility - WAI-ARIA

  • To circumvent the limitations of native HTML controls, for some time there has been an industry effort to extend HTML so that developers can build applications that have custom controls and are accessible to assistive technology users. WAI-ARIA is a W3C recommendation that provides such extensions in the form of roles and attributes that are understood by accessibility agents.
  • For example, with WAI-ARIA a developer can mark a control as a tree, and it will be exposed as a tree control to assistive technology by WAI-ARIA-capable browsers. Other WAI-ARIA roles include sliders and menus.
  • WAI-ARIA is an excellent effort to provide native HTML elements with accessibility, but it isn't backward-compatible. Web browsers that are not WAI-ARIA-aware, such as Internet Explorer prior to version 8, simply ignore the WAI-ARIA information. Earlier versions of assistive technology also do not expose WAI-ARIA information.
  • Because of this backward-compatibility problem, organizations with significant numbers of older browsers and assistive technology products in their deployed base, will not be able to use a "pure" WAI-ARIA approach to web accessibility. In order to be accessible to older browsers and assistive technology, web applications still need to be built using semantic HTML.
  • And, it is always better to use the built-in functionality rather than building your own, if you can. The controls that are part of the browser are very thoroughly specified and tested, and work in cases you may not cover in your custom control. This is particularly important when dealing with assistive technology products, because there are so many of them, and most developers don't have the resources, time, or experience to effectively test with all of them.
  • Our recommendation is to build your web applications using semantic HTML and layer WAI-ARIA roles and attributes on top of the HTML. In this manner, users of older browsers and assistive technology will get the best accessibility, and users of newer versions will get an even richer experience.
  • For more information about WAI-ARIA and this "progressive enhancement" approach to building web applications, see Accessibility and Legacy Browsers, and Introduction to ARIA, as well as the set of related samples.

Tip: Introduction to Web Accessibility - Designing for Accessibility

  • Because HTML is read-only, it is critical to use existing, native HTML control elements where possible. For example, use a button element rather than a div made to look and act like a button with CSS and script modifications. This ensures backward compatibility where ARIA is not available, such as early browsers.
  • For a couple of examples, see the Semantic HTML samples. Microsoft recommends that designs are reviewed with both designers and developers very early in the process, to identify designs that cannot be implemented in semantic HTML alone, and either modify the designs or budget time to add ARIA. For information about how to combine this process with ARIA implementation, see the Accessibility and Legacy Browsers article.

Tip: Introduction to Web Accessibility - Web Accessibility

  • In recent years, the Internet and corporate intranets have proven themselves to be extremely important application platforms. Rather than deploy applications to multiple desktop computers running multiple operating systems, organizations can write one version of an application in HTML and make it available from a single server to anyone with connectivity and a browser.
  • Developing accessibility for traditional Classic Windows applications typically involves using a specific accessibility API such as Microsoft Active Accessibility or UI Automation, to write additional code to create applications like "magnifying glass." This application programmatically enlarges screen contents so that the screen is easier to read for people with sight limitations. The developer had to do "extra" work to make the application accessible, but also had great control over the accessibility information that the application exposed.
  • For example, the developer might write a custom control using Windows GDI+, and assign to that control an appropriate role for assistive technology to use, such as a slider, a tree, or something else. Developers might also specify any custom events that they wanted the control to engage.
  • There was some complexity in writing an accessible control, but also great discretion and flexibility in how that control was exposed. In addition, standard controls that ship with Windows have these assistive technologies implemented, so that developers who use any of the wide variety of common controls, get built-in accessibility, and the API values can be set by changing the ARIA values.
  • By using HTML web applications, the situation is different. With a Classic Windows application the developer has read/write access to the controls, but with HTML, the built-in controls, such as form elements and links, are read-only.
  • For example, if an HTML developer wants to implement a form with a text box and a button, the developer might use the existing HTML forms controls, in this case the input type=text and the input type=button,or button. The developer can certainly create a custom "textbox" and "button" using other elements, such as the generic div container, adding to it Cascading Style Sheets (CSS) and script to make it look and act like a textbox. But, because the accessibility of controls in HTML is read-only, there has been no way to have this custom "textbox" expose itself to assistive technology as an actual input type=text, and assistive technology users might not know that there was supposed to be a textbox.
  • This use of the correct control is referred to as Semantic HTML. Semantic HTML, roles, and names are discussed in much more detail in the Semantic HTML – Role and Name article.
  • The new ARIA technology from the World Wide Web Consortium (W3C) addresses this issue by specifying a set of attributes that can be added to HTML elements to modify the Accessibility API. However, this technology is quite new, and organizations who are still using older browsers may not be able to take advantage of it. The Introduction to ARIA article discusses this technology in general, and the Introduction to ARIA article discusses ways to use ARIA while still providing accessibility for browsers and assistive technology that do not support ARIA.
  • Figure 3: Web Accessibility Technical Overview: The browser maps values from HTML and ARIA to the Accessibility API. ARIA makes use of that information in the same way as it does for a Windows application, exposing it to the end user.

Tip: Introduction to Web Accessibility - How Accessibility Works

  • Assistive technology adds capabilities that the computer doesn't usually have. For example, a visually impaired user might employ assistive technology such as a screen reader and voice recognition, rather than directly using the application with the mouse and screen.
  • For applications on Microsoft platforms such as Windows or Windows Internet Explorer, and on the web, the assistive technology interacts with Microsoft UI Automation, Microsoft Active Accessibility, an application-specific object model such as the Document Object Model (DOM) in Internet Explorer, or some combination of these.
  • For Windows developers, UI Automation and Microsoft Active Accessibility provide an API to which they can write, to assign the appropriate accessibility properties and events. For web developers, certain HTML elements are mapped to Microsoft Active Accessibility and UI Automation objects, so in selecting those HTML elements, the developer can make use of the accessibility properties and events built in to those elements.
  • In both cases, the developer usually needs to be concerned only with ensuring that the API is correctly written to (or that the appropriate element is specified), in order for the application to be accessible, and need not be concerned with the wide variety of types of assistive technology in use ( see Figure 1).
  • Figure 1: Architecture of Accessibility APIs and assistive technology on Windows: the browser interprets HTML and Accessible Rich Internet Applications (ARIA) information, and exposes it to the same platform Accessibility API used by Windows applications.
  • Figure 2: Windows Accessibility Technical Overview: applications expose information to the Accessibility API, which is consumed by assistive technology products and exposed to the user

Tip: Introduction to Web Accessibility - Accessibility in General

  • In the world of computer applications, accessibility is about making applications usable by people with disabilities. These disabilities can range from an inability to detect differences in color, to repetitive stress injuries that make using a mouse difficult.
  • Some people have mobility limitations that require a special input device instead of the keyboard and mouse. Others are visually impaired and require screen reader software that reads aloud to the user what is on the screen. The goal of web accessibility is to provide "equivalent functionality for every user," regardless of their disability. All functions of your applications must be available for all users.
  • With so many people using computers both at home and at work, far more people with varying degrees of disabilities rely on computers to accomplish important tasks. As a result, various standards and regulations have been implemented to help ensure that these users have equal access to software and web applications.
  • According to a 2003 Forrester study commissioned by Microsoft, 57% of working-age adult computer users can benefit from changes made to improve the accessibility of computer applications, and 44% use some form of accessible technology. These changes range from relatively minor modifications to the user interface, such as large fonts or high contrast settings for those with visual impairments, to enabling keyboard navigation for those unable to use a mouse. And the changes include full replacements for the interaction model, such as a screen reader where application content is read to the user, and voice recognition where commands are spoken by the user to the computer.
  • There are also market considerations, as some government organizations, including the United States federal government, are required to purchase the most accessible application in a category. And an application that is the most widely accessible will be able to be used by the greatest number of people. In the case of internal company applications, those that are accessible from the beginning will be usable by all employees without subsequent modifications.
  • The following two reports show findings from the 2003 Forrester study:

Tip: Use a single ADO connection to reduce ASP server load

  • If you need to execute multiple SQL statements on a single database in a single ASP page, it's often wise to open a single Connection and reuse it multiple times. Doing so reduces the number of times the server must open and close the same database, which can significantly increase the server's load. To use a single connection, create the database Connection at the beginning of the page, then destroy it at the end. When you Execute a SQL statement, whethe r it returns a Recordset or not, specify the active Connection. Here's an example.
    • <%strDSN = "DSN=database;UID=username;PWD=password"
    • Set conn = Server(.)CreateObject("ADODB.Connection")
    • conn(.)Open strDSN
    • strSQL = "select column from table"
    • Set rsResults=conn(.)Execute(strSQL, , 1)
    • if not rsResults(.)eof then
    • temp = rsResults("column")
    • else
    • temp = "No Results"
    • end if
    • 'close the Recordset, but leave the Connection open
    • rsResults(.)Close
    • strSQL = "delete from table where column=123"
    • conn(.)Execute strSQL, , 1
    • 'Done executing SQL statements at this point, so close the Connection.
    • conn(.)Close
    • set rsResults = Nothing
    • set conn = Nothing
    • %>
    • Remove the () around the .

Tip: Generate GUID values in ASP

  • In ASP, you have a couple ways to create a GUID. One way is by the script below. It uses the Scriptle type library to generate the value, like this
    • <%guid = server(.)createobject _ ("scriptlet.typelib").guid response(.)write guid%>
    • Remove the () around the .
  • As with all Windows GUID operations, this method uses the current system time to create the unique value. Of course, to take advantage of this technique, you'll need the Scrobj.dll installed on your server

Tip: Use Request.Form to gather all the data from your text input fields (ASP 3.0+)

  • In a previous tip, we showed you how to gather all the data in a QueryString object with a call to Request(.)QueryString without specifying any key values.
  • This technique also works for obtaining all of the values from the text input fields on a form.  For example, we placed two fields and a button on a form using the following HTML code:
    • <Form Method="Post">Public Relations
    • <input type="text" value="Element"name="field1">&nbsp;<input type="text" value="K" name:
    • <input type="submit" value="OK"name="action">
    • </FORM>
  • On the server side, we obtained the field data, like so:
    • <%
    • Response(.)write "?" & Request(.)Form & "
    • "
    • %>
  • When we clicked the OK Button, the server side code displayed the following information on the browser window:
    • ?field1=Element&field2=K&action=OK
  • You'll notice that the string also includes the information about the button we pressed.  If we had to send this data to another asp page, we could do so just by attaching the file address.

Tip: Learn the difference between JavaScript's substr() and substring() functions (Microsoft Scripting Edition 5.0+)

  • It's safe to say that manipulating strings is a critical aspect to learn when using JavaScript.  You'll discover all kinds of reasons for doing so, and to this end, JavaScript contains a host of helpful functions to help you along the way.
  • When you do need to manipulate a string--specifically, when you need to extract a portion of a string from a larger one--keep in mind that JavaScript offers the standard substring() function as well as a newer (relatively) substr() method.
  • With both these functions, you provide a starting index number.  This number tells JavaScript at which character to start the new snippet.  However, the new string WILL NOT actually include the character a t the starting index.
  • For the substring() method, you also supply a second ending index number.  With this number in place, JavaScript extracts the range of characters from the starting to ending index.  For instance, given the following code:
    • var str = new String("JavaScript")
    • var newStr = str.substring(4,10)
    • alert(newStr)
    • The message box would display the string "Script".
  • Unlike substring(), the substr() function's second argument is optional.  In this argument, you enter a number that indicates the length of the desired snippet.  With this in mind, to generate the same results as our previous code using this method, we'd use:
    • var str = new String("JavaScript")
    • var newStr = str.substring(4,6)
    • alert(newStr)

Tip: How to position controls on Web forms (Visual Studio .NET)

  • One of the great things about developing Web applications in Visual Studio .NET is that you can add and manipulate control objects just as you currently do when designing forms in Visual Basic.  ASP .NET allows you to position the controls using the following two methods: GridLayout and FlowLayout.
  • GridLayout is the default method and it offers the greatest flexibility for positioning controls.  You can use your mouse to move the controls to any desired position on the form.  This method is most like what you can do now in the Visual Basic IDE.
  • FormLayout takes away most of your placement control.  In this mode, .NET positions the controls in a reading pattern, from left to right and top to bottom.  You can use the [Spacebar] to place spaces between two controls on a line.  If you place the cursor in front of a control and press the [Enter] key, you can move the control to a new line.
  • If the Web form is currently configured for GridLayout, you can change to FlowLayout by placing the mouse cursor on the form and clicking the right mouse button.  When .Net displays the Document Properties Pages window, you can select FlowLayout from the PageLayout dropdown menu on the General tab.  If .NET doesn't display the Properties windows, you can also select Document from the Properties menu in the solution explorer, scroll down the PageLayout property, and select the desired layout method.

Tip: Download a complete list of all the scripting functions from Microsoft (Microsoft Scripting Edition 5.6)

  • You can download a comprehensive list of all the VBScript and JavaScript functions from the following Microsoft Web Site:
  • http://msdn.microsoft.com/library/default.asp?url=/
  • downloads/list/webdev.asp
  • The help file not only lists the functions, but also the VBScript version that supports it.

Tip: Easily create a single dimensional array suing the Array function (Microsoft Scripting Edition 5.0+)

  • If you need to create a quick single-dimension array to hold some static data, user the VBScript Array function.  The syntax is as follows:
    • Array(val1,Val2,...valn)
  • This feature is perfect for creating small arrays for things like the months of a year or the days of a week.  Because of the flexibility of script code, you can mix strings and integers in your array.  Consider the following code:
    • Dim x
    • x = Array(0,1,"Monday",2,"Tuesday"3,"Wednesday")
    • Response.write x(1) + x(3) & "
    • "
    • Response.write x(2) + x(4)
  • The fires statement would display the number three while the second statement would display Monday Tuesday.  Also, you can use variables or functions to supply the array content.  The following statement creates an array of arrays:
    • Dim x,y
    • y = array(1,2,3)
    • x = Array(y, array(3,4,5), array(6,7,8))

Tip: Pop-up blocking software may be hazardous to your local Web service

  • Downloading pop-up blocking software is a wonderful way to prevent those annoying pop-up windows from invading your PC.  Unfortunately, if you don't set them up properly, they'll interfere with the operation of your local Web service.  We downloaded one op-up blocking program, turned it on and then launched an ASP program using the Open method.  We were able to load our primary page with no problems.  However, when we tried to navigate to the new page, the software blocked us.  Fortunately, there's an easy solution to this problem.  Most pop-up blocking software packages allow you to always accept pop-ups originating from any number of acceptable URL's.  So, before you turn on that pop-up blocking software, take a moment to identify your computer as safe to avoid debugging hassles down the road after you've forgotten that you even turned it on.

Tip: Use the Page.IsPostBack method to obtain the state of your page

  • In traditional ASP, if we wanted to evaluate the state of the current page, we'd use the Request(.)ServerVariables, like so:
    • If Request(.)ServerVariables("REQUEST_METHOD") = "Post" Then... With ASP.NET, we can now accomplish this same task using the Page.IsPostBack function.  You'll use this function, like so:
    • If Page(.)IsPostBack Then...
    • Remove the () around the .
  • If the resulting value is True, the browser has just posted the page to the server. If it's False, then the page is still in Get mode.

Tip: Using the SQLDataReader to select records from a SQL Server database

  • Following are the steps you'll need to take to Select records from a database table using the SQLDataReader:
  • 1) Import the System(.)Data(.)SqlClient namespace
  •     Imports System(.)Data(.)SqlClient
  • 2) Establish a connection to the database
  •     Dim cn As New SqlConnection
  •     cn(.)ConnectionString = "Data Source=yourserver;Database=yourtable;"
  •     cn(.)ConnectionString = cn(.)ConnectionString & "UserID=uid;Password=pw;"
  • 3) Use the connection to create a SQL Command and open the connection
  •     Dim myCMD As SqlCommand =
  •       New SqlCommand("Select * from yourtable",cn)
  •     cn(.)Open()
  • 4) Create a new SQLDataReader using the SqlCommand object Dim myReader As SqlDataReader = myCMD.ExecuteReader()
  • Our final step is to loop through the records in the SQLDataReader. This process will return the first two column headers and the all the database records in the table.  In the following example, we wrote the values out to the debug window.
    • Dim NextResult As Boolean = True
    • Do Until Not NextResult
    •    Console(.)WriteLine(vbTab & myReader(.)GetName(0) & _
    •       vbTab & myReader(.)GetName(1))
    •    Do While myReader(.)Read()
    •       Console(.)WriteLine(vbTab & _
    •          myReader(.)GetString(0) & vbTab & _
    •          myReader(.)GetString(1))
    •    Loop
    •   
    •    NextResult = myReader(.)NextResult()
    • Loop
    •  
    • myReader(.)Close()
    • cn(.)Close()
    • Remove the () around the .

Tip: Be careful when using the InStr function to search string values

  • The InStr() function is the perfect tool for searching for a string within a string and returning the position where it found it.  However, if you have a delimited string of similar values, the InStr() function may not return the correct position.  Consider the following code:
    • t = "boats,coats,floats,oats"
    • Response.write Instr(t,"oats")
  • This call to the InStr() would return a value of 2 because that's the first occurrence of the word "oats" in the string.  Unfortunately, it isn't the "oats" we wanted to find.  For a more precise search, you could do the following:
    • t = "boats,coats,floats,oats"
    • Response.write Instr("," & t & ",",",oats,")
  • Now, we'll get a value of 20, which is the exact location of the word "oats" in the unaltered string.

Tip: Use the table owner to access other databases in a Server group

  • If you're using ISQL or some other query manager, you don't have to switch from your current database to access the tables in another database.  You can simply append the database name and table owner to the table name, like so:
    • Select * From Address_book.dbo.mycontacts

Tip: When you're done with a temporary table, just dump it!

  • We're sure this next tip will make most DB administrators cringe and scramble to revoke their user's permissions.  To delete a SQL Server table, you simply need to execute a query using the Drop keyword and the table name you want to destroy, like so:
    • DROP Table tablename
  • We were also able to perform the task in our ASP code by passing the SQL statement to an open connection, as shown here:
    • result = cn.Execute("Drop Table tablename")
  • If the operation is successful, SQL Server will return a result of True.  We'll try to be responsible and specify that you should only perform this operation on temporary database tables that you created and you should back up your database first to prevent a typo from sending you to the unemployment line.

Tip: Need a temporary table for testing?  Use the SQL Select into statement to create one

  • If you ever need to perform a test but you don't want to destroy your current table data, you can easily create a copy of the data using the SELECT INTO statement.  The syntax for this operation is:
    • SELECT * INTO new_table_name FROM existing_table_name
  • Assuming you have the proper permissions, this statement will create a new table with all the physical information of the existing table.  If you don't need to recreate all the columns of information, you can also specify a subset of the table, like so:
    • SELECT field1, field2, field3 INTO new_table_name from existing_table_name
  • We were able to perform this task in our ASP code by passing the SQL statement to an open connection, as shown here:
    • result = cn.Execute("SELECT * INTO new_table_name from existin_table_name")
  • If the operation is successful, SQL Server will return a result of True.  Keep in mind that these statements perform a data transfer only.  Primary key and index information won't be carried over to the new table.

Tip: Shorten your SQL Query by assigning aliases to long table and field names

  • In the early days of database development, we kept table names and field names down to 6-8 generic characters like XPNOWHS5, NPPDK12B in table WWSYSPDF.  Ten years later when no one knew what these letters represented, the designers moved the naming conventions to the other end of the spectrum in frustration.  Now, the field names are External_Printer_Number_Warehouse_Five in table Worldwide_System_Printer_Definitions.  Who wants to build a query using these names?  If you don't, consider using alias names in place of the long actual names.  Following is a quick example of a query using alias names:
    • Select External_Printer_Number_Warehouse_Five as ep5 from Worldwide_System_Printer_Definitions as wwp Where ep5 <> 'blah'
  • You will, of course, have to use the actual name once in the query.  However, after you've used the As keyword to introduce the alias name, you can use that name for all other times that you reference the table or field.  If desired, you can omit the As keyword when defining aliases.

Tip: Obtain the entire Query String with out entering any key values

  • By now, you've probably used Request(.)QueryString a time or two to obtain the QueryString portion of your URL.  Just to refresh your memory, this is the portion of the URL that looks like the following:
    • ?val1=Abc&val2=Def&val3=Ghi
  • Typically, we'd pull out each item one by one using its key value, like so:
    • ?field1 = Request(.)QueryString("val1")
    • field2 = Request(.)QueryString("val2")
    • field3 = Request(.)QueryString("val3")
  • However, did you know you could obtain the full QueryString value just by calling the function without any key values?  To try it out, just enter the following line of code into your ASP page:
    • Response(.)write Request(.)QueryString & ""
    • Remove the () around the .
  • You should see the entire QueryString without the address information.  This little trick could come in handy if you have a large QueryString that you want to pass to another Web form or even if you'd rather parse the string yourself than list each individual member.

Tip: Locking down your input fields using HTML

  • HTML provides two ways to prevent users from using input fields.  The first way is to include the word DISABLED inside the <input> tag like so:
    • <input type="text" name="some_name" DISABLED>
  • Using this keyword, the input field will have a light gray appearance when the browser loads the page.  The second HTML keyword to lock an input field is READONLY.   You use it in the same way you use the DISABLED keyword, like so:
    • <input type="text" name="some_name" READONLY>
  • With this keyword, the text of the input field will remain black, resembling all the other non-formatted text on the page.

Tip: A simple tip to display borderless text boxes

  • The HTML text box is not only good for accepting user inputs; it can also be used as a label to relay programmatically generated text statements, like error and informational messages.  One of the problems associated with using an input box in this manner, is that the default style for a text box draws an unsightly border around the text box field.  Luckily, you can easily remove the border so that your text box blends in with the rest of the page.  You do so by assigning the following value to the style attribute of the <input> tag:
    • "border: 0;"
  • Using this value, the HTML code to draw a borderless text box will look something like this:
    • <input type="text" name="some_name" style="border: 0;">

Tip: A less taxing alternative to Count(*)

  • For SQL server users, there's an even more resource-friendly way to obtain a table record count than the standard SQL count(*) statement.  You can get the value from the sysindexes table where SQL server automatically stores the most up-to-date count.  The syntax for the SQL query to accomplish this task is as follows:
    • SELECT rows FROM sysindexes WHERE id=OBJECT_ID ('your_table')
  • This method is a slightly faster way to obtain a record count, especially if your database tables are very large.  However, you won't be able to use the Where clause to obtain more specialized record counts, such as SELECT count(*) FROM mytable WHERE hrs > 40.

Tip: Avoid these 3 common JavaScript errors

  • Just as unterminated conditional statements are a problem in VBScript, so are unterminated functions and conditional statements in JavaScript.  For JavaScript, curly braces serve as terminators and should be paired together like so:
    • function myfunction()
    • {
    • }
  • They're also required for your conditional statements, as shown here:
    • if (x == y) {//your code here}
  • Another common mistake occurs when capital letters are used when referencing keywords.  For example, the following JavaScript code is incorrect:
    • Function x(y)
    • {
    • If (y == 12) {alert('yeah');}
    • }
  • JavaScript won't recognize the capital F in Function or the capital I in If.  The final common mistake is unterminated lines of code.  JavaScript uses the semi-colon to terminate lines of code.
  • While remembering to include these in your code may be a pain, there is one small advantage.,  JavaScript doesn't require a line continuation character to break apart long lines of code.  For example in VBScript, you'd need to use an underscore to wrap this long line of code across two lines, like so:
    • longvariablenumber4 = (lonvariablenumber1 * _
    • longvariablenumber2) + longvariablenumber3
  • You'll notice in the following JavaScript code, the underscore isn't necessary:
    • longvariablenumber4 = (lonvariablenumber1 *
    • longvariablenumber2) + longvariablenumber3;
  • So, if your JavaScript code isn't functioning properly, check these areas first and you'll probably find the culprit.

Tip: Think ahead when adding loops and conditional statements to your code

  • Did you know that infinite loops and unterminated conditional statements were among the most common ASP errors?  For this reason, it's a good idea to think ahead when using these constructs and include all required information before adding the actualvmeat of the code.  For example, when building If-Then-Else statements, enter the following:
    • If mycondition Then
    • Else
    • End if
  • Likewise, when looping through recordsets, begin with the following:
    • Do While Not rs.EOF
    •   rs.MoveNext
    • Wend
  • This is especially a good practice when dealing with loops because infinite loops have a tendency to not only crash your code but the entire Web service.

Tip: Your comments are welcome

  • You've probably heard more than you ever wanted to know about the importance of commenting your code.  However, we feel this point can't be stressed enough especially when it comes to ASP code.  Consider, for a moment, the following JavaScript code:
    • this.parent.opener.search.sort.selectedIndex = index
  • Do you know what this code does?  If not, don't worry.  Neither did the author who needed 15 minutes opening 8 different files to determine which file was the parent and what was the purpose of the value being set.  Whereas, a simple comment probably would have saved a lot of time.  Following is the syntax for commenting JavaScript, VBScript, and HTML code:
    • //This is a javaScript comment
    • 'This is a VBSpcript comment
    • <!-- This is an HTML commnt -->
  • Commenting your code only takes a little extra time, but it could mean a big difference if you're looking at the code years later or passing it on to another programmer.

Tip: ASP.NET and SQL Server primary key Newid() default values (ASP.NET 1.0+, SQL 7.0/2000)

  • When the underlying data source of a DataSet table in VB.NET is a SQL Server table with a primary key that's an unique identifier datatype with the NEWID() default value, adding records in a grid in VB.NET will cause an error that the primary key field doesn't allow NULLs.  We know that the key field will be defaulted on SQL Server side, but VB.NET enforces the NULL before the data is pushed to SQL Server.  The solution is easy, since we have access to the dataset XML.  First, we can delete the key form the dataset table by right-clicking on the table and selecting Delete Key.  The field isn't deleted, just the key indicator for the field.  Now the field won't require a unique value, but we still need to allow the value to be NULL.  You can do this by adding minOccurs="0" to the <xs:element> code for this field as in the example below:
    • <xs:element
    •    name="KeyFieldName"
    •    msdata:DataType="System.Guid, mscorlib, version=1.0.3300.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"
    • type="xs:string"
    • minOccurs="0" />
  • Now records can be added to the grid without raising any errors, and SQL Server will default the key field values with NEWID() once the table is updated.

Tip: Trap timeout errors in ASP (2.0/3.0)

  • It's a common practice to trap ASP script errors with an On Error Resume Next, but what about script timeouts?  These "errors" can't be trapped using this technique, but there *is* a way to detect and react to them.  To do so, you have to make your ASP page utilize MTS transactions.  Once you do this, a timeout, like other errors, will cause the transaction to fail, and you can provide an OnTransactionAbourt procedure to respond.  The client browser will still see a timeout error, but you'll be able to take any programmatic action your application might require.  Here's a skeletal example of how you might use this technique:
    • <%@ Transaction=Required language="VBScript" %>
    •  
    • 'Your routine ASP code goes here...
    • Sub OnTransactionAbort()
    •    Response.Write "The transaction has been aborted, probably due to a timeout!"
    •    'Do whatever cleanup, logging, or other reporting you might need
    • End Sub
    • %>

Tip: Return and display images from Oracle in ASP (ASP 2.0/3.0, Oracle 8+)

  • Oracle tables can use columns of the RAW or LONG RAW data type to store images.  These columns are relatively easy to access from ASP and display in a browser.  In fact, they're a little bit more straightforward than accessing BLOB data from Microsoft SQL Server.  Here's how to do it:
    • <%
    • Response(.)Expires = 0
    • Response(.)Buffer = True
    • Response(.)Clear
    • Response(.)ContentType = "image/gif"
    •  
    • 'Establish your connection to Oracle
    • Set oConn = Server(.)CreateObject("ADODB(.)Connection")
    • oConn(.)Open "DSN = ..."
    •  
    • Set oRS = Server(.)CreateObject("ADODB(.)Recordset")
    • oRS(.)Source = "SELECT ImageID, RawImage FROM MyImagesTable WHERE ImageID = "123"
    • Set oRS(.)ActiveConnection = oConn
    • oRS(.)Open
    •  
    • Response(.)BinaryWrite(oRS("IMG"))
    • Response(.)End
    •  
    • oRS(.)Close
    • oConn(.)Close
    • Set oRS = Nothing
    • Set oConn = Nothing
    • %>
    • Remove the () around the .
  • Obviously, for JPEG images, you should change the ContentType property to "image/jpeg".

Tip: Transform XML through XSLT in ASP.NET (ASP.NET 1.0+)

  • With classic ASP, as you know from previous tips, you can use the MSXML DOM to transform XML content with XSLT and display the results in your Web browser.  So how do you do this in ASP.NET?  The answer, like most answers to previously complicated questions, is very simple:  user the XML server control.
  • To do so, all you do is drag an XML control onto the design surface of your Web page (or add it programmatically to the script source), then specify the location of the XML document as well as the XSLT stylesheet to use in transforming it.  For instance:
    • <asp:xml runat="server" id="MyXmlDoc"
    •     DocumentSource="sourcedata.xml"
    •     TransformSource="transformation.xsl" />
  • The results are streamed right into the browser; no code is needed!

Tip: Reap new benefits with ASP.NET and IIS 6.0 (ASP.NET 1.0+)

  • As you know, ASP.NET works quite well with IIS 5.0, but with the recent release of Windows Server 2003, IIS 6.0 comes with even tighter integration with .NET.  This results in better performance and reliability.  In particular, here are some of the key benefits of upgrading to IIS 6.0:
  • With IIS 6.0, ASP.NET has fully caching capabilities, including the ability to cache complete responses.  And this can improve performance in a big way.  In addition, whereas ASP.NET and IIS 5.0 communicated through the proxy process of ASPNET_WP.EXE, under IIS 6.0, ASP.NET now runs completely in-process with IIS.  As far as reliability is concerned, IIS 6.0 includes better and more complete application isolation capabilities than its predecessor.  Lastly, IIS 6.0 and ASP.NET are more tightly integrated to detect deadlocking and other problems that indicate the need for process recycling, resulting in better overall responsiveness and reliability.
  • Obviously, upgrading your Web server isn't a simple decision; it's one in which you have to consider many different factors.  But IIS 6.0 offers several key improvements which might be just the incentive you need.

Tip: IIS 6.0 features: The metabase becomes a robust XML document

  • Now that Windows Server 2003 has hit the streets, many of you may be wondering about the new features of IIS 6.0.  One of the best of these is the new metabase.  Where under IIS 5.0 and earlier versions, the metabase was a fragile, binary file which could only be edited through a utility (like MetaEdit) or an API (like ADSI), the new metabase in IIS 6.0 is a straightforward (if not succinct) XML document.  This means that you can edit it directly, with any text editor, XML editor, or even Visual Studio .NET.
  • As soon as you make the change and save the metabase.xml file, a Web service monitoring the file for changes notifies IIS, which incorporates the changes.  This results in a small delay; however, you don't have to stop and restart IIS.  And what happens if you munge up the file with some poorly-formed XML?  Not to worry: IIS 6.0 is smart enough to detect this.  In that case, it discards the changes and reloads the last-known-good metabase.  In prior versions, you could easily render IIS inoperable by monkeying around with the metabase.  Not so with IIS 6.0!

Tip: Learn ASP.NET by example with new, complete sample applications from Microsoft

  • Microsoft has released a new series of end-to-end sample applications to demonstrate principles of ASP.NET application development and best practices.  These are great learning tools for programmers new to ASP.NET, and can be found at www.asp.net/Default.aspx?tabindex=9&tabid=47.  There are several different applications, each representing a common business application for the Web.  They include the following:
    • * The Time Tracker Starter Kit demonstrates a time-tracking and project management application.
    • * The Reports Starter Kit shows how to build dynamic reports in various formats using real data from a SQL Server of other data source.
    • * The Community Starter Kit allows you to create a community-oriented site for news, resources, or events, photos, and more.
    • * The Commerce Starter kit provides a skeleton for building an Internet storefront, complete with ASP.NET implementations of shopping carts, product catalogs, and order submission.
    • The Portal Starter Kit illustrates how to build dynamic portal applications with pluggable portal modules.
  • All the source code is available for your use, free of charge, and you can learn a lot from examining it.  You can even run live versions of the starter kits online before you download them.

Tip: Increase performance by avoiding unnecessary logging

  • Capturing information about which of your ASP pages are accessed when and by whom, in addition to any number of other metrics, can be essential for running a reliable and secure Web site.  But logging can go too far.  When every possible ounce of performance matters, you might want to consider whether to log the activity in particular directories of your Web site.  For example, if your site uses many images, and if these images are all stored in a common directory, there's really very little justification for logging each and every image access request on your Web server.  Keeping track of this kind of information not only takes up disk space, but it also has a measurable effect on performance.  Through small, this performance impact can add up if your site uses many thousands of images or experiences very heavy traffic.
  • To make this change, launch the Internet Services manager.  Drill down to the directory for which you'd like to stop logging request.  Right-click on the directory, and then choose Properties.  In the resulting dialog box, deselect the Log Visits check box, and then click OK.  For a production Web site, the information you're sacrificing isn't particularly useful anyway, and your server will get a performance boost in the process.

Tip: Help! My ASP code runs on one computer but not on another!

  • So, you've got your code written, tested, debugged, and finalized on your development machine and you deploy it to a server only to find that something breaks.  What do you do?  There are, of course, many reasons this might occur, but the best first steps in troubleshooting the problem are the following:
    • * Ensure that any components you're referencing are installed and registered on the target computer.
    • * Verify that component versions are between computers are compatible.  MDAC/ADO is a big culprit here, and Microsoft provides a version checker for MDAC at www.microsoft.com/data
    • * Make sure you've got a version of VBScript or JScript sufficient for the tasks you're undertaking in your scripts.  Microsoft provides tables showing which scripting features and functions were introduced with which versions of the scripting engines.  For VBScript, see msdn.microsoft.com/library/en-us/script56/html/vtoriVersionInformation.asp, and for JScript, see msdn.microsoft.com/library/en-us/script56/html/js56jsoriVersionInformation.asp

Tip: Translate generic ASP error code with a little help from Microsoft

  • You're probably tired of trying to figure out what caused an error in your ASP page when all it spits out is something like this:
    • ASP 0100
  • Active Server Pages often returns a generic error with little information to help you diagnose the problem.  Worse, all you get is the error number.  How do you track down the problem when you aren't even sure what the error is?  The answer is to look up the error in the handy table:
    • http://support.microsoft.com/default.aspx?scid=kb;en-us;Q294271
    • This Knowledge Base article translates error codes into their associated descriptions for all versions of IIS (all the way up to version 6.0)

Tip: Rate your Web site's content to protect children from inappropriate material

  • Content ratings are often overlooked in Web site development, but rating your content's suitability for younger audiences is a very responsible thing to do.  To rate a page or Web application, access the Properties dialog box for it in the Internet Services Manager, and then select the HTTP Headers tab.  Click the Edit Ratings button to invoke the Content Rating dialog box.  Once there, select the Ratings tab and select the Enable Ratings For This Resource check box.
  • Now, to rate the page, directory, or site, use the slider control to provide ratings in each of the four RASC categories: violence, nudity, sex, and language.  You'll also need to provide a name and date to identify the ratings.

Tip: Comparing Server(.)CreateObject and the <object> tag in ASP

  • As you may know, there are two ways you can create a COM object in Active Server Pages.  These two equivalent methods are shown here:
    • <%
    • 'Using Server(.)CreateObject
    • Dim fso
    • Set fso = Server(.)CreateObject_("Scripting(.)FileSystemObject")
    • %>
    •  
    • <!-- Using the <object> tag -->
    • <object runat="server" id="fso" progid="Scripting(.)FileSystemObject"></object>
  • Apart from being slightly more succinct, the <object> tag method has another advantage.  When you use Server(.)CreateObject, the COM object is instantiated immediately, whether you actually end up using it or not.  With <object>, on the other hand, the object isn't instantiated at all until the first time you set one of its properties or call one of its methods.  This can help you converse memory in an application where every byte counts.

Tip: Show your Web site users you know what time it is

  • A nice element you can easily add to your ASP-based Web sites is a time-based greeting or other interface element.  For example, you can greet your users with a hearty "Good Morning!" or a tranquil "Good Evening" based on the time of day.  take a look at the following function for an idea of how easy this is to implement:
    • <%
    • Function GreetUser()
    •    Dim intHour
    •  
    •    intHour = Hour(Now)
    •  
    •    If intHour >= 0 and intHour < 12 Then
    •       GreetUser = "Good Morning"
    •    ElseIf intHour > 12 and intHour < 18 Then
    •       GreetUser = "Good Afternoon"
    •    Else
    •       GreetUser = "Good Evening"
    •    End If
    • End Function
    • %>
  • You might also try basing the selection of images or color schemes on the time of day.  Or here's another idea.  Why not also look at the date?  Then, you can adjust the appearance of your Web site to reflect the seasons of the year.  In the end, you'll have a more visually interesting site, which can help keep users coming back.

Tip: Tip: Another way to watch for and prevent SQL injection attacks in your Web applications

  • In a previous tip, we discussed how SQL injection attacks in poorly protected Web pages can jeopardize your critical business systems.  Here's another way to prevent them.  Look for semicolons in the item posted to the Web page before executing a SQL statement and/or make semicolons invalid characters in your form fields.
  • This would look something like this:
    • <%
    • Set cn = Server(.)CreateObject("ADODB(.)connection")
    • strSQL = "SELECT * FROM Users WHERE UserID=" & Request("UserID")
    • cn.Open 'Some valid ConnectionString
    •  
    • If Instr(1,Request("UserID"),",") = ) Then
    •     Set rs = cn.Execute(strSQL)
    • Else
    •   Response(.)Write "Invalid Character (semicolon) Detected in UserName Field."
    • End If
    • %>
    • Remove the () around the .

Tip: Hide inline frames scroll bars in your Web applications

  • Have you ever presented dynamic content in an inline frame and wished you could get rid of the scroll bars?  the following bit of code inserted as a function in the parent page will allow you to do it:
    • <script language='javascript'>
    •    function resetlFrame(){
    •       //Dynamically resize frame based on the frame's content.
    •      var iDocheight = window.frames
    •      ("insetFrame").document.forms(0).scrollHeight + 30;
    •      var iDocWidth = window.frames("insetFrame").document.
    •      forms(0).scrollWidth + 30;
    •      document.all.insetFrame.width = iDocWidth;
    •      document.all.insetFrame.height = iDocHeight;
    •   }
    • </script>
  • Then, simply call the function in your onload event in the iframe:
    • <iframe id='insetFrame' name='insetFrame' onload='resetlFrame()'
    • frameborder='0' width='600px' height='500px' src='http://www.myapp.com'></iframe>
  • After the frame loads, it will resize itself based on the new content, and the scroll bars will disappear.

Tip: Hide inline frames scroll bars in your Web applications

  • There may be occasions, particularly when you deploy code onto one machine from another, where you encounter the following error:  Invalid Default Script Language )or a slight variation on this wording).  Why does this occur?  First off, double-check your page directive for typos such as "VBScrip" or JScirpt".  Of course, if the code was running on one machine successfully, then there's a different problem:  The scripting language you've chosen may not be available on the target machine.  To check, launch the Internet Services Manager, right-click on the Web site or virtual directory that's malfunctioning, and choose Properties.  Then, on the Home Directory tab, click the Configuration button.  Click on the App Options tab and examine the Default ASP Language text box.  Ensure that a valid entry exists here.  And, if this doesn't work download the latest scripting engines from Microsoft at msdn.microsoft.com/scripting.

Tip: Handling the Invalid Default Script Language error in ASP

  • There may be occasions, particularly when you deploy code onto one machine from another, where you encounter the following error:  Invalid Default Script Language )or a slight variation on this wording).  Why does this occur?  First off, double-check your page directive for typos such as "VBScrip" or JScirpt".  Of course, if the code was running on one machine successfully, then there's a different problem:  The scripting language you've chosen may not be available on the target machine.  To check, launch the Internet Services Manager, right-click on the Web site or virtual directory that's malfunctioning, and choose Properties.  Then, on the Home Directory tab, click the Configuration button.  Click on the App Options tab and examine the Default ASP Language text box.  Ensure that a valid entry exists here.  And, if this doesn't work download the latest scripting engines from Microsoft at msdn.microsoft.com/scripting.

Tip: What to do when you want to use optional function parameters in ASP

  • One of the disadvantages of VBScript is that, unlike the Visual Basic language, of which it's a subset, VBScript doesn't support the declaration of optional parameters in subroutines or functions.  You can, of course, work around this in a couple of ways.  For example, you can pass in an array instead of a more basic parameter type.  Then, include members of the array for each parameter you want to pass.  "Optional parameters" correspond simply to omitted members of the array.  Or you can declare the parameter, but always pass an empty value for it, like this:
    • Call TestFn("TestString","")
  • But these are both relatively clumsy solutions.  JScript, on the other hand, *does* support optional parameters.  And it's a perfectly valid choice for server-side ASP code.  Here's an example of how to use optional parameters in JScript:
    • function TestFn(Param1, Param2)
    •    {
    •    Response.Write(Param1 + Param2);
    •    }
    • TestFn('1','2')
    • TestFn('1');

Tip: My ASP page is timing out! What do I do?

  • It's just a fact of Web development that some ASP pages take longer to execute than others.  Often, the culprit is heavy database or COM component activity.  Of course, you'll want to try and minimize the amount of time it takes a page to run, but occasionally, you just have to live with the fact that a particular process isn't very snappy.  In those cases, you can experience timeout errors in ASP.  This is because the default amount of time IIS allows for an ASP page to complete its work is 90 seconds.  Normally, that's plenty of time, but in some cases you need to adjust it, here's how:
  • Launch the Internet Services Manager, locate the virtual directory the contains your page; then right-click and choose Properties.  Then, on the Virtual Directory tab, click the Configuration button.  Next, on the App Options tab, enter a new timeout value in the ASP Script Timeout text box.  Click OK twice and you're set.

Tip: Change the default ASP scripting language used in Visual InterDev 6.0

  • If you need to change the default scripting language in VI6.0, it isn't terribly difficult to do, if you know where to look.  Right-click on your project in the Solution Explorer and choose Project Properties.  Then, click on the Editor Defaults tab.  In the Default Scripting Language dropdown list, which will be automatically populated with all installed Active Scripting Engines, choose the new default.  This is how, for instance, you can choose PerlScript or Python as your new default scripting language in VI6.0.

Tip: Help! My ASP Session or Application variables have disappeared!

  • Suppose you're working with an ASP Web application that depends upon Session or Application variables and all of a sudden you realize they've disappeared.  What can cause this?
  • For Session variables, the most common cause is that the Session has expired.  You can configure an entire Web site as well as individual Web applications with their own Session expiration time limits.  The default is 20 minutes.  If the user leaves a browser idle for that long--poof!--his Session variables will be destroyed.
  • For Application variables, this usually happens if the Web site has been stopped and restarted, if the Web server itself has been stopped and restarted, or if the Global.asa file for the Web application has been changed.  Since the first two would usually result in the entire application being unavailable, check the last modified date of Global.asa to see if a fellow developer has made a change without telling you.  You'd be surprised how often this happens!

Tip: Change the default ASP scripting language used in Visual InterDev 6.0

  • If you need to change the default scripting language in VI6.0, it isn't terribly difficult to do, if you know where to look.  Right-click on your project in the Solution Explorer and choose Project Properties.  Then, click on the Editor Defaults tab.  In the Default Scripting Language dropdown list, which will be automatically populated with all installed Active Scripting Engines, choose the new default.  This is how, for instance, you can choose PerlScript or Python as your new default scripting language in VI6.0.

Tip: Help! My ASP Session or Application variables have disappeared!

  • Suppose you're working with an ASP Web application that depends upon Session or Application variables and all of a sudden you realize they've disappeared.  What can cause this?
  • For Session variables, the most common cause is that the Session has expired.  You can configure an entire Web site as well as individual Web applications with their own Session expiration time limits.  The default is 20 minutes.  If the user leaves a browser idle for that long--poof!--his Session variables will be destroyed.
  • For Application variables, this usually happens if the Web site has been stopped and restarted, if the Web server itself has been stopped and restarted, or if the Global.asa file for the Web application has been changed.  Since the first two would usually result in the entire application being unavailable, check the last modified date of Global.asa to see if a fellow developer has made a change without telling you.  You'd be surprised how often this happens!

Tip: How do I host ASP or ASP.NET Web sites using Microsoft Windows XP Home Edition?

  • The short answer is: You don't.  Microsoft doesn't provide or support IIS with the Home Edition of Windows XP, and although there are some posted workarounds to getting IIS installed and running with XP Home, we can't endorse or recommend them.  The best solution is to upgrade XP Home Edition to XP Professional.  It isn't expensive, and you won't run the risk of breaking something in an effort to force XP Home Edition to do something Microsoft hasn't designed it to do.