Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Will Rickards http://willrickards.net/

« Newer Snippets
Older Snippets »
Showing 1-10 of 18 total  RSS 

Programmatically Change a Crystal Reports datasource location

I had an aspx.net project where I needed to generate a pdf.
I used crystal to do the heavy lifting of geneating the pdf for me.
But as I needed to deploy it to multiple databases/clients I needed a way of programmatically changing the datasource location of the report. So with a bit of help from the crystal knowledgebase here is the code I use.
There is a lot of debugging information in here and trust me when it fails you need it.
The .dbo of the location reference obviously means I was working with sql server.

   ' --------------------------------------------------------------------------
   ' SetupReport
   '
   ' Description:
   '    sets up the crystal report
   '
   ' Arguments:
   '    objCrystalReportDocument             - crystal report document object
   '
   ' Dependencies:
   '    GetConnnectionInfo
   '    CrystalDescisions
   '
   ' History:
   ' 03/17/2006 - WSR : created
   '
   Private Function SetupReport(ByRef objCrystalReportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument) As System.Boolean

      ' a heck of a lot of objects used
      Dim crParameterDiscreteValue As CrystalDecisions.Shared.ParameterDiscreteValue
      Dim crParameterFieldDefinitions As CrystalDecisions.CrystalReports.Engine.ParameterFieldDefinitions
      Dim crParameterFieldLocation As CrystalDecisions.CrystalReports.Engine.ParameterFieldDefinition
      Dim crParameterValues As CrystalDecisions.Shared.ParameterValues
      Dim crSections As CrystalDecisions.CrystalReports.Engine.Sections
      Dim crSection As CrystalDecisions.CrystalReports.Engine.Section
      Dim crReportObjects As CrystalDecisions.CrystalReports.Engine.ReportObjects
      Dim crReportObject As CrystalDecisions.CrystalReports.Engine.ReportObject
      Dim crSubreportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument
      Dim crSubreportObject As CrystalDecisions.CrystalReports.Engine.SubreportObject
      Dim crConnectionInfo As CrystalDecisions.Shared.ConnectionInfo
      Dim crDatabase As CrystalDecisions.CrystalReports.Engine.Database
      Dim crTables As CrystalDecisions.CrystalReports.Engine.Tables
      Dim aTable As CrystalDecisions.CrystalReports.Engine.Table
      Dim bTable As CrystalDecisions.CrystalReports.Engine.Table
      Dim crTableLogOnInfo As CrystalDecisions.Shared.TableLogOnInfo
      Dim blnTest As System.Boolean
      Dim strLocation As System.String
      Dim blnErrors As System.Boolean

      ' instantiate the debug page
      m_strDebugPage = New System.Text.StringBuilder(4096)
      blnErrors = False

      crConnectionInfo = GetConnectionInfo()

      crDatabase = objCrystalReportDocument.Database

      crTables = crDatabase.Tables

      'For intCounter = 0 To objCrystalReportDocument.Database.Tables.Count - 1
      For Each aTable In crTables

         crTableLogOnInfo = aTable.LogOnInfo

         OutputDebugLine("BEFORE")
         OutputDebugLine("TABLE NAME: " & aTable.Name)
         OutputDebugLine("TABLE LOC: " & aTable.Location)
         OutputDebugLine("SERVER: " & crTableLogOnInfo.ConnectionInfo.ServerName)
         OutputDebugLine("DB: " & crTableLogOnInfo.ConnectionInfo.DatabaseName)
         OutputDebugLine("UID: " & crTableLogOnInfo.ConnectionInfo.UserID)
         OutputDebugLine("PWD: " & crTableLogOnInfo.ConnectionInfo.Password)
         OutputDebugLine("RN: " & crTableLogOnInfo.ReportName)
         OutputDebugLine("TN: " & crTableLogOnInfo.TableName)

         crTableLogOnInfo.ConnectionInfo = crConnectionInfo
         aTable.ApplyLogOnInfo(crTableLogOnInfo)
         strLocation = crConnectionInfo.DatabaseName & ".dbo." & aTable.Location.Substring(aTable.Location.LastIndexOf(".") + 1)
         OutputDebugLine("New Location: " & strLocation)
         Try
            aTable.Location = strLocation
         Catch ex As Exception
            OutputDebugLine("Set Location Error: " & ex.ToString)
            blnErrors = True
         End Try

         OutputDebugLine("AFTER")
         OutputDebugLine("TABLE NAME: " & aTable.Name)
         OutputDebugLine("TABLE LOC: " & aTable.Location)
         OutputDebugLine("SERVER: " & crTableLogOnInfo.ConnectionInfo.ServerName)
         OutputDebugLine("DB: " & crTableLogOnInfo.ConnectionInfo.DatabaseName)
         OutputDebugLine("UID: " & crTableLogOnInfo.ConnectionInfo.UserID)
         OutputDebugLine("PWD: " & crTableLogOnInfo.ConnectionInfo.Password)
         OutputDebugLine("RN: " & crTableLogOnInfo.ReportName)
         OutputDebugLine("TN: " & crTableLogOnInfo.TableName)
         Try
            blnTest = aTable.TestConnectivity()
            OutputDebugLine("CONNECTED? " & blnTest.ToString())
         Catch ex As Exception
            OutputDebugLine("CONNECTED? NO")
            OutputDebugLine(ex.ToString)
            blnErrors = True
         End Try

         '// THIS STUFF HERE IS FOR REPORTS HAVING SUBREPORTS 
         '// set the sections object to the current report's section 
         crSections = objCrystalReportDocument.ReportDefinition.Sections

         '// loop through all the sections to find all the report objects 
         For Each crSection In crSections

            crReportObjects = crSection.ReportObjects

            '//loop through all the report objects in there to find all subreports 
            For Each crReportObject In crReportObjects

               If crReportObject.Kind = ReportObjectKind.SubreportObject Then

                  crSubreportObject = CType(crReportObject, CrystalDecisions.CrystalReports.Engine.SubreportObject)
                  '//open the subreport object and logon as for the general report 
                  crSubreportDocument = crSubreportObject.OpenSubreport(crSubreportObject.SubreportName)
                  crDatabase = crSubreportDocument.Database
                  crTables = crDatabase.Tables

                  For Each bTable In crTables

                     crTableLogOnInfo = bTable.LogOnInfo

                     OutputDebugLine("BEFORE")
                     OutputDebugLine("TABLE NAME: " & bTable.Name)
                     OutputDebugLine("TABLE LOC: " & bTable.Location)
                     OutputDebugLine("SERVER: " & crTableLogOnInfo.ConnectionInfo.ServerName)
                     OutputDebugLine("DB: " & crTableLogOnInfo.ConnectionInfo.DatabaseName)
                     OutputDebugLine("UID: " & crTableLogOnInfo.ConnectionInfo.UserID)
                     OutputDebugLine("PWD: " & crTableLogOnInfo.ConnectionInfo.Password)
                     OutputDebugLine("RN: " & crTableLogOnInfo.ReportName)
                     OutputDebugLine("TN: " & crTableLogOnInfo.TableName)

                     crTableLogOnInfo.ConnectionInfo = crConnectionInfo
                     bTable.ApplyLogOnInfo(crTableLogOnInfo)
                     strLocation = crConnectionInfo.DatabaseName & ".dbo." & bTable.Location.Substring(bTable.Location.LastIndexOf(".") + 1)
                     OutputDebugLine("New Location: " & strLocation)
                     Try
                        bTable.Location = strLocation
                     Catch ex As Exception
                        OutputDebugLine("Set Location Error: " & ex.ToString)
                        blnErrors = True
                     End Try

                     OutputDebugLine("AFTER")
                     OutputDebugLine("TABLE NAME: " & bTable.Name)
                     OutputDebugLine("TABLE LOC: " & bTable.Location)
                     OutputDebugLine("SERVER: " & crTableLogOnInfo.ConnectionInfo.ServerName)
                     OutputDebugLine("DB: " & crTableLogOnInfo.ConnectionInfo.DatabaseName)
                     OutputDebugLine("UID: " & crTableLogOnInfo.ConnectionInfo.UserID)
                     OutputDebugLine("PWD: " & crTableLogOnInfo.ConnectionInfo.Password)
                     OutputDebugLine("RN: " & crTableLogOnInfo.ReportName)
                     OutputDebugLine("TN: " & crTableLogOnInfo.TableName)
                     Try
                        blnTest = bTable.TestConnectivity()
                        OutputDebugLine("CONNECTED? " & blnTest.ToString())
                     Catch ex As Exception
                        OutputDebugLine("CONNECTED? NO")
                        OutputDebugLine(ex.ToString)
                        blnErrors = True
                     End Try

                  Next bTable

               End If

            Next crReportObject

         Next crSection

      Next aTable

      ' get parameter fields from report
      crParameterFieldDefinitions = objCrystalReportDocument.DataDefinition.ParameterFields

      '    ' Set the first parameter
      '    ' - Get the parameter, tell it to use the current values vs default value.
      '    ' - Tell it the parameter contains 1 discrete value vs multiple values.
      '    ' - Set the parameter's value.
      '    ' - Add it and apply it.
      '    ' - Repeat these statements for each parameter.
      '    '
      crParameterFieldLocation = crParameterFieldDefinitions.Item("@psindex")
      crParameterValues = crParameterFieldLocation.CurrentValues
      crParameterDiscreteValue = New CrystalDecisions.Shared.ParameterDiscreteValue
      crParameterDiscreteValue.Value = m_intReportID
      crParameterValues.Add(crParameterDiscreteValue)
      crParameterFieldLocation.ApplyCurrentValues(crParameterValues)

      ' if there were errors
      If blnErrors Then

         ' display debug page
         OutputDebugPage()

      End If

   End Function
   ' --------------------------------------------------------------------------


   ' --------------------------------------------------------------------------
   ' GetConnectionInfo
   '
   ' Description:
   '    retrieves the connection information from the data layer object
   '
   ' Arguments: none
   '
   ' Dependencies:
   '    DataLayer.GetConnectInfo
   '
   ' History:
   ' 03/17/2006 - WSR : created
   '
   Private Function GetConnectionInfo() As CrystalDecisions.Shared.ConnectionInfo

      Dim objConnectionInfo As CrystalDecisions.Shared.ConnectionInfo
      Dim strDSN As System.String
      Dim strDB As System.String
      Dim strUID As System.String
      Dim strPWD As System.String
      Dim blnTrust As System.Boolean

      ' get connection information from data layer
      m_objDataLayer.GetConnectInfo(strDSN, strDB, strUID, strPWD, blnTrust)

      ' create new crystal connection info object
      objConnectionInfo = New CrystalDecisions.Shared.ConnectionInfo

      ' populate it
      objConnectionInfo.IntegratedSecurity = False
      objConnectionInfo.ServerName = strDSN
      objConnectionInfo.UserID = strUID
      objConnectionInfo.Password = strPWD
      objConnectionInfo.DatabaseName = strDB

      ' return object
      GetConnectionInfo = objConnectionInfo

   End Function
   ' --------------------------------------------------------------------------

   ' --------------------------------------------------------------------------
   ' OutputDebugLine
   '
   ' Description: appends a line to the debug string builder
   '
   ' Arguments: text to add
   '
   ' Dependencies:
   '    m_strDebugPage
   '
   ' History:
   ' 03/17/2006 - WSR : created
   ' 2007.04.25 - WSR : revised to use string builder
   '
   Function OutputDebugLine(ByVal strLine As System.String) As System.Boolean

      m_strDebugPage.Append("<div>" & Server.HtmlEncode(strLine) & "</div>")

   End Function
   ' --------------------------------------------------------------------------


   ' --------------------------------------------------------------------------
   ' OutputDebugPage
   '
   ' Description: sends debug string builder to response
   '
   ' Arguments: none
   '
   ' Dependencies:
   '    m_strDebugPage
   '
   ' History:
   ' 2007.04.25 - WSR : created
   '
   Function OutputDebugPage() As System.Boolean

      With Response
         .ClearHeaders()
         .ClearContent()
         .ContentType = "text/html"
      End With

      Response.Write("<html><head><title>Debug Page</title></head><body>")
      Response.Write(m_strDebugPage.ToString())
      Response.Write("</body></html>")

      Response.Flush()
      Response.End()

   End Function
   ' --------------------------------------------------------------------------


