Setting new window location with JavaScript 13 August 2004 at 00:00
<SCRIPT LANGUAGE="JAVASCRIPT">
    var top = 100;
    var left = 400;
    var w = 280;
    var h = 210;
    // adjust left and top position of new window
    left = (screen.availWidth / 2) - (w / 2);
    top = (screen.availHeight / 2) - (h / 2);
    window.open ('YourPage.htm', 'winValidation', 'width=' + w + ',height=' + h + ',
     resizable=1,left=' + left + ',top=' + top + ',scrollbars=0');
</SCRIPT>
Javascript : Instantiating and Using ActiveX Objects 13 August 2004 at 00:00
You can use ActiveX objects from within your client-side JavaScript code, although you will need to open up the security restrictions for the required zone. This is usually only done on Intranet settings - by default it's locked down for all zones.
  <HEAD>
  <SCRIPT LANGUAGE="JAVASCRIPT">
  
  // create reference to object
  var objMine;

  /**
  * Initialisation function - creates active x object
  */
  function initialise() {
    objMine = new ActiveXObject("MyProject.MyClass");
    document.myForm.myTextBox.value = objMine.SomeProperty;
  }

  /**
  * Clean up function when page unloads - gets rid of activeX object
  */
  function cleanUp() {
    objMine = null;
  }

  </SCRIPT>
  </HEAD>
  <BODY onLoad="initialise()" onUnLoad="cleanUp()">
A JavaScript Vector object 13 August 2004 at 00:00
  /**
  Vector object simulating the vector object used in the Java programming language.
  */
  function Vector() {
    this.myArr = new Array();
    this.size = size;
    this.addElement = addElement;
    this.elementAt = elementAt;
    this.contains = contains;
    this.indexOf = indexOf;
    this.removeElementAt = removeElementAt;
    this.toString = toString;
  }

  /**
  * Function to determine how many elements are contained in the vector
  */
  function size() {
    return this.myArr.length;
  }

  /**
  * Add an element to the vector
  * @param  newElement  element to be added to the vector
  */
  function addElement(newElement) {
    var newPos = this.size();
    this.myArr[newPos] = newElement;
  }

  /**
  * Find out the item contained at a certain position in the vector
  * @param  where index to look for the item
  */
  function elementAt(where) {
    if (where > (this.size() -1)) {
      return -1;
    }
    else {
      return this.myArr[where];
    }
  }

  /**
  * Check to see whether the vector contains a specific element
  * @param  element   object you are looking for
  */
  function contains(element) {
    for (var i=0; i < this.size(); i++) {
      if (this.elementAt(i) == element) {
        // found element!
        return true;
      }
    }
    // element not found
    return false;
  }

  /**
  * Find out the specific location of a specific element
  * @param  item  Object you are looking for
  */
  function indexOf(item) {
    for (i=0; i < this.size(); i++) {
      if (item == this.elementAt(i)) {
        return i;
      }
    }
    // element not found - return -1
    return -1;
  }

  /**
  * Function to remove an element from the vector
  * @param  index   The position of the element in the vector which you want to remove
  */
  function removeElementAt(index) {
    // make a temporary array
    var tmpArr = new Array();
    var cnt = 0;
    // loop through the vector object's array, adding all elements EXCEPT the unwanted
    // element to the temp array
    for (i=0; i < this.myArr.length; i++) {
      if (i != index) {
        tmpArr[cnt] = this.myArr[i];
        cnt++;
      }
    }
    // reset the vector objects array to the temp array
    this.myArr = tmpArr;
  }

  /**
  * Get a string representation of the vector object
  * @param  passDelim (optional) Delimiter to split the elements of the string up with (defaults 
  *                   to a comma if no argument is passed.
  */
  function toString(passDelim) {
    var outStr = '';
    var commaStr = '';
    var delim = ',';
    if (arguments.length > 0) {
      delim = passDelim;
    }  
    for (var i=0; i < this.size(); i++) {
      outStr = outStr + commaStr + this.elementAt(i);
      commaStr = delim;
    }
    return outStr;
  }
JavaScript Modal Dialog Boxes with Internet Explorer 13 August 2004 at 00:00
With Internet Explorer 4+, you can create modal dialog boxes for your web site. The basic syntax is:
vReturnValue = window.showModalDialog(sURL [, vArguments] [, sFeatures])
where
  • sURL is the url of the page to be displayed in the dialog box
  • vArguments is a list of arguments to be sent to the new window (zero length string if none)
  • sFeatures are semi-colon-delimited extra features for the new window:
    • dialogHeight
    • dialogLeft
    • dialogTop
    • dialogWidth
    • center (1/0)
    • dialogHide (1/0)
    • edge (sunken/raised)
    • resizable (1/0)
    • scroll (1/0)
    • status (1/0)

For example:
var sFeatures="dialogHeight: 100px; dialogWidth: 100px;";
window.showModalDialog("showModalDialog_target.htm", "", sFeatures)
Return value: For the return value, in the HTML page that was opened as a dialog page, you need to have the following code:
window.returnValue = 'whatever';

Getting window.opener

With modal dialog boxes you can't call window.opener to get a reference to the parent window. Instead, you need to pass the window as one of the arguments when opening the dialog box:

  // when opening the window:
  window.showModalDialog("page.htm", window, features);

  // in the dialog window:
  var parent = window.dialogArguments;

Form Submission in the Modal Dialog

If you want to be able to submit form values within the modal dialog box before returning a value to the parent page, you need to add the following tag in your dialog page (in the head section):

  <base target="_self">
JavaScript Regular Expressions 13 August 2004 at 00:00
Regular expressions are objects in JavaScript. For example, if you have an input field that should only allow characters a-z (lower and upper case) and numerical digits, you could use regular expressions to do the input validation as follows:
function cleanData() {
  var inputStr = document.myTxtBox.value;
  var re = new RegExp("[a-z]|[A-Z]|[0-9]");
  var outStr = "";
  var c;
  for (var i=0; i < inputStr.length; i++) { 
    c = inputStr.charAt(i);
    if (re.exec(c) != null) {
      outStr += c;
    }
  }
  document.myTxtBox.value = outStr;
}
JavaScript pop-up boxes 13 August 2004 at 00:00
The example here is specific to IE4+, but can easily be adjusted for Netscape. You need three elements in your HTML document:

1. Div reference in the style portion of the document

<style type="text/css">
#divInfo {
  width: 300px;
  height: 60px;
  background: #F0F0F0;
  color: black;
  visibility: hidden;
  position: absolute;
  font-family: tahoma;
  font-size: 8pt;
  border-bottom: #A0A0A0 1px solid;
  border-top: #A0A0A0 1px solid;
  border-left: #A0A0A0 1px solid;
  border-right: #A0A0A0 1px solid;
  padding: 4;
}
</style>

