Thursday, August 26, 2004

Replace content in database table (SQL)

You may have rows in your database that contains <br>, which you want to replace with line breaks (this may be the case if you are using Server.HtmlEncode to encode your output, which you didn't previously do). This can simply be done using the replace function (note the line break):

UPDATE [table]
SET
  [column]= REPLACE([column], '<br>', '
')
WHERE
  [column] LIKE '%<br>%'
Also, if you wish to convert < and > to their html encoded equivalents:
UPDATE [table]
SET
  [column]= REPLACE([column], '<', '&lt;')
WHERE
  [column] LIKE '%<%'
UPDATE [table]
SET
  [column]= REPLACE([column], '>', '&gt;')
WHERE
  [column] LIKE '%>%'
Or to do the reverse:
UPDATE [table]
SET
  [column]= REPLACE([column], '&lt;', '<')
WHERE
  [column] LIKE '%&lt;%'
UPDATE [table]
SET
  [column]= REPLACE([column], '&gt;', '>')
WHERE
  [column] LIKE '%&gt;%'
Tested this in the Query Analyzer so not sure if it would work on web pages. To make sure nothing goes wrong (unlikely though), backup your data first.

Friday, August 13, 2004

Popup Window Countdown (JavaScript)

This code opens a new popup window that contains a timer that counts down, then closes the window when it reaches 0. Will not work if user has a popup blocker blocking the page.

<html>
<head>
<title>Popup Timer</title>
<script language="JavaScript" type="text/JavaScript">

// popup window var
var popup;

// At what number shall the countdown counter start?
CounterStart = 10;
 
// This function CustomAction() can be modified to do 
// whatever you want done every second.
 
function CustomAction() {
	popup.document.timer.timeleft.value = CounterStart;
} // end of function CustomAction()

// end of JavaScript customization


function Decrement() {
	CounterStart--;
	CustomAction();
	if(CounterStart <= 0) { popup.close(); alert('Timer reached 0'); }
	else { setTimeout('Decrement()',1000); }
}
 
function StartTheCounter() {
	openPopup(120,100);
	setTimeout('Decrement()',1000);
}

function openPopup(w,h){
	// new window title
	var contents = '<html><head><title>Counter Window<\/title>';
	// resize window once image has loaded
	contents += '<script type="text\/javascript">window.onload = init;';
	// centre the popup window
	contents += 'function init() {window.moveTo((screen.width-'+w+')/2,(screen.height-'+h+')/2)}';
	contents += '<\/script>';
	contents += '<\/head><body>';
	contents += '<form name="timer">'
	contents += '<input name="timeleft" type="text" size="4" readonly="" value="'+CounterStart+'" /> seconds!';
	contents += '</form>';
	contents += '<\/body><\/html>';
	// open popup window
	popup = window.open('about:blank','popup','location=no,menubar=no,scrollbars=no,status=no,toolbar=no,width='+w+',height='+h);
	popup.document.open();
	popup.document.write(contents);
	popup.document.close();
}
// -->
</script>
</head>
<body onload="StartTheCounter();">
Popup Window Timer
</body>
</html>

Wednesday, August 11, 2004

Prevent User Control Code from running (ASP.NET)

You can prevent code within a user control (ascx file) from running if it is invisible on the containing page. To do so, just check base.Visible (C#) or MyBase.Visible (VB). For example:

C#

private void Page_Load(object sender, EventArgs e)
{
	if (base.Visible) {
		// run code
	}
}

VB

Private Sub Page_Load(sender As Object, e As EventArgs)
	If MyBase.Visible Then
		' run code
	End If
End Sub

Tuesday, August 10, 2004

Recursive File List Control (ASP.NET)

This control lists files and folders within a given directory. It shows only the root directories and files, but if you click a folder in the list, your get the sub folders and files.

Control code (filelist.ascx)

<%@ Control Language="C#" %>
<%@ Import Namespace="System.Collections" %>
<script runat="server">

private void Page_Load(object sender, EventArgs e)
{
	// add file types
	fileTypes.Add("doc");
	fileTypes.Add("rtf");
	fileTypes.Add("xls");
	fileTypes.Add("pdf");
	walkFolders(VirtualFolder);
	lnkReset.NavigateUrl = Url;
}
public string VirtualFolder = "/";
private ArrayList fileTypes = new ArrayList();
private ArrayList folders;
private ArrayList Folders {
	get {
		if (folders==null) {
			if (PathInfo!=null) {
				folders = new ArrayList(PathInfo.Split(';'));
			} else {
				folders = new ArrayList();
			}
		}
		return folders;
	}
	set {
		folders = value;
	}
}
private string Url {
	get {
		return HttpContext.Current.Request.Path;
	}
}

private string PathInfo
{
	get {
		return HttpContext.Current.Request.QueryString["show"];
	}
}
private string BuildQuery
{
	get {
		string strList = string.Empty;
		for(int i=0; i<Folders.Count; i++)
		{
			strList += Server.UrlEncode(Folders[i].ToString()) + ";";
		}
		if (strList!=string.Empty) {
			strList = "?show=" + strList.Substring(0, strList.LastIndexOf(';'));
		}
		return strList;
	}
}
private bool InQuery(string s)
{
	for(int i=0; i<Folders.Count; i++)
	{
		if(Folders[i].ToString() == s) {
			return true;
		}
	}
	return false;
}
private bool AllowedFileType(string fileExt)
{
	for(int i=0; i<fileTypes.Count; i++)
	{
		if(fileTypes[i].ToString() == fileExt.ToLower()) {
			return true;
		}
	}
	return false;
}
// based on code from http://groups.google.com/groups?selm=uUvzKryuDHA.540%40tk2msftngp13.phx.gbl&rnum=3
private void walkFolders(string rootPath)
{
	// Open the list
	FileList.Text += "<ul>";
	string mappedRoot = Server.MapPath(rootPath);
	try {
		// Iterate through each folder
		foreach (string folder in System.IO.Directory.GetDirectories(mappedRoot))
		{
			string virtfolder = folder.Replace(mappedRoot, string.Empty);
			string subFolder = rootPath + virtfolder + "/";
			string strList = string.Empty;
			if (InQuery(subFolder)) {
				Folders.Remove(subFolder);
				strList = BuildQuery;
				Folders.Add(subFolder);
			} else {
				Folders.Add(subFolder);
				strList = BuildQuery;
				Folders.Remove(subFolder);
			}
			string b = "<li> Folder: <a href=\"" + Url + strList + "\">" + Server.HtmlEncode(virtfolder) + "</a>";
			FileList.Text += b;
			if (InQuery(subFolder)) {
				// Walk through this folder
				FileList.Text += Environment.NewLine;
				walkFolders(subFolder);
			}
			FileList.Text += "</li>" + Environment.NewLine;
		}	
	} catch (System.Exception ex) {
		Trace.Write(ex.Source + " : " + ex.HelpLink + " : " + ex.Message);
	}
	try {
		// Iterate through the files in this folder
		foreach (string file in System.IO.Directory.GetFiles(mappedRoot))
		{
			string fileName = file.Replace(mappedRoot, string.Empty);
			if (!AllowedFileType(getExt(fileName))) continue;
			// Remove path and prefix with LI
			string b = "<li> File: " + "<a href=\"" + rootPath + fileName + "\">" + Server.HtmlEncode(removeExt(fileName)) + "</a></li>";
			// Put the fileName in the textbox
			FileList.Text += b + Environment.NewLine;
		}
	} catch (System.Exception ex) {
		Trace.Write(ex.Source + " : " + ex.HelpLink + " : " + ex.Message);
	}
	// Close the list
	FileList.Text += "</ul>" + Environment.NewLine;
}

private string removeExt(string fileName)
{
	return fileName.Substring(0,fileName.LastIndexOf('.'));
}

private string getExt(string fileName)
{
	int dot = fileName.LastIndexOf('.') + 1;
	return fileName.Substring(dot, fileName.Length - dot);
}
</script>
<asp:HyperLink id="lnkReset" runat="server" Text="Reset List" />
<asp:Literal EnableViewState="False" runat="server" id="FileList" />

Page code (filelist.aspx)

<%@ Page Language="C#" Trace="False" ContentType="text/html" ResponseEncoding="iso-8859-1" %>
<%@ Register TagPrefix="Files" TagName="List" Src="filelist.ascx" %>
<html>
<head>
<title>File listing</title>
</head>
<body>
<form runat="server">
	<Files:List runat="server" VirtualFolder="/virtualdir/" />
</form>
</body>
</html>

Wednesday, August 04, 2004

Internet Explorer Toolbar Fix

When Internet Explorer has several toolbars installed, the context menu items do not reflect the correct toolbar - i.e. Google and Yahoo toolbars are both showing and you wish to hide the Google one. So you click 'Google' in the menu - but the Yahoo one disappears instead. This bug has been around for a long time. However, it can be fixed by tweaking the registry (found at http://www.mvps.org/winhelp2002/ietips.htm#Odd). Here is the fix (create blank text file called ResetBrowserToolbar.reg, and then double-click the newly created file)

REGEDIT4

[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Toolbar\WebBrowser]
"ITBarLayout"=-