ASP.Net Serve File For Download

Function I use to serve a file on the webserver to the client machine.

   ' sends file to browser for download
   Private Sub SendFile(ByVal strPath As System.String, ByVal strSuggestedName As System.String)

      Dim strServerPath As String
      Dim objSourceFileInfo As System.IO.FileInfo

      ' convert relative path to path on server machine
      strServerPath = Me.Server.MapPath(strPath)

      ' get fileinfo of source file
      objSourceFileInfo = New System.IO.FileInfo(strServerPath)

      ' if the file exists
      If objSourceFileInfo.Exists Then

         With Me.Response

            ' tell the browser what content type to expect
            .ContentType = "application/octet-stream"
 
            ' tell the browser to save rather than display inline
            .AddHeader("Content-Disposition", "attachment; filename=" & strSuggestedName)

            ' tell the browser how big the file is
            .AddHeader("Content-Length", objSourceFileInfo.Length.ToString)

            ' send the file to the browser
            .WriteFile(objSourceFileInfo.FullName)

            ' make sure response is sent
            .Flush()

            ' end response
            .End()

         End With

      ' if the file does not exist
      Else

         ' show error page
         ThrowError("Application Error", "File Missing From Server")

      End If

   End Sub        

Javascript Manipulate Class Names

I often have to manipulate class names of objects in javascript.
But className can have multiple classes in it.
These functions deal with that.