2. JavaScript handling the showing and hiding of the div

<SCRIPT LANGUAGE="javascript">

// global variables for keeping track of mouse x and y co-ordinates
var x = 0;
var y = 0;

/**
* Called with the onMouseOut event to hide the information div
*/
function hideInfo() {
	document.all.divInfo.style.visibility = "hidden";
}

/**
* Keeps x and y variables in sync with the mouse position
*/
function mouseMove(e) {
  x = event.x + document.body.scrollLeft + 5;
  y = event.y + document.body.scrollTop + 5;
  // reset x and y if div goes off screen
  if ((document.body.offsetHeight - y) < 60) {
    y = document.body.offsetHeight - 60;
  }
  if ((document.body.offsetWidth - x) < 300) {
    x = document.body.offsetWidth - 300;
  }
}

/**
* Shows the information in the tooltip box
* @param	info	Information to display
*/
function showInfo(info) {
  var obj = document.all.divInfo;
  // only show if there is information to display and the box is 
  // not already visible
  if ((info == '') || (obj.style.visibility == "visible")) {
    return;
  }
  obj.style.left = x;
  obj.style.top = y;
  obj.innerHTML = info;
  obj.style.visibility = "visible";
}

// enable tracking of mouseMove event
document.onmousemove = mouseMove;

