DreamHost have been offering Subversion repositories with their hosting packages for the last couple of months, and if you're a developer, a central repository can be a useful thing to have.
Although DreamHost have a simple form for setting up a new repository and they make regular backups incase a hard drive fails, I still have a lingering fear of losing all of my source code. Luckily, DreamHost also offer SSH access and allow you to setup cron jobs to backup your data yourself. This guide provides instructions for creating a shell script to backup, compress, email and restore your SVN repository.
The tools you'll need to export a repository are svnadmin, tar, split, mutt - an email client, and optionally crontab.
Read more »
When Microsoft were deciding what to include in the .NET Compact Framework, they decided to restrict the OpenFileDialog and SaveFileDialog to the My Documents directory. There are plenty of reasons you’d need to choose a file outside of My Documents, so I coded a new file chooser from other components.

The dialog is just a form with a ComboBox which shows the current directory and all of it’s parents, a ListView which shows the files and directories in the current directory, and a text box to show the selected file.
Instantiate it with either the default constructor or a directory and file to show on startup.
FileInfo dbFile = new FileInfo("\\Storage Card\\Somefile.txt");
Lime49.OpenFileDialog dlg = new Lime49.OpenFileDialog(dbFile.DirectoryName, dbFile.Name);
dlg.Filter = "*.txt";
dlg.ShowDirectory(dbFile.DirectoryName);
dlg.ShowDialog();
MessageBox.Show(dlg.SelectedFile);
The selected file is available through the SelectedFile property, and the filter doesn’t work the same way as standard FileDialogs, it uses a standard wildcard pattern to list files.
Download Lime49.OpenFileDialog
Also published on CodeProject
Last week I posted about drag and drop in C#. The post covered pre-built controls (TreeView and ListView). There are a few things the post didn't cover, such as user controls and anything which doesn't raise the ItemDrag event.
To be able to drag a user control, the control has to call the DoDragDrop method. The logical way to do this is by tracking the state of the left mouse button. If the left button is pressed and the mouse moves, start the drag/drop.
private bool isDragging = false;
...
private void userControl_MouseDown(object sender, MouseEventArgs e) {
this.isDragging = true;
};
private void userControl_MouseUp(object sender, MouseEventArgs e) {
this.isDragging = false;
};
private void userControl_MouseLeave(object sender, EventArgs e) {
isDragging = false;
};
private void userControl_MouseMove(object sender, MouseEventArgs e) {
if(isDragging) {
DoDragDrop(userControl, DragDropEffects.Move);
}
};
Read more »
Drag and drop is one of the things that seems easier in C# than Java. In OnTime, the project I'm currently working on, I've used it in several places to make the UI easier to use.
The first example I want to cover is dragging between a ListView and TreeView. This could be used to make re-arranging things easier. Eg: If you're displaying categories in a tree and items in a list.
Read more »
This took a while to get working, but I got there eventually. It's used in OnTime to calculate the number of hours and minutes a user has clicked on. I have rows of horizontal lines which show hours. It's easy to extract a time from a click position, but generally people don't need that much precision and unless the grid is quite large (bigger than 1440 pixels), you won't have 1px per minute anyway.
This snippet will find the nearsest 30 minute interval, so if a user clicks ⅓ of the way between the 4th and 5th division, this would round to 4 hours and 30 minutes.
double clickPosition = ((double)e.Y + -this.AutoScrollPosition.Y) / heightPerHour;
int hours = (int)clickPosition;
int mins = (int)((clickPosition - (double)hours) * 60);
int roundedMinutes = (int)Math.Round((double)mins / 30, 0) * 30;
double fractionalHours = hours + (double)(roundedMinutes / 60.0);
This is designed for a control which autoscrolls, so the actual position of the click is determined first. heightPerHour is the height of each row (each hour).
I thought it would be nifty to show my last Twitter update as a profile field next to all of my posts in the Lime49 forums. It took a bit longer than expected, but eventually I got it working. These instructions are specific to Dreamhost, but you could change the slightly to work on other hosts.
-
You need to change your PHPBB template to include the status next to post matching a certain criteria. I'm the only administrator on the forum, so I set a template flag which is set for administrators, but no-one else.
-
Open viewtopic.php and add the template switch will determine whether the field will be shown. I used my User ID so it wouldn’t be shown for anyone else, but you could use another variable from PHPBB.
Find the section:
'S_CUSTOM_FIELDS' => (isset($cp_row['row']) && sizeof($cp_row['row'])) ? true : false,
'S_TOPIC_POSTER' => ($topic_data['topic_poster'] == $poster_id) ? true : false,
'S_IGNORE_POST' => ($row['hide_post']) ? true : false,
'L_IGNORE_POST' => ($row['hide_post']) ? sprintf($user->lang['POST_BY_FOE'], get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']), '<a href="' . $viewtopic_url . "&p={$row['post_id']}&view=show#p{$row['post_id']}" . '">', '</a>') : '',
And at the end add:
'POSTER_ADMIN' => ($poster_id == 2),
-
Now open stylename\template\viewtopic_body.html and add the following to the top:
<!-- PHP -->
$twitterStatus = file_get_contents('/home/hjennerway/lime49.com/forums/twitter.php');
<!-- ENDPHP -->
-
Still in viewtopic_body.html, add this to the profile section (where the status message will be shown).:
<!-- IF postrow.POSTER_ADMIN -->
<br />
<dd><strong>Currently:</strong>
<span class="twitter"><!-- PHP -->echo $twitterStatus;<!-- ENDPHP --></span>
</dd>
<!-- ENDIF -->
-
Log in to the admin panel and purge the cache.
-
By default, PHP is not enabled in templates. You can enable it in the Security Settings section on the General tab.
-
Now you need a cronjob to connect to twitter, parse your last update and write it to a file. Create a new php file and modify this script to point to your PHPBB installation. Save it as twittercron.php
-
Add a line to crontab to run the script every six hours (or more, depending on how often you update your status). You'll need to change the path to the location where PHP is installed, which you can using which php.
* */6 * * * php5.cgi /path/to/twittercron.php 1>&2 &>/dev/null
This code saves your twitter status to a file every six hours. Them stores the contents of the file in a variable, which is shown in the template.
If you have a toolstrip for navigation, you might want to have buttons on the left and the right, and a label in the centre. There’s no way to stretch the label automatically, but this snippet will resize the label to fill the rest of the ToolStrip. The only requirement is that all of the buttons are the same width.
private void CenteredLabel_Resize() {
int remainingWidth = 144 + btnPrevSkip.Bounds.Left + 2;
lblCenteredLabel.Width = toolStrip1.ClientSize.Width - remainingWidth;
}
You need to replace 144 with the total width of all of the other items on the ToolStrip.
Due to a quirk in the way Windows handles events, once a mouse hover event has been triggered on a windows form control, another event cannot be triggered until the mouse leaves and re-enters the control. Sometimes you might need to process more than one MouseHover event, for example if you have a user control which has draws shapes on itself. As long as you have a record of where the shapes are (by storing them in a collection), you can use the method below as a workaround.
I used this to display a tooltip, so to prevent the MouseHover event being spammed, action is only taken when my tooltip is not visible.
private const uint TME_HOVER = 0x00000001;
private const uint TME_LEAVE = 0x00000002;
private const uint HOVER_DEFAULT = 0xFFFFFFFF;
[DllImport("user32.dll")]
public static extern bool TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack);
public struct TRACKMOUSEEVENT {
public uint cbSize;
public uint dwFlags;
public IntPtr hwndTrack;
public uint dwHoverTime;
}
ToolTip toolTip = new ToolTip();
toolTip.Location = new System.Drawing.Point(290, 80);
Rectangle currentActiveShape = new Rectangle(); // the currently active shape (over which the mouse is hovering)
this.MouseMove += delegate(object sender, MouseEventArgs e) {
foreach(Rectangle rect in myShapeCollection) {
if(rect.Contains(e.Location)) {
if(currentActiveDay != day.Bounds) {
toolTip.Hide();
Console.WriteLine("Hide tooltip");
}
currentActiveShape = rect;
// Set location here
Console.WriteLine("Entered " + rect.ToString());
}
}
};
this.MouseHover += delegate(object sender, EventArgs e) {
TRACKMOUSEEVENT trackMouseEvent = new TRACKMOUSEEVENT();
trackMouseEvent.hwndTrack = ((Control)sender).Handle;
trackMouseEvent.dwFlags = TME_HOVER;
trackMouseEvent.dwHoverTime = HOVER_DEFAULT;
trackMouseEvent.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(trackMouseEvent);
TrackMouseEvent(ref trackMouseEvent);
if(!toolTip.Active) {
toolTip.Show();
Console.WriteLine("Show tooltip");
}
};
As the mouse moves around the control, the location of the tooltip changes, but it’s not shown until the MouseHover event is triggerd.
Due to a quirk in the way Windows handles events, once a mouse hover event has been triggered on a windows form control, another event cannot be triggered until the mouse leaves and re-enters the control. Sometimes you might need to process more than one MouseHover event, for example if you have a user control which has draws shapes on itself. As long as you have a record of where the shapes are (by storing them in a collection), you can use the method below as a workaround.
This snippet will create a JTextBox and draw an image on the right hand side. It also sets the margin accordingly to prevent the user typing into that area.
JTextField myTextField = new JTextField(20) {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
try {
URL url = this.getClass().getResource("image.png");
final java.awt.image.BufferedImage image = javax.imageio.ImageIO.read(url);
Border border = UIManager.getBorder("TextField.border");
JTextField defaultField = new JTextField();
final int x = getWidth() - border.getBorderInsets(defaultField).right - image.getWidth();
setMargin(new Insets(2, 2, 2, getWidth() - x));
int y = (getHeight() - image.getHeight())/2;
g.drawImage(image, x, y, this);
} catch(Exception ignore) {}
}
};
If you’re creating an icon for an application or a website, getting it to look good at 16×16 can be difficult. I spent a few hours getting it right yesterday, so here’s a guide to get you started.
Good Looking 16×16 Icons
A priority queue is like a standard queue, but instead of dequeuing items on a first-in-first-out basis, items are instead served by priority. There are lots of implementations of a priority queue, but none I could find which let the user re-order items. The following class functions just like a regular queue, but can also change the order of items in the queue by their index.
The queue is designed to be used with a ListView set to details mode, but could be adapted for use elsewhere. Using it with a ListView makes sense since the first item in the queue (the next to be executed) is always at index 0, and the indexing for a ListView also starts at 0.
Read more »
Ever needed to retrieve the shell icon for a particular file type in C#? This class will retrieve the Icon associated with a file from just the extension.
using System;
using System.Runtime.InteropServices;
using System.Drawing;
namespace Lime49.Utils {
/// <summary>
/// Retrievs shell info associated with a file or filetype
/// </summary>
/// <summary>
/// Get a 32x32 or 16x16 System.Drawing.Icon depending on which function you call
/// either GetSmallIcon(string fileName) or GetLargeIcon(string fileName)
/// </summary>
public class ShellIcon {
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO {
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
class Win32 {
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // Large icon
public const uint SHGFI_SMALLICON = 0x1; // Small icon
public const uint USEFILEATTRIBUTES = 0x000000010; // when the full path isn't available
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
[DllImport("User32.dll")]
public static extern int DestroyIcon(IntPtr hIcon);
}
...
Read more »
Why couldn't Sun have made JLabels automatically wrap when they're too wide to fit the container they're in? I'd been trying to get a custom component to automatically wrap for hours, then someone suggested a JTextPane in IRC. You can style the pane to look like a JLabel, and it automatically wraps.
JTextPane txtMyTextPane= new JTextPane();
txtMyTextPane.setText("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquam sem et nunc vulputate aliquet. Duis sollicitudin. Vestibulum sit amet lacus a risus egestas nonummy. Donec eu odio id felis auctor lobortis. Cras id nisl vitae pede lacinia elementum. Suspendisse convallis leo. Donec elit. Quisque id mi tincidunt quam tristique posuere.");
txtMyTextPane.setBackground(null);
txtMyTextPane.setEditable(false);
txtMyTextPane.setBorder(null);
This will close a JFrame when the escape key is pressed. The actionPerformed method can do be used to call another method or to close the frame which called it.
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
Action escapeAction = new AbstractAction() {
// close the frame when the user presses escape
public void actionPerformed(ActionEvent e) {
myFrame.dispose();
}
};
myFrame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
myFrame.getRootPane().getActionMap().put("ESCAPE", escapeAction);
If you have hosting with Dreamhost or any other host which gives you a shell account, you can install your own custom version of PHP. I needed to compile PHP with GMP support for the OpenID login plugin for WordPress, so I spent the whole day tweaking trying to get everything working. There's a page on Dreamhost's Wiki which has a script, but it still took me hours to get right. I've written a quick guide to help avoid the mistakes which slowed me down.
- The first thing you need to do is download Putty and set it up to connect to your host.
- We're going to create a few shell scripts to install PHP and all the other packages it requires. It's probably easiest to make your edits in notepad or another text editor, then copy and paste them into Putty by right-clicking. If you just create the files then upload them, there tend to be problems with line breaks and the script doesn't work.
- Start by downloading the preparation script and the installation script. Open them with a text edtitor and change the line export DOMAIN="yourdomainhere.com" to match the domain you're installing the CGI script on. This should be the directory the domain is served from. Eg: If your site serves files from /home/someone/xyz.com, use xyz.com. The version information may need updating, because I won't be updating this script.
- The first script we need to set up will download the different packages and extract them. Once you're done editing, hit CTRL+A in your text editor, then copy everything to your clipboard. Create a new file by typing nano php_prep.sh at the command prompt.
- Paste the contents of your clipboard into the new file by right clicking in Putty, then hit CTRL+O to save the file, then CTRL+X to exit nano.
- In *nix you need to make files excutable before you can run them. Do this by typing chmod +x php_prep.sh
- Now we need to set up the script which does the installing. Create a new file by typing nano php_inst.sh at the prompt, then copy and paste the contents of your edited php_inst.sh file by right clicking the terminal. Hit CTRL+O, Return, then CTRL+X to save and exit.
- Make the file executable by typing chmod +x php_inst.sh
- Now that everything's set up, we can run the first script by typing ./php_prep.sh at the prompt. It might take a while but if there are no errors you should eventually see "Done downloading and unpacking prerequisites".
- Run the installation script using ./php_inst.sh . This might take a while to complete, so start solitaire or something.
- When everything's finished, you should see "INSTALL COMPLETE!" and have a shiny new custom version of PHP installed.
- If you don't already have one, create a .htaccess file at the root of your domain. You can do this by typing nano .htaccess. Add the following lines:
Options +ExecCGI
AddHandler php-cgi .php
Action php-cgi /cgi-bin/php.cgi
- That should be it. If there were no errors, you can test your installation by viewing a PHP file on your site. Hopefully you'll either see no change, but it's possible you'll see a load of errors.
If you have problems installing, the Dreamhost forums might be a good place to ask for help.