Wensveen's Blog

March 12, 2013

Batch converting a directory of FLAC files to MP3

Filed under: Uncategorized — Tags: , , , , , — wensveen @ 12:35 am

Just a quick one, because it took me a while to get the command right. Hope it helps someone out there with a similar problem. I’m using Debian unstable with (unofficial) deb-multimedia repositories enabled.

The magic command I use is:


find . -name "*.flac" -print0 | xargs -0 -n 1 basename -s ".flac" | xargs -n 1 -I % ffmpeg -i %.flac -ab 196k %.mp3

The 1st command of course finds the input files. The 2nd turns filename.flac into filename. The last command runs ffmpeg on all flac files to convert it to mp3 files (at 196kbps).

If you’re running a version of ffmpeg that can’t encode mp3 files (because of format / patent restrictions), you’ll have to pipe the output from ffmpeg into lame or some other mp3 encoder.

Enjoy!

November 17, 2012

Reboot to Windows from Linux

Filed under: Uncategorized — Tags: , , , — wensveen @ 1:23 am

I, like many others, have a dual-boot system. I run Debian (unstable / sid) as my primary OS, and Windows 7 when I play games. Hopefully Steam coming to Linux means that I won’t have to reboot anymore, but for the moment I do.

Of course, it’s not really hard to reboot your system and then choose the correct option in th GRUB menu, but it does mean you have to stay around to prevent GRUB from booting the default OS, instead of walking to the kitchen to get a cup of coffee / tea  / [insert beverage of choice here]. Well, there’s a solution for that, a command called grub-reboot. For example:

sudo grub-reboot 6

This will set the 7th entry in the list of OSes as the default for one boot (it’s a 0-based index). Then reboot, et voila! You still have to know which entry to boot, of course, but you can just count it once and remember. Right? Well, it’s not always that simple.

The problem is that sometimes a new Linux kernel is installed and the old one is kept, to be able to reboot safely when the new kernel doesn’t work (which has actually never happened to me, but is a possibility when running Debian unstable). In that case, you might need to reboot to a different entry. Besides that, I wanted to have a nice icon to click on, that would set the grub entry and reboot me in one simple step.

I’ve created a simple shell script that reads the correct menu entry from grub.cfg and sets that up for the next boot. After that the script calls gnome-session-quit to request a reboot (you can choose between Cancel, Restart or Power Off):

#!/bin/sh

# Find the menuentry containing Windows
#entry=`grep menuentry /boot/grub/grub.cfg | grep -n Windows | cut -d":" -f 1`
#entry=`grep -E '^menuentry|submenu' /boot/grub/grub.cfg | grep -n Windows | cut -d":" -f 1`
entry=`grep -E '^menuentry' /boot/grub/grub.cfg | grep -n Windows | cut -d":" -f 1`

/usr/sbin/grub-reboot $(($entry - 1))
# Use line below for gnome
#gnome-session-quit --power-off

# Use line below for xfce
xfce4-session-logout --fast

Update (16-5-2013): The version of Grub I currently use, adds support for submenus. Only top-level menuitems and submenus should be counted.

Update (12-2-2014): The current version of Grub does not count submenu items as bootable items. Changed reboot command to match XFCE, which is my current DE (a script could/should be made to auto-detect this).

Save it as ~/bin/reboot-to-windows.sh (or some such). Use chmod to make it executable. Also, you will probably have to fiddle with write rights to /boot/grub/grubenv. Either create a grub-reboot group that you add all allowed users to, and set that as the group for the file. Or you can add yourself and other allowed users to the ‘root’ group (Beware: This might introduce serious security issues). Or you can just make the file world-writeable (which allows all users to fuck up your system by corrupting the file).

Now, to create an entry in the Gnome-shell menu (yes, I use Gnome-shell), create a file ~/.local/share/applications/RebootWindows.desktop with the following contents:

#!/usr/bin/env xdg-open
[Desktop Entry]
Encoding=UTF-8
Name=Reboot to Windows
Exec=/home/your-username/bin/reboot-to-windows.sh
Icon=/home/your-username/bin/Windows-reboot.svg
Type=Application
Categories=System;

Where ‘your-username’ is your username, obviously. I’m not sure ~/bin/reboot-to-windows.sh will work, instead of a full path. The Icon entry refers to a svg graphic I created, here it is:
Windows reboot desktop icon
Save the file. The entry should now show up and be clickable.

Enjoy!