// ----------------------------------------------------------------------------
// HasClassName
//
// Description : returns boolean indicating whether the object has the class name
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function HasClassName(objElement, strClass)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ )
         {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // we found it
            return true;

            }

         }

      }

   // if we got here then the class name is not there
   return false;

   }
// 
// HasClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// AddClassName
//
// Description : adds a class to the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function AddClassName(objElement, strClass, blnMayAlreadyExist)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // if the new class name may already exist in list
      if ( blnMayAlreadyExist )
         {

         // get uppercase class for comparison purposes
         var strClassUpper = strClass.toUpperCase();

         // find all instances and remove them
         for ( var i = 0; i < arrList.length; i++ )
            {

            // if class found
            if ( arrList[i].toUpperCase() == strClassUpper )
               {

               // remove array item
               arrList.splice(i, 1);

               // decrement loop counter as we have adjusted the array's contents
               i--;

               }

            }

         }

      // add the new class to end of list
      arrList[arrList.length] = strClass;

      // add the new class to beginning of list
      //arrList.splice(0, 0, strClass);
      
      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   else
      {

      // assign modified class name attribute      
      objElement.className = strClass;
   
      }

   }
// 
// AddClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// RemoveClassName
//
// Description : removes a class from the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to remove
//
function RemoveClassName(objElement, strClass)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ )
         {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // remove array item
            arrList.splice(i, 1);

            // decrement loop counter as we have adjusted the array's contents
            i--;

            }

         }

      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   // there is nothing to remove

   }
