Sunday, June 27, 2004

JavaScript: Open Image Links in Popup

The following script makes all links to images open in a popup window. No inline JavaScript required. Modern browser required (i.e. IE5+, NS 6+, Mozilla Firefox). Save into scripts directory and include on page by adding into page <head> tags:

example.html

<html>
<head>
<title>Popup Image Example</title>
<script type="text/javascript" src="scripts/imagepop.js"></script>
</head>
<body>
<p><a href="images/foo.gif" title="Foo Title" width="120" height="300">Foo</a>
| <a href="images/bar.jpg" width="140" height="280">Bar</a>
| <a href="page.html">Baz</a></p>
</body>
</html>

scripts/imagepop.js

function imagepop(url,title) {
	// new window title
	var contents = '<html><head><title>' + ((title)?title:'Image Popup') + '<\/title>';
	// resize window once image has loaded
	contents += '<script type="text\/javascript">window.onload = resize;';
	contents += 'function resize() {';
	contents += 'w=document.images[0].width+25;';
	contents += 'h=document.images[0].height+25;';
	contents += 'window.resizeTo(w,h);';
	// centre the popup window
	contents += 'window.moveTo((screen.width-w)/2,(screen.height-h)/2)}';
	contents += '<\/script>';
	// remove padding and margin using css
	contents += '<style type="text\/css">body{margin:0;padding:0;text-align:center}img{display:block;margin:auto}<\/style>';
	// add image to page
	contents += '<\/head><body><img src="' + url + '">';
	contents += '<\/body><\/html>';
	// open popup window
	imgpop = window.open('about:blank','imgpop','location=no,menubar=no,scrollbars=no,status=no,toolbar=no');
	imgpop.document.open();
	imgpop.document.write(contents);
	imgpop.document.close();
	return false;
}
function checklinks() {
	if(document.getElementsByTagName) {
		// list of image types that are recognised as images
		types = new Array('.jpg','jpeg','.gif','.png','.bmp');
		// get anchor links
		a = document.getElementsByTagName('a');
		// loop through list of anchors
		for (var i=0;i<a.length;i++) {
			// loop through image types
			for (var j=0;j<types.length;j++) {
				/* make sure it links to an image by checking where the extension appears in the string
				   Example 1 (image): http://localhost/image.jpg
				   length of href string is 26, index of .jpg is 22
				   so 26 - 22 = 4 (same length as '.jpg') so linking to an image
				   Example 2 (not image): http://localhost/image.jpg/folder/
				   length of href string is 34, index of .jpg is 22
				   so 34 - 22 = 12 (not the same length as '.jpg') so leave alone
				*/
				if ((a[i].href.length - a[i].href.indexOf(types[j])) == types[j].length){
					// attach onclick event to call the function to open a popup window
					a[i].onclick = function () {
						// pass on href link and title
						return imagepop(this.href,this.title);
					}
				}
			}
		}
	}
}
window.onload = checklinks;

Friday, June 25, 2004

CSS: min-width and min-height with Internet Explorer

Combining the underscore hack with the ability of IE to evaluate expressions in CSS, you can set the minimum/maximum width and minimum height of an HTML element using CSS:

div.content {
	background: #eee;
	/* minimum height */
	min-height: 400px;
	/* auto height for compliant browsers */
	height: auto;
	/* min-height for IE browsers */
	_height: 400px;
	/* minimum width */
	min-width:300px;
	/* IE Dynamic Expression to set the width */
	width:expression(document.body.clientWidth < 300 ? "300px" : "100%" );
	/* maximum width */
	max-width:600px;
	/* IE Dynamic Expression to set the width */
	width:expression(document.body.clientWidth > 600 ? "600px" : "100%" );
}

This makes sure that the DIV element this is applied to is at least 400px high and 300px wide and at most 600px wide. This is a combination of Imposing Minimum Width With CSS and The Underscore Hack.

Saturday, June 12, 2004

Browser Capabilities Project

The Browser Capabilities Project is a site where you can get an updated Browscap.ini file that is used for getting the capabilities of the browser that the site visitor is using - so you can check to see if a certain feature is supported - JavaScript, VBScript, Cookies, Tables etc.