Update (31-12-2012): I forgot a modification in /etc/default/grub:

# Enable grub-reboot
#GRUB_DEFAULT=0
GRUB_DEFAULT=saved

Otherwise, grub will just boot the first entry, no matter what.

November 12, 2012

Synchronous .NET event handling with PowerShell

Filed under: Uncategorized — Tags: , , , — wensveen @ 11:12 pm

There are multiple ways in Windows PowerShell to handle events generated by objects in the .NET framework. The most common, or at least, the most documented way to register an event handler to a .NET object is with Register-ObjectEvent. Usage is fairly straightforward: Register-ObjectEvent -InputObject $obj -EventName "BeforeProcess" -Action { Write-Host "BeforeProcess called" }.

The thing is, that the action you registered with Register-ObjectEvent is called asynchronously. This means that the code that generates the BeforeProcess event doesn’t have to wait for the action to end. Consider, for example, a .NET class:

namespace Echo
{
	public class Echo
	{
		public event EventHandler<EchoEventArgs> BeforeEcho;

		public void EchoMessages(string messages)
		{
			foreach (string message in messages.Split(','))
			{
				EchoEventArgs args = new EchoEventArgs { Message = message };
				if (BeforeEcho != null)
				{
					BeforeEcho(this, args);
				}

				Console.WriteLine(message);
			}
		}
	}

	public class EchoEventArgs : EventArgs
	{
		public string Message { get; set; }
	}
}

Now, create an Echo object in PowerShell:

[void] [System.Reflection.Assembly]::LoadFrom('echo.dll')
$echoObject = New-Object Echo.Echo

Running it without event handlers:

$echoObject.EchoMessages('Mary,had,a,little,lamb')

should yield:
Mary
had
a
little
lamb

Now, when you attach an event handler with Register-ObjectEvent:

Register-ObjectEvent -InputObject $echoObject -EventName "BeforeEcho" -Action { Write-Host ("ObjectEvent: " + $EventArgs.Message) }
$echoObject.EchoMessages('Foo,bar')

Result:
Foo
bar
ObjectEvent: Foo
ObjectEvent: bar

As you can see, the foreach loop in EchoMessages doesn’t wait for the Action to finish, before going on to the next message.

Very often, this is exactly what you want. A lot of examples use System.Timers.Timer, where you just want to execute something every so-and-so hours. But once in a while, you may need the event handler to finish before the next line of code is executed.

Let’s say we want the event handler to be able to skip certain messages, or cancel the rest of the messages altogether. Or maybe modify the message before it is written.

namespace Echo
{
	public class Echo
	{
		public event EventHandler<EchoEventArgs> BeforeEcho;

		public void EchoMessages(string messages)
		{
			foreach (string message in messages.Split(','))
			{
				EchoEventArgs args = new EchoEventArgs { Message = message };
				if (BeforeEcho != null)
				{
					BeforeEcho(this, args);
				}

				if (args.Cancel)
				{
					break;
				}
				else if (!args.Skip)
				{
					Console.WriteLine(args.Message);
				}
			}
		}
	}

	public class EchoEventArgs : EventArgs
	{
		public string Message { get; set; }
		public bool Skip { get; set; }
		public bool Cancel { get; set; }
	}
}

Now, let’s say I want to cancel all messages straight away:

Register-ObjectEvent -InputObject $echoObject -EventName "BeforeEcho" -Action { $EventArgs.Cancel = $true }
$echoObject.EchoMessages('1,2,3,4,5')

Result:
1
2
3
4
5

Why? Because you’re already too late. When you decide to cancel, the number is already outputted. Next invocation is with a new EchoEventArgs object. So we need to register the event handler for synchronous execution. Unfortunately, it isn’t documented at all how to do this. Looking with Reflector, we can see the compiler generated two methods for us: add_BeforeEcho and remove_BeforeEcho:
Echo class in Reflector

So, when we register the event handler with add_BeforeEcho, it all works as expected:

$echoObject.add_BeforeEcho({
  param($Source, $EventArgs)
  if ($EventArgs.Message -eq '2') {
    $EventArgs.Skip = $true
  } elseif ($EventArgs.Message -eq '7') {
    $EventArgs.Cancel = $true
  } else {
    $EventArgs.Message = ($EventArgs.Message + ".00")
  }
})
$echoObject.EchoMessages('1,2,3,4,5,6,7,8,9,10')