// 
// RemoveClassName
// ----------------------------------------------------------------------------
  

Javascript QuickSelect (Coordinated Textbox And ListBox)

In HTML, say you have a select element with all the states.
Unfortunately typing in this select box only works with the first letter.
So if you type P then A you don't select pennsylvania.
What I commonly do in this situation is to have what I call a quickselect textbox on the page as well.
This is a textbox and listbox that are coordinated.

// in your onload event handler you need this

// hookup event handlers and control references
var objElement = document.getElementById('cboState');
if ( objElement )
   {
   objElement.onchange = QuickSelect_Change;
   objElement.textbox = document.getElementById('txtState');
   if ( objElement.textbox )
      {
      objElement.textbox.onchange = QuickSelect_TextChange;
      objElement.textbox.onblur = QuickSelect_TextChange;
      objElement.textbox.onkeypress = QuickSelect_KeyPress;
      objElement.textbox.listbox = objElement;
      }
   }       

// and now the functions

// ----------------------------------------------------------------------------
// QuickSelect_KeyPress
//
// Description : event handler for quick select textbox's key press event
//    selects the appropriate item in the associated listbox control
//
// Arguments : none
//
// Dependencies : 
//
// History :
// 2006.09.20 - WSR : created
//
function QuickSelect_KeyPress( e )
   {


   var strCompare = '';
   var numEntryLen;
   var strEntry;
   var objSelect = this.listbox;
   var numOptions = objSelect.options.length;

   var numCharCode;
   var elTarget;

   // get event if not passed
   if (!e) var e = window.event;

   // get character code of key pressed
   if (e.keyCode) numCharCode = e.keyCode;
   else if (e.which) numCharCode = e.which;

   // get target
   if (e.target) elTarget = e.target;
   else if (e.srcElement) elTarget = e.srcElement;
                                              
   // if form input field & it is a printable character
   if ( elTarget.nodeName.toUpperCase() == 'INPUT' && numCharCode >= 32 && numCharCode <= 126 )
      {

      strEntry = this.value + String.fromCharCode(numCharCode);
      numEntryLen = strEntry.length;

      // cycle through options
      for (var i = 0; i < numOptions; i++)
         {

         // get compare string from value same length as entered string
         strCompare = objSelect.options[i].value.substring(0, numEntryLen);

         // if value matches what is entered
         if (strEntry == strCompare)
            {

            // select this option
            objSelect.options[i].selected = true;

            // end loop
            break;

            }

         }

      // I usually add an error class when input is required and not filled in
      // this removes the class so the input is no longer marked as invalid
      // commented out as it isn't necessary for general purpose
      // RemoveClassName( this, 'error' );

      }

   }