</SCRIPT>

3. Add the events to the document

..
<table onMouseOver="showInfo('your text')" onMouseOut="hideInfo()">..
Changing element background colours dynamically 13 August 2004 at 00:00
For the document body, you use the bgColor property
  function changeCol(col) {  
    eval('document.bgColor = "' + col + '"');
  }
However, for example if you want to highlight an entire table row, you use the backgroundColor property:
<tr id="row1" style="cursor: hand;" class="rs" 
onMouseOver="this.style.backgroundColor='blue" 
onMouseOut="this.style.backgroundColor='red'">...
Note: The row colouring code only works in IE+. Also, you must not set a background colour (HTML or CSS) on the <td> cells themselves as the highlighting will not show.
JavaScript Data Validation Functions 13 August 2004 at 00:00
These functions can be used to validate data on the client before submitting to the server. However, server-side validation should still occur - some older browsers which ignore javascript may not go through the validation process.
  /**
  * Checks to see that the user has entered a valid date (in dd/mm/yyyy format).  
  * @param  dt Date value
  * @returns Empty string if valid, otherwise the error.
  */
  function checkDate(dt) {
    var re = new RegExp('[0-3][0-9]/[0-1][0-9]/[1-2][0-9][0-9][0-9]');
    // check regular expression for form
    if (!re.test(dt)) {
      return 'Date must be in the format dd/mm/yyyy';
    }
    // make sure month is in ranger
    var mon = dt.substring(3, 5);
    if (mon.indexOf('0') == 0) mon = mon.replace('0', '');
    mon = parseInt(mon);
    if (mon < 1 || mon > 12) {
      return dt.substring(3, 5) + ' is an invalid month - it must be in the range 01 - 12';	
    }
    // check if leapyear
    var year = parseInt(dt.substring(6, 10));
    var isLeapYear = ((year % 4) == 0);
    // make sure day is in range for the month
    var day = dt.substring(0, 2);
    if (day.indexOf('0') == 0) day = day.replace('0', '');
    day = parseInt(day);
    if (day < 1) return 'Day cannot be less than 1';
    switch (mon) {
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:
        if (day > 31) return ('Day cannot be greater than 31 for month ' + mon);
        break;
      case 2:
        if ((isLeapYear) && (day > 29)) {
          return ('Day cannot be greater than 29 for month ' + mon);
        }
        if ((!isLeapYear) && (day > 28)) {
          return ('Day cannot be greater than 28 for month ' + mon);
        }
        break;
      case 4:
      case 6:
      case 9:
      case 11:
        if (day > 30) return ('Day cannot be greater than 30 for month ' + mon);
        break;
    }
    return '';
  }

  /**
  * function to check that user has entered a valid email address
  * @param  obj Text field where onBlur event has occurred
  */
  function checkEmail(obj) {
    if ((obj.value.indexOf('@') == -1) || (obj.value.indexOf('.') == -1)) {
      obj.value = "";
      return;
    }
  }

  /**
  * Function to remove all characters except for numbers from an input box
  * @param  obj Text field where onBlur event has occurred
  */
  function removeAlpha(obj) {
    var inputStr = obj.value;
    var outStr = "";
    for (var i=0; i < inputStr.length; i++) { 
      var c = inputStr.charAt(i);
      if (!isNaN(c)) {
        outStr = outStr + c;            
      }
    }
    obj.value = outStr;
  }

  /**
  * Removes characters from input box
  * @param  obj Text field where onBlur event has occurred
  * @param  ch  Character type to be removed
  */
  function removeChars(obj, ch) {
    var inputStr = obj.value;
    var outStr = "";
    for (var i=0; i < inputStr.length; i++) { 
      var c = inputStr.charAt(i);
      if (c != ch) {
        outStr = outStr + c;            
      }
    }
    obj.value = outStr;
  }
