Setting new window location with JavaScript
Created 13 August 2004 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>
A JavaScript Vector object
Created 13 August 2004 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 Regular Expressions
Created 13 August 2004 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 Error Handling
Created 13 August 2004 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
Created 13 August 2004 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
Created 13 August 2004 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
Created 13 August 2004 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
Created 06 August 2004 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
Created 13 August 2004 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;
  }
SQL Server : Retrieving Database and Table Sizes
Created 03 August 2004 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>'