//
// QuickSelect_KeyPress
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// QuickSelect_TextChange
//
// Description : event handler for quick select textbox's change & onblur events
//    makes sure item in textbox is a value from list
//
// Arguments : none
//
// Dependencies : none
//
// History :
// 2006.08.09 - WSR : created
//
function QuickSelect_TextChange()
   {

   var strCompare = '';
   var numEntryLen = this.value.length;
   var strEntry = this.value;
   var objSelect = this.listbox;
   var numOptions = objSelect.options.length;

   // cycle through options
   for (var i = 0; i < numOptions; i++)
      {

      // get compare string from value same length as entered string
      strCompare = objSelect.options[i].value.substring(0, numEntryLen);

      // if value matches what is entered
      if (strEntry == strCompare)
         {

         // select this option
         objSelect.options[i].selected = true;

         // end loop
         break;

         }

      }

   // copy code to textbox
   this.value = this.listbox.options[this.listbox.selectedIndex].value;

   // I usually add an error class when input is required and not filled in
   // this removes the class so the input is no longer marked as invalid
   // commented out as it isn't necessary for general purpose
   // RemoveClassName( this, 'error' );

   }
//
// QuickSelect_TextChange
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// QuickSelect_Change
//
// Description : event handler for quick select list box's change event
//    updates the textbox with the selected value
//
// Arguments: none
//
// Dependencies :
//
// History :
// 2006.08.09 - WSR : created
//
function QuickSelect_Change()
   {

   // copy code to textbox
   this.textbox.value = this.options[this.selectedIndex].value;

   }	
//
// QuickSelect_Change
// ----------------------------------------------------------------------------
  


Javascript LookupControl

A lookup control is a common thing to have on many web pages. In this case we assume a textbox, a command button, and a label of some sort to display a description.

The HTML might look like this
<label for="txtExistingClient">Client</label>
<input id="txtExistingClient" name="txtExistingClient" type="text" size="15" maxlength="14" class="text uppercase" runat="server">
<input id="cmdExistingClientLookup" name="cmdExistingClientLookup" type="button" value=" ? ">
<span id="lblExistingClient"></span>


Here is a javascript function to call in the onload to setup that lookup control. And examples of the functions required.
// ----------------------------------------------------------------------------
// SetupLookupControl
//
// Description : sets up a lookup control by linking it to its 
//    associated controls and hooking up the event handlers
//
// Arguments :
//    strTextBoxID               : input type=text id
//    strLookupButtonID          : input type=button id
//    strLabelID                 : span of div id
//    funcTextBoxOnChange        : function for textbox's onchange and onblur event
//    funcLookupButtonOnClick    : function for lookup button's onclick event
//
// Dependencies : none
//
// History :
// 2006.07.14 - WSR : created
//
function SetupLookupControl( strTextBoxID, strLookupButtonID, strLabelID, funcTextBoxOnChange, funcLookupButtonOnClick )
   {

   // get reference to lookup button
   var ctlLookupButton = document.getElementById(strLookupButtonID);

   // if lookup button was found
   if (ctlLookupButton)
      {

      // hookup event handlers and control references
      ctlLookupButton.onclick = funcLookupButtonOnClick;
      ctlLookupButton.textbox = document.getElementById(strTextBoxID);

      // if textbox was found
      if (ctlLookupButton.textbox)
         {

         // hookup event handlers and control references
         ctlLookupButton.textbox.onchange = funcTextBoxOnChange;
         ctlLookupButton.textbox.onblur = funcTextBoxOnChange;
         ctlLookupButton.textbox.label = document.getElementById(strLabelID);

         // init last value property of textbox
         if ( typeof ctlLookupButton.textbox.lastvalue == 'undefined' )
            ctlLookupButton.textbox.lastvalue = ''; 

         }

      }

   }