The above does not work with ASP.NET, but there is a way to do it by editing your machine.config or web.config files. Details

Underscore Hack (CSS)

A useful hack for serving up CSS that only Internet Explorer for Windows can interpret (i.e. to fix various bugs). Other browsers simply ignore the property. Useful for working round the position:fixed and min-height issues, as well as any others that require CSS that is only interpreted on Windows IE.

ASP.NET Poll Web Control

A useful ASP.NET web control for adding polls to an ASP.NET driven site. Free to use, supports SQL and Access databases. Fairly customisable and the API is documented.

Wednesday, June 02, 2004

MyGeneration SharpDevelop Project Template (C# version)

C# version of my previous template for MyGeneration. Save in the same directory as generated C# dOOdads entities. Set namespace to same one that was used to generate the dOOdads entities. Also MyGeneration.dOOdads.dll has to be placed in the bin\Release subfolder - i.e. My Documents\SharpDevelop Projects\My Project\bin\Release

Interface Code:

Dim cmbDatabases
Dim lstTables

Sub setup()

	If Not input.Contains("lstTables") Or Not input.Contains("txtPath") Then

		ui.Title = "Generate C# SharpDevelop Project"
		ui.Width  = 330
		ui.Height = 450

		' Grab default output path
		Dim sOutputPath
		sOutputPath = ""
		If input.Contains("defaultOutputPath") Then 
			sOutputPath = input.Item("defaultOutputPath")
		End If

		ui.AddLabel "lblPath", "Output file path: ",  "Select the output path."
		ui.AddTextBox "txtPath", sOutputPath, "Select the Output Path."
		ui.AddFilePicker "btnPath", "Select Path", "Select the Output Path.", "txtPath", true
		
		ui.AddLabel "lblNamespace", "Namespace: ",  "Provide your objects namespace."
		ui.AddTextBox "txtNamespace", "Your.Namespace", "Provide your objects namespace."

		' List Databases in a ComboBox
		ui.AddLabel "lblDatabases", "Select a database:", "Select a database in the dropdown below."
		Set cmbDatabases = ui.AddComboBox("cmbDatabase", "Select a database.")

		' List Tables in a listbox
		ui.AddLabel "lblTables", "Select tables:", "Select tables from the listbox below."
		Set lstTables = ui.AddListBox ("lstTables", "Select tables:")
		lstTables.Height = 150

		' Attach the onchange event to the cmbDatabases control.
		setupDatabaseDropdown cmbDatabases
		cmbDatabases.AttachEvent "onchange", "cmbDatabases_onchange"
		
		ui.ShowGUI = true
	Else 
		ui.ShowGUI = false
	End if

End Sub

Sub setupDatabaseDropdown(cmbDatabases)
	cmbDatabases.BindData MyMeta.Databases

	If Not MyMeta.DefaultDatabase Is Nothing Then
		cmbDatabases.SelectedValue = MyMeta.DefaultDatabase.Name
		bindTables cmbDatabases.SelectedValue
	End If
End Sub

Sub bindTables(sDatabase)
	Set db = MyMeta.Databases.Item(sDatabase)
	lstTables.BindData(db.Tables)
End Sub

' Event Handler
Sub cmbDatabases_onchange(control)
	Set cmbDatabases = ui.item("cmbDatabase")
	bindTables cmbDatabases.SelectedText
End Sub

Template Code:

<%
'------------------------------------------------------------------------------
' SharpDevelopC#.vbgen
' Last Updated: 2 June 2004
' Author: Sam Collett
' Creates SharpDevelop project file. Save to same directory as generated business entities
' Place MyGeneration.dOOdads.dll to bin\Release sub folder
'
'------------------------------------------------------------------------------

Dim objTable
Dim objColumn
Dim intLp
Dim bInFirst
Dim tableNames
Dim tableName
Dim namespace
Dim buffer
' Grab the namespace
namespace = input.Item("txtNamespace")
Dim databaseName
databaseName  = input.Item("cmbDatabase")
Set database = MyMeta.Databases.Item(databaseName)

Set tableNames = input.Item("lstTables")
%>
<Project name="<%=database.Alias%>" standardNamespace="<%=namespace%>" description="" newfilesearch="None" enableviewstate="True" version="1.1" projecttype="C#">
	<Contents>
  <%
' Loop through tables in db
For intLp = 0 To tableNames.Count - 1
	tableName = tableNames(intLp)
	Set objTable = database.Tables.Item(tableName)
	If objTable.Name = tableName Then
%>
		<File name=".\<%=objTable.Alias%>.cs" subtype="Code" buildaction="Compile" dependson="" data="" /><%
	End If
Next
%>
		<File name=".\AssemblyInfo.cs" subtype="Code" buildaction="Compile" dependson="" data="" />
	</Contents>
	<References>
		<Reference type="Assembly" refto=".\bin\Release\MyGeneration.dOOdads.dll" localcopy="True" />
	</References>
	<DeploymentInformation target="" script="" strategy="File" />
	<Configuration runwithwarnings="True" name="Release">
		<CodeGeneration includedebuginformation="False" optimize="True" generateoverflowchecks="False" rootnamespace="" mainclass="" target="Library" definesymbols="" generatexmldocumentation="False" win32Icon="" imports="" />
		<VBDOC outputfile="" enablevbdoc="False" filestoparse="" commentprefix="" />
		<Execution consolepause="True" commandlineparameters="" />
		<Output directory=".\bin\Release" assembly="<%=database.Alias%>" executeScript="" executeBeforeBuild="" executeAfterBuild="" />
	</Configuration>
	<Configurations active="Debug">
		<Configuration runwithwarnings="False" name="Debug">
			<CodeGeneration includedebuginformation="True" optimize="True" generateoverflowchecks="True" rootnamespace="" mainclass="" target="Library" definesymbols="" generatexmldocumentation="False" win32Icon="" imports="" />
			<VBDOC outputfile="" enablevbdoc="False" filestoparse="" commentprefix="" />
			<Execution consolepause="True" commandlineparameters="" />
			<Output directory=".\bin\Debug" assembly="<%=database.Alias%>" executeScript="" executeBeforeBuild="" executeAfterBuild="" />
		</Configuration>
		<Configuration runwithwarnings="True" name="Release">
			<CodeGeneration includedebuginformation="False" optimize="True" generateoverflowchecks="False" rootnamespace="" mainclass="" target="Library" definesymbols="" generatexmldocumentation="False" win32Icon="" imports="" />
			<VBDOC outputfile="" enablevbdoc="False" filestoparse="" commentprefix="" />
			<Execution consolepause="True" commandlineparameters="" />
			<Output directory=".\bin\Release" assembly="<%=database.Alias%>" executeScript="" executeBeforeBuild="" executeAfterBuild="" />
		</Configuration>
	</Configurations>
</Project>
<% 
' save project file
SaveOutput database.Alias, "prjx"
' assembly file %>
using System;
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

// Review the values of the assembly attributes

[assembly: AssemblyTitle("<%=database.Alias%>")]
[assembly: AssemblyDescription("C# Class Library")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
// Version information for an assembly consists of the following four values:

//      Major Version
//      Minor Version 
//      Build Number
//      Revision

// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:

[assembly: AssemblyVersion("1.0.*")]
<%
SaveOutput "AssemblyInfo", "cs"
' this function saves the output to disk
Function SaveOutput(filename, ext)
	' Save the output file for this Table
	Dim filepath
	filepath = input.item("txtPath")
	' length of file path
	Dim length
	' position of last 	Dim pos
	' get length from input
	length = Len(filepath)
	' get position of last 	pos = InStrRev(filepath, "\")
	' if last \ is not at the end of the file path, it needs adding
	If Not pos = length Then
		' append \ to path
		filepath = filepath & "\"
	End If
	' filename is generated from table alias, removing invalid filename characters
	filename = filepath & filename & "." & ext
	' save output to file
	output.save filename, false
	buffer = buffer & output.text
	output.clear
End Function

output.write buffer

 %>

<%

Function TrimSpaces(str)

	Dim tname
	Dim name
	Dim char
	Dim l

	name = ""
	tname = str
	l = Len(tname)

	For j = 1 To l
		char = Mid(tname, j, 1)
		If Not char = " " Then
			name = name & char
		End If
	Next

	TrimSpaces = name
End Function
%>