Result:
1.00
3.00
4.00
5.00
6.00

Hurray!

March 28, 2012

Typing Danish characters on a US keyboard

Filed under: Uncategorized — Tags: , , , , , , , , — wensveen @ 11:35 am

I live in Denmark, and because I am learning Danish I often have to type the Danish characters æ, ø and å. Since I still have a US keyboard, this is not easy. At least on windows. I usually open the Character Map application and select the characters from there. Once you have inserted them in a text you can copy-paste them when you need them. This works, but it is a little cumbersome.

Character Map

Another option is to hold the Alt key and type the character’s ASCII code on the NumPad, but that means remembering 6 rather random numbers. Here is a table, if you like:

Character NumPad (ASCII) Code
Æ 198
æ 230
Ø 216
ø 248
Å 197
å 229

Unfortunately, many laptops don’t have a NumPad to save space. So not an option.

Luckily, there is a cool program from Microsoft called The Microsoft Keyboard Layout Creator which you can use to create your own keyboard layouts, based on existing ones or from scratch.
(more…)

May 27, 2011

Toggling boilerplate HTML visibility in ASP.NET

Filed under: Uncategorized — Tags: , — wensveen @ 10:23 pm

The problem

When you are writing an aspx page, you write HTML mixed with ASP.NET controls. Sometimes, when some control is not visible, or has no visible (html) output, you may need to hide the html that is containing the control as well.

For example, suppose a document from some CMS may or may not have a Title, or said Title may be empty. Your aspx page might look like this:

..
<h1><cms:FieldControl runat="server" Field="Title" /></h1>
..

Suppose FieldControl is a control that renders the a field of the current document when that field exists and isn’t empty. When Title is empty, you don’t want the <h1> tag to be rendered either.

Solution 1: Placeholders and code-behind

The most straightforward solution to this problem is to place an <asp:Placeholder> control around the <h1>. Then in code-behind, test the FieldControl for output and set the Placeholder visibility accordingly. For example:

<asp:Placeholder runat="server" ID="phTitle">
	<h1><cms:FieldControl runat="server" ID="fcTitle" Field="Title" /></h1>
</asp:Placeholder>

code behind:

protected override void OnPreRender(EventArgs e)
{
	base.OnPreRender(e);
	phTitle.Visible = fcTitle.Visible && !String.IsNullOrEmpty(fcTitle.Text)
}

While there is nothing wrong with this code, it could become cumbersome if you have more than a few of these snippets. There may even be controls that don’t expose a Text property or a similar way to test the control for output.

Solution 2: Introducing the Enclosure control

(more…)

April 12, 2011

A Fluent interface for creating Control hierarchies (method chaining)

Filed under: Uncategorized — Tags: , — wensveen @ 8:34 am

I was creating a custom ASP.NET control for a project and I noticed that creating Control hierarchies was a lot of work, and a bit clunky. For instance, create a table with a single row, with a single cell with just two Panels and some literals in them.

Control structure:

  • (this)
    • Table
      • TableRow
        • TableCell
          • Panel
            • Literal
          • Panel
            • Literal
Table table = new Table { BorderStyle = BorderStyle.None, Width = Unit.Percentage(100) };
TableRow tr = new TableRow();
TableCell td = new TableCell();

Panel ush = new Panel { CssClass = "UserSectionHead" };
ush.Controls.Add(new Literal { Text = "Title" });
td.Controls.Add(ush);

Panel usb = new Panel { CssClass = "UserSectionBody" };
usb.Controls.Add(new TextField { Text = "Enter title" });
td.Controls.Add(usb);

tr.Cells.Add(td);
table.Rows.Add(tr);
this.Controls.Add(table);

As you can see, there’s a lot of variables you need to create just to be able to add (nested) child controls to the control hierarchy. And this is just a very small example. Fortunately, most properties can be set in the initializer, otherwise the boilerplate would be even larger!

(more…)

March 1, 2010

Currying in C#

Filed under: Uncategorized — Tags: , — wensveen @ 4:06 pm

A few days ago, I suddenly felt like experimenting with currying in C#. For those of you that don’t know what currying is, from Wikipedia currying: “[..] currying [..] is the technique of transforming a function that takes multiple arguments [..] in such a way that it can be called as a chain of functions each with a single argument.”

A simple example:

int Add(int x, int y) { return x + y; }
add3 = Add(3);

r1 = add3(6);
r2 = add3(9);

(more…)

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.