//
// SetupLookupControl
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// cmdTimekeeperLookup_click
// Description: handler for requesting timekeeper selection button click event
// Arguments: none
// Dependencies:
//    TimekeepQuery (lookup.js)
//
function cmdTimekeeperLookup_click()
   {

   // show timekeeper query window
   TimekeepQuery( this.textbox );

   // update timekeeper information
   this.textbox.onchange();

   // process default action
   return true;

   }
//
// cmdTimekeeperLookup_click
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// txtTimekeeper_change
// Description: event handler for timekeeper textbox change event
// Arguments: none
// Dependencies:
//    window.strTkprMask (masking.js)
//    trim
//    ApplyMask (masking.js)
//    TimekeepLookup (lookup.js)
//    UpdateElementText (shared.js)
//
function txtTimekeeper_change()
   {

   var strTimekeepName = '';
   var objXMLDOM;
   var nodField;
 
   // trim input
   this.value = this.value.trim();
  
   // if there was input
   if ( this.value.length > 0 )
      {

      // apply timekeep mask to textbox input
      ApplyMask( this, window.strTkprMask );

      // if inputted timekeeper is different from current timekeeper
      if ( this.lastvalue != this.value )
         {

         // request timekeeper information
         objXMLDOM = TimekeepLookup( this.value );

         // if XML DOM object returned
         if ( typeof objXMLDOM == 'object' )
            {

            // get field values
            nodField = objXMLDOM.selectSingleNode('//lastname');
            if (nodField != null)
               strTimekeepName = nodField.firstChild.nodeValue;

            nodField = objXMLDOM.selectSingleNode('//firstname');
            if (nodField != null)
               strTimekeepName = strTimekeepName + ', ' + nodField.firstChild.nodeValue;

            // update timekeeper
            this.lastvalue = this.value;

            }
         // if XML DOM object wasn't returned
         else
            {

            // indicate timekeeper was not found
            strTimekeepName = 'Timekeep \'' + this.value + '\' was not found.';

            // update timekeeper
            this.lastvalue = '';

            }

         // update document
         UpdateElementText( this.label, strTimekeepName );

         }

      }
   // if there was no input
   else
      {

      // clear the timekeep and display
      this.lastvalue = '';
      UpdateElementText( this.label, '' );

      }

   // process default action
   return true;

   }
//
// txtTimekeeper_change
// ----------------------------------------------------------------------------

Javascript: Preventing Form Submit When Enter is Pressed

In a web page, normally pressing enter when any form element has focus will submit the form. This is often premature. When you have a checkbox selected you probably just want to check the checkbox, not submit the form. So I wrote some javascript to translate the enter into a tab when possible (IE) and prevent the form submit when translation isn't possible (non-IE).

First is the code in your onload event handler.
This sets up onkeydown if window.event is supported (IE) and onkeypress if not.
var frmRequest = document.getElementById('frmRequest');
if (frmRequest)
   {
   if (window.event)
      frmRequest.onkeydown = frmRequest_KeyDown;
   else
      frmRequest.onkeypress = frmRequest_KeyPress;
   }