JavaScript Error Handling 13 August 2004 at 00:00

Error trapping with JavaScript only works for newer generation browsers. However, older browser generally ignore window.onerror code, so it is worth putting in. There are two ways to do this:

Handling Errors via the window.onerror DHTML Event
    function reportError(msg,url,line) {
      // do what you want with the message (msg), url (url) 
      // and line number (line) here
      return true;
    }

    window.onerror = reportError;
Handling Errors via ECMAScript 2.0 Exception Handling
  try {
    // code that may cause an error
  }
  catch (exception) {
    alert(err.number + ' ' + err.description);
  }
  finally {
     // code that is always executed
  }
JavaScript Trim Method 13 August 2004 at 00:00

There are number of ways you can trim strings using javascript. The best way is to prototype the string object, adding a trim method, so you can perform the action by merely calling "string.trim()".

Regular expressions provide a slick way of trimming strings, but at the time of writing regular expression implementations can be buggy in some browsers, and you may find it doesn't always work. This will probably be the standard going forward.

Trimming with Regular Expressions

  // Add a function called trim as a method of the prototype 
  // object of the String constructor.
  String.prototype.trim = function() {
    // Use a regular expression to replace leading and trailing 
    // spaces with the empty string
    return this.replace(/^(s+)?(.*S)(s+)?$/, '$2');
  }

For now, a more reliable way is to just use the substring method and just loop through the string characters. The following three methods provide a left trim, right trim and full trim:

Trimming using substrings

  // remove leading whitespace
  String.prototype.ltrim = function() {
    var str = this;
    while (str.length > 0) {
      var ch = str.substr(0,1);
      if ((ch == ' ') || (ch == 'n') || (ch == 'r') || (ch == 't') || (ch == 'f')) {
        str = str.substring(1);
      }
      else {
        break;
      }
    }
    return str;
  }

  // remove trailing whitespace
  String.prototype.rtrim = function() {
    var str = this;
    while (str.length > 0) {
      var ch = str.substr(str.length - 1, 1);
      if ((ch == ' ') || (ch == 'n') || (ch == 'r') || (ch == 't') || (ch == 'f')) {
        str = str.substring(0, str.length - 1);
      }
      else {
        break;
      }
    }
    return str;
  }

  // remove leading and trailing whitespace
  String.prototype.trim = function() {
    var str = this.ltrim();
    return str.rtrim();
  }
JavaScript replaceAll Function 13 August 2004 at 00:00
The JavaScript replace() function does not replace all instances of the query string - only the first one encountered. This function replaces all instances of the unwanted string.
/**
 * @param strChk      String to be cleaned
 * @param strFind     String to replace
 * @param strReplace  String to insert
 * @return            String without unwanted characters/strings
 */
function replaceAll(strChk, strFind, strReplace) {
  var strOut = strChk;
  while (strOut.indexOf(strFind) > -1) {
    strOut = strOut.replace(strFind, strReplace);
  }
  return strOut;
}

Alternatively, a cleaner approach is to prototype the string object, effectively adding the replaceAll method to the string class. Using the following approach, you can then use this method as you would any other string method, e.g. yourstring.replaceAll('a', 'b');

String.prototype.replaceAll = function(find, replace) {
  var str = this;
  while (str.indexOf(find) > -1) {
    str = str.replace(find, replace);
  }
  return str;
}
Cross-browser screen dimensions with JavaScript 13 August 2004 at 00:00
In order to calculate the user's available screen width and height use the screen object:
// available dimensions excluding toolbars
screen.availWidth
screen.availHeight

// screen size
screen.height
screen.width
However, in order to calculate the size of the screen actually showing, you need to make the following calls AFTER the page has loaded:

Netscape

// gets the size of the visible window
window.innerWidth
window.innerHeight
// gets the size of the document
document.width
document.height

Internet Explorer

