Monthly Archives: October 2011

Say no to primitives in your API.. and make your software more explicit

A while ago I wrote some code like this:

public interface ICanBroadcast
{
 public void Broadcast(string message) { ... }
 public void Broadcast(string message, string author) { ... }
}

A bit later the requirements changed and from now on it was required to specify the topic:

public interface ICanBroadcast
{
 public void Broadcast(string message, string topic) { ... }
 public void Broadcast(string message, string author, string topic) { ... }
}

In case you were using Broadcast(string message) the compiler would rightfully inform you that no such method exists. In case you were using Broadcast(string message, string author) the compiler does not catch the error and incorrectly uses the author as topic. I can only hope that you have a suite of tests that makes you notice that something is wrong when you upgrade to my latest release.

Let’s make the difference between an Author and a Topic more explicit (to our API consumers and the compiler) by creating explicit types to represent the concepts:

public interface ICanBroadcast
{
 public void Broadcast(Message message, Topic topic) { ... }
 public void Broadcast(Message message, Author author, Topic topic) { ... }
}

The joy of using a typed language ;)

Force the removal of a file with PowerShell

Last couple of weeks I have been generating a lot of files (and restricting their ACLs) and today I decided to remove all those files. The problem is that my user account did not have permissions on those files. Here is a small script that will first take ownership of the file, then grants FullControl permissions, and finally removes the file :)

function RemoveFile
{
	param($FileName)
	
	&takeown /F $FileName
	
	$User = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
	
	$Acl = Get-Acl $FileName
	$Acl.SetOwner($User)
	$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($User, "FullControl", "Allow")
	$Acl.SetAccessRule($AccessRule)
	Set-Acl $FileName $Acl

	Remove-Item $FileName
}

Get-ChildItem *.txt -R | % { RemoveFile $_.FullName; }

Edit on 2011-10-19

Resetting the permissions with icacls c:\output /reset /t and then calling Remove-Item c:\output -R does the trick.

function RemoveFiles
{
 param($Directory)
 icacls $Directory /reset /t
 Remove-Item $Directory -R
}

RemoveFiles c:\output;