Next are the actual event handlers.
Nothing really special here, just dealing with the different ways of accessing event properties.
// ----------------------------------------------------------------------------
// frmRequest_KeyDown
//
// Description: event handler for request form key down event
//    translates returns on option buttons to a tab
//    this works only for IE, the keypress event is used for other browsers
//
// Arguments : 
//    e - the event object
//
// Dependencies : none
//
// History :
// 2006.07.13 - WSR : adapted to this project
//
function frmRequest_KeyDown( e )
   {

   var numCharCode;
   var elTarget;
   var strType;

   // get event if not passed
   if (!e) var e = window.event;

   // get character code of key pressed
   if (e.keyCode) numCharCode = e.keyCode;
   else if (e.which) numCharCode = e.which;

   // get target
   if (e.target) elTarget = e.target;
   else if (e.srcElement) elTarget = e.srcElement;
                                              
   // if form input field
   if ( elTarget.tagName.toLowerCase() == 'input' )
      {

      // get type
      strType = elTarget.getAttribute('type').toLowerCase();

      // based on type
      switch ( strType )
         {
         case 'checkbox' :
         case 'radio' :
         case 'text' :

            // if this is a return - change to tab
            if ( numCharCode == 13 )
               {
               if (e.keyCode) e.keyCode = 9;
               else if (e.which) e.which = 9;
               }

            break;
            
         }

      }

   // process default action
   return true;

   }
//
// frmRequest_KeyDown
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// frmRequest_KeyPress
//
// Description: event handler for request form key press event
//    cancels returns on form elements that would prematurely submit the form
//
// Arguments : 
//    e - the event object
//
// Dependencies : none
//
// History :
// 2006.07.13 - WSR : adapted to this project
//
function frmRequest_KeyPress( e )
   {

   var numCharCode;
   var elTarget;
   var strType;

   // get event if not passed
   if (!e) var e = window.event;

   // get character code of key pressed
   if (e.keyCode) numCharCode = e.keyCode;
   else if (e.which) numCharCode = e.which;

   // get target
   if (e.target) elTarget = e.target;
   else if (e.srcElement) elTarget = e.srcElement;
                                              
   // if form input field
   if ( elTarget.tagName.toLowerCase() == 'input' )
      {

      // get type
      strType = elTarget.getAttribute('type').toLowerCase();

      // based on type
      switch ( strType )
         {
         case 'checkbox' :
         case 'radio' :
         case 'text' :

            // if this is a return
            if ( numCharCode == 13 )
               {
               // cancel event to prevent form submission
               return false;
               }

            break;
            
         }

      }

   // process default action
   return true;

   }
//
// frmRequest_KeyPress
// ----------------------------------------------------------------------------

Output DataSet as XML

I was having problems with my ajax lookups when the database fields returned weird characters like the copyright symbol. The responseXML would be blank. After many searches I found you need to output in utf-8 and add an xml declaration to the output that says it is utf-8. Here is the code below in vb.net for asp.net v1.1

   Private Sub OutputDataSetAsXML(ByRef dsSource As System.Data.DataSet)

      Dim xmlDoc As System.Xml.XmlDataDocument
      Dim xmlDec As System.Xml.XmlDeclaration
      Dim xmlWriter As System.Xml.XmlWriter

      ' setup response
      Me.Response.Clear()
      Me.Response.ContentType = "text/xml"
      Me.Response.Charset = "utf-8"
      xmlWriter = New System.Xml.XmlTextWriter(Me.Response.OutputStream, System.Text.Encoding.UTF8)

      ' create xml data document with xml declaration
      xmlDoc = New System.Xml.XmlDataDocument(dsSource)
      xmlDoc.DataSet.EnforceConstraints = False
      xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", Nothing)
      xmlDoc.PrependChild(xmlDec)

      ' write xml document to response
      xmlDoc.WriteTo(xmlWriter)
      xmlWriter.Flush()
      xmlWriter.Close()
      Response.End()

   End Sub 

javascript image swap using DOM

Here is a javascript image swap that uses the DOM methods.
It uses them to support swapping images with different sizes.
Just changing the src property causes the swapped images to be distorted in IE.
This script uses replaceChild instead.

var blnDOMSUPPORT = (document.getElementById) ? true : false;
window.onload = window_load;

function window_load()
   {

   if ( blnDOMSUPPORT )
      {

      document.getElementById('icon1').onclick = swapimage;
      document.getElementById('icon2').onclick = swapimage;
      document.getElementById('icon3').onclick = swapimage;
      
      }
   else
      {

      document.images['icon1'].onclick = swapimage;
      document.images['icon2'].