// gets the size of the visible window
document.body.clientHeight
document.body.clientWidth
// gets the size of the document
document.body.scrollHeight
document.body.scrollWidth
Example You want a div to stretch from top to bottom:
  var oFill = document.getElementById("mnuFill");
  var iFill = (ie ? document.body.clientHeight : window.innerHeight);
  if (ie && (document.body.scrollHeight > iFill)) {
    iFill = document.body.scrollHeight;
  }
  if ((!ie) && (document.height > iFill)) {
    iFill = document.height;
  }
  oFill.style.height = (iFill) + 'px';
Dynamic images with ASP.NET 06 August 2004 at 00:00

Creating dynamic images with ASP.NET is simple using the System.Drawing namespaces:

WebForm1.aspx

<%@ Page language="c#" Codebehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm1" %>

WebForm1.aspx.cs

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
...
private void Page_Load(object sender, System.EventArgs e) {
  Response.Clear();
  int height = 100;
  int width = 200;
  Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format64bppArgb);
  // set up encoding options
  EncoderParameters encoderParams = new EncoderParameters();
  long[] quality = new long[1];
  quality[0] = 90;	// valid values 0 to 100
  EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, quality);
  encoderParams.Param[0] = encoderParam;
  ImageCodecInfo info = this.GetEncoderInfo();
  // get graphics context
  Graphics graphics = Graphics.FromImage(bitmap);
  // set alias and color to fill with
  graphics.SmoothingMode = SmoothingMode.AntiAlias;
  graphics.Clear(Color.RosyBrown);
  // create borders around the image
  graphics.DrawRectangle(Pens.White, 1, 1, width - 3, height - 3);
  graphics.DrawRectangle(Pens.Black, 1, 1, width, height);
  // write some text to the image
  graphics.DrawString("This is a test image!", new Font("Arial", 12, FontStyle.Regular), SystemBrushes.WindowText, new PointF(30,50));
  // send the image to the users browser
  Response.ContentType = info.MimeType;
  bitmap.Save(Response.OutputStream, info, encoderParams);
  // clean up
  graphics.Dispose();
  bitmap.Dispose();
  Response.End();
}

/// 
/// Gets ImageCodecInfo for JPEG images.
/// 
/// ImageCodecInfo object for encoding JPEG images
private ImageCodecInfo GetEncoderInfo() {
  ImageCodecInfo jpegEncoder = null;
  ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
  foreach (ImageCodecInfo encoder in encoders) {
    if (String.Compare(encoder.MimeType, "image/jpeg", true) == 0) {
      jpegEncoder = encoder;
      break;
    }
  }
  encoders = null;
  return jpegEncoder;
}

or a simpler example creating a gif:

  int width = 700;
  int height = 500;
  Bitmap bitmap = new Bitmap(width, height);
  Graphics g = Graphics.FromImage(bitmap); 
  g.FillRectangle(new SolidBrush(Color.Yellow), 0, 0, width, height);
  g.DrawString("This is a dynamic image:", new Font("Arial", 8), new SolidBrush(Color.Black), new PointF(10,10));
  Response.ContentType = "Image/GIF";
  bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
Preventing page unload with JavaScript 13 August 2004 at 00:00
The onbeforeunload event handler (supported by Internet Explorer 4+ only) can be used to confirm that the user does want to close the browser window or navigate away from the current page. If your event handler returns something, this message will be included in a confirmation which the user must click OK to. If you do not return anything, the event handler is ignored:

  var saved = false;

  window.onbeforeunload = unloadHandler;

  function unloadHandler() {
    msg = "You will lose all data associated with this screen."
    if (saved) return msg;
  }
Determining element position with JavaScript 13 August 2004 at 00:00
To determine the exact location of an element on a page, you need to use the offsetLeft and offsetTop attributes. For example:
function getLeftPos(obj) {
  var left = 0;
  // internet explorer
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      left += obj.offsetLeft
      obj = obj.offsetParent;
    }
  }
  // other browsers
  else if (obj.x) {
    left = obj.x;
  }
  return left;
}

NOTE: this will only work in DOM-enabled browsers.

SQL Server : Retrieving Database and Table Sizes 03 August 2004 at 00:00

Log file sizes

select size as 'pages', size*8000 as 'size', name from sysfiles

For the whole database

sp_spaceused @updateusage = 'TRUE'

For a specific table

sp_spaceused @objname = '<table_name>'
Creating dynamic images with ASP.NET 06 August 2004 at 00:00
Creating dynamic images with ASP.NET is simple using the System.Drawing namespaces:

WebForm1.aspx

<%@ Page language="c#" Codebehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm1" %>

WebForm1.aspx.cs

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
...
private void Page_Load(object sender, System.EventArgs e) {
  Response.Clear();
  int height = 100;
  int width = 200;
  Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format64bppArgb);
  // set up encoding options
  EncoderParameters encoderParams = new EncoderParameters();
  long[] quality = new long[1];
  quality[0] = 90;	// valid values 0 to 100
  EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, quality);
  encoderParams.Param[0] = encoderParam;
  ImageCodecInfo info = this.GetEncoderInfo();
  // get graphics context
  Graphics graphics = Graphics.FromImage(bitmap);
  // set alias and color to fill with
  graphics.SmoothingMode = SmoothingMode.AntiAlias;
  graphics.Clear(Color.RosyBrown);
  // create borders around the image
  graphics.DrawRectangle(Pens.White, 1, 1, width - 3, height - 3);
  graphics.DrawRectangle(Pens.Black, 1, 1, width, height);
  // write some text to the image
  graphics.DrawString("This is a test image!", new Font("Arial", 12, FontStyle.Regular), SystemBrushes.WindowText, new PointF(30,50));
  // send the image to the users browser
  Response.ContentType = info.MimeType;
  bitmap.Save(Response.OutputStream, info, encoderParams);
  // clean up
  graphics.Dispose();
  bitmap.Dispose();
  Response.End();
}

/// <summary>
/// Gets ImageCodecInfo for JPEG images.
/// </summary>
/// <returns>ImageCodecInfo object for encoding JPEG images</returns>
private ImageCodecInfo GetEncoderInfo() {
  ImageCodecInfo jpegEncoder = null;
  ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
  foreach (ImageCodecInfo encoder in encoders) {
    if (String.Compare(encoder.MimeType, "image/jpeg", true) == 0) {
      jpegEncoder = encoder;
      break;
    }
  }
  encoders = null;
  return jpegEncoder;
}

or a simpler example creating a gif:

  int width = 700;
  int height = 500;
  Bitmap bitmap = new Bitmap(width, height);
  Graphics g = Graphics.FromImage(bitmap); 
  g.FillRectangle(new SolidBrush(Color.Yellow), 0, 0, width, height);
  g.DrawString("This is a dynamic image:", new Font("Arial", 8), new SolidBrush(Color.Black), new PointF(10,10));
  Response.ContentType = "Image/GIF";
  bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
JavaScript replaceAll function 13 August 2004 at 00:00
The JavaScript replace() function does not replace all instances of the unwanted string - only the first one encountered. This function replaces all instances of the unwanted string.
/**
 * @param strChk      String to be cleaned
 * @param strFind     String to replace
 * @param strReplace  String to insert
 * @return            String without unwanted characters/strings
 */
function replaceAll(strChk, strFind, strReplace) {
  var strOut = strChk;
  while (strOut.indexOf(strFind) > -1) {
    strOut = strOut.replace(strFind, strReplace);
  }
  return strOut;
}

Alternatively, a cleaner approach is to prototype the string object, effectively adding the replaceAll method to the string class. Using the following approach, you can then use this method as you would any other string method, e.g. yourstring.replaceAll('a', 'b');

String.prototype.replaceAll = function(find, replace) {
  var str = this;
  while (str.indexOf(find) > -1) {
    str = str.replace(find, replace);
  }
  return str;
}