Capistrano failure to deploy

Had an issue a while ago where running the capistrano deploy common would sorta run capistrano but always got the following error.

The deploy has failed with an error: No live threads left. Deadlock?

The quick and easy answer is to make sure to prefix the cap command with bundle exec. So it should look like

bundle exec cap production deploy

There is some strange behavior here that I have not found the cause of yet. Something about how bundler executes ruby scripts. So just a heads up.

Set ConformanceLevel to Auto but it is already set to Auto!?

Quick post. I'm currently uplifting an old .NET 1.1 app to 4.5 and when trying to run it was getting the following exception.

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=Token Text in state Start would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment. 
  Source=System.Xml
  StackTrace:
       at System.Xml.XmlWellFormedWriter.AdvanceState(Token token)
       at System.Xml.XmlWellFormedWriter.WriteString(String text)
       at System.Xml.Xsl.Runtime.XmlQueryOutput.WriteString(String text, Boolean disableOutputEscaping)

Upon checking my code I verified that my XslCompiledTransform had the ConformanceLevel set to Auto. However I was still getting this error.

My online searches then suggested it had something to do with the XmlWriter. However there was no clear way to find the ConformanceLevel of the XmlWriter. After a bit of digging I discovered that when calling XmlWriter.Create one can pass in an XmlWriterSettings object with a ConformanceLevel property. I added this property and passed the object to the XmlWriter in Create. This solved the issue that I encountered.

The lesson from this is not only did the XslCompiltedTransform.OutputSettings ConformanceLevel had to be set to Auto but so did the XmlWriter.

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings{ConformanceLevel = ConformanceLevel.Fragment};
XmlWriter resultWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
xslt.Transform(elementToTranform, resultWriter);

Nowhere was the specific change detailed so I think this might be useful for others. Please leave a comment if you find this useful.

Creating Windows Event Log Sources from PowerShell

To help out with some logging in a recent project we needed to organise the Windows logs with multiple sources. A bit of research later and I found a nice and easy way to create these log sources from PowerShell using the New-EventLog cmdlet.

After a few iterations I also put in checks to make sure the event source did not exist before trying to create it and give the appropriate feedback to the user.

function Create-LoggingSources($loggingSources){
Write-HostIndent "Creating logging sources" 1
foreach($loggingSource in $loggingSources.LoggingSource){
$eventLog = [System.Diagnostics.EventLog]::SourceExists($loggingSource)

if($eventLog)
{
Write-HostIndent "Logging Source '$loggingSource' exists" 2
}
else
{
Write-HostIndent "Creating Logging Source '$loggingSource'" 2
New-EventLog -LogName "Sauces" -Source $loggingSource
}

Limit-EventLog -OverflowAction OverWriteAsNeeded -MaximumSize 10240KB -LogName "Sauces"
}
Write-HostIndent "Logging sources created" 1
}

The logging sources are provided in an XML configuration file. $loggingSources is in the following structure.

<LoggingSources>
<LoggingSource>Apple</LoggingSource>
<LoggingSource>Orange</LoggingSource>
</LoggingSources>

I've put together a self contained example of this script you can play with. It will create two new event log sources called Apple and Orange in the log of Sauce. CreateEventLogs.ps1

Checking if supplied domain user credentials are correct with PowerShell

On a recent project we had the problem of creating multiple Windows Services to be run under a single account. So since we did not want to store the password in source control we had our script prompt us for the password. This worked really well until one day we put the wrong password in, and since Active Directory was set up to lock accounts after three bad tries we found we would instantly lock an account every time we put the password in wrong once.

So the obvious solution was to check once that the credentials you had were right before trying to do all this work and stupidly locking an account.

Of course someone had thankfully asked this question before. And thanks to JimB on ServerFault I basically used his entire answer as it did just what was needed. Original answer on ServerFault.

function Test-Login($serviceUsername, $password){
# http://serverfault.com/questions/276098/check-if-user-password-input-is-valid-in-powershell-script
# Get current domain using logged-on user's credentials
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain, $serviceUsername, $password)

if ($domain.name -eq $null)
{
write-host "Authentication failed - please verify your username and password." -ForegroundColor Red -BackgroundColor Black
return $false;
}
else
{
write-host "Successfully authenticated with domain $serviceUsername" -ForegroundColor Green
return $true;
}
}
 

Getting the Combination of Two ItemGroups in MSBuild

In a project recently we needed a way to generate the combinations of two ItemGroups to build a release package with folders for environments and several copies of a program within each environment folder.

As MSBuild does not have an easy way to iterate through two collections to build such a combinations we need to take some advantage of how MSBuild handles collections.

We can take advantage of this by creating a new ItemGroup using one of the ItemGroups we want to combine and creating a new property on this new ItemGroup using the collection defined by the second ItemGroup we want to combine

The below snippet shows this in action. Try it out by copying into a text file, saving it, and running it with MSBuild.exe.

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="DressPerson"
 xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<ItemGroup>
<Person Include="Item">
<Name>Alice</Name>
</Person>
<Person Include="Item">
<Name>Bob</Name>
</Person>
<ItemOfClothing Include="Item">
<Name>Shirt</Name>
</ItemOfClothing>
<ItemOfClothing Include="Item">
<Name>Shorts</Name>
</ItemOfClothing>
</ItemGroup>

<Target Name="DressPerson">
<!-- Neat way to get the combinations of two ItemGroups http://stackoverflow.com/a/18032552/41492 -->
<ItemGroup>
<Combined Include="@(Person)">
<ItemOfClothingName>%(ItemOfClothing.Name)</ItemOfClothingName>
</Combined>
</ItemGroup>

<Message Text="%(Combined.Name) -- %(Combined.ItemOfClothingName)" />
</Target>
</Project>

Huge thanks to the user Dog Ears on StackOverflow whose answer put me on the right path. http://stackoverflow.com/a/18032552/41492

Remembering where you've been in Powershell with pushd and popd

The other day I discovered a long existing pair of commands in Powershell that allows one to navigate to a directory and then back to the previous one without having to manually maintain a stack of directories. The two commands are pushd and popd.

A quick bit of searching shows that these commands have existed in Unix shells for many years as well as Powershell since version 2. Wikipedia -- Pushd and popd

Where I have found this really useful recently is in deployment scripts where I need to change the current directory in the script but for usability I want to go back to where the script was first called from should any errors occur or even if the script finishes successfully. By using a try/catch/finally pattern this allows me to put the user back where they started with confidence whenever they execute the script.

try
{
pushd DIRECTORYPATH
# Logic goes here
}
catch
{
# Make sure any exceptions are bubbled up
throw $_
}
finally
{
popd
}

TechNet -- Push-Location
TechNet -- Pop-Location

Open Government Data Sets

One of the lesser known government websites that I have come across is https://data.govt.nz/

This is a site that gathers together most, if not all, the data sets offered by all the various government department. From CEO salaries, to land mapping, to health data.

In the past I've used it to find such interesting tidbits as how the median age of death has moved over time and how state sector CEO salaries have moved in comparison to front line workers.

So go browse and find interesting things and make use of the data created via your taxes.

Health, Voting, and Corruption.

Green Party Health Policy

One of the things that has made me wary of putting strong support for the Greens has always been their policy on science related topics. Whilst the Genetic Engineering one is well known their health policy was one full of anti vaccination and alt med. This was a direct result of the previous Green Party health spokesperson Sue Bradford. Since then Kevin Hague has overseen a change to this policy. The author of HonestUniverse recently got in contact with Kevin Hague to see just what sorts of support for alt med the Green Party has as part of their current health policy. A very interesting read it demostrates an interesting change in how the Green Party has changed.

Advance voting statistics

An interesting change in this election to previous elections has been just how hard all the parties have been pushing early voting. During the week the Electoral Commission tweeted a link to this page where they are tallying the number of votes per day but also compare it against the early voting period of the past two elections. The Electoral Commission does state they will update this everyday but as of this writing it seems to be every weekday. So far the uptake of early voting is already nearly 3 times compared to the same time last election. However I will find it interesting to see if this is people who do not usually vote or is it just people who usually vote on election day getting in early.

Judith Collins' office made haste on OIA

Even though Judith Collins jumped before she was pushed there are still details coming to light on the selected fast tracking of OIA requests. It does seem to be that the only OIA requests to be delivered in a reasonable time or even extremely fast time are those that covered topics that would embarass those she disliked such as the head of the SFO at the time. It will be interesting to see just what the results of all the investigations are after the election and to see just what happens to Judith Collins.

Good comments instead of bad

One of the refrains that we all hear when the topic of code comments comes up is the refrain “My code is self-documenting.” On the surface this refrain makes sense, why write more than you have to. Unfortunately the way this is usually implemented results in the baby being thrown out with the bathwater. Leaving us in a worse off position than we were with too many comments.

I’ve never met someone who would argue that the code we create should be difficult to understand. That the how the code executes should be hidden or where the flow of control goes. Our code needs to be easy to understand so that as we maintain it in the future we do not have to rewrite entire classes just to add a bit of functionality.

So, what is a good code comment?

Comments should explain WHY” to paraphrase the colleague of mine who gave me this pointer.

Code Comments

How often have you come across some code that works but does something in a crazy way when a much more simple option is clear to you? Only when you implement your simple solution suddenly bugs appear and you finally understand why those lines existed.

An example of a superflorus comment can be found in the .NET Framework Reference Source of the String class. Range check everything. Yes, I can see that’s being done. You’ve obviously thought it important enough to point out but why? Why is it important to note that you are doing all range checks? A comment like this only results in more questions while answering none.

This sort of situation is where code comments become invaluable and will save you and your colleague’s hours in the future. Spend the time to explain why you made the design decisions you did. When you apply a workaround that is strange explain why you did this instead of the more ‘obvious’ solution.

A good example can also be found in the .NET Framework Reference Source. But this time in the DateTime class. That DateTime adjustment underneath the code is not clear at first glance why you would want to add double the day remainder in milliseconds when the time is negative. However when we read the comment above it explains why we would want to do such a thing and even uses a clear example to demonstrate the way.

Commit Comments

This concept of explaining why finds even more value when it comes to commit comments.

How often do you see an odd design decision but when you look into the history of that file the comment is “Added files.” A comment like that is less than worthless because not only does it tell you nothing new but you get irritated or angry and it sits with you as you try to fix whatever is wrong. Again, explain WHY you have made the changes you have. Explain why you chose a pattern or design over another. When writing these comments imagine that 12 months from now you will be coming back to this. When we can barely remember why we made choices a few weeks ago how can we expect to remember why we made choices 52 weeks later?

So to conclude. “Self-documenting code” should be applied to only the how something works. In no way can it show the why changes were made of designs chosen. When you come back months or years later the why is more valuable than any amount of how or what comments.

Running MSTest unit tests via an MSBuild script

The past couple days I've been having fun trying to get some MSTest unit tests to be run from a MSBuild build script. This was so I could run all the tests via one build script via TeamCity without having it tied into TeamCity too heavily.

You can then use the XML Report Processing build step in a TeamCity build configuration to parse the results file and this will give you the tracking of tests.

Huge thanks to Yet Another Blog In Cyberspace for doing most of the legwork that I based my stuff off of. Running MSTest UnitTests using MSBuild

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="RunCIBuild"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MsTestExePath>C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\mstest.exe</MsTestExePath>
<DoubleQuotes>"</DoubleQuotes>
<OutputPath>$(MSBuildProjectDirectory)\Output</OutputPath>
<MsTestResultPath>$(OutputPath)\MyResults.trx</MsTestResultPath>
<Configuration>Release</Configuration>
</PropertyGroup>


<Target Name="RunCIBuild">
<CallTarget Targets="CompileSolution"/>
<CallTarget Targets="AfterBuild"/>
</Target>

<Target Name="CompileSolution">
<MSBuild Projects="<!--Solution file goes here-->"
Properties="Configuration=$(Configuration)"
Targets="Build">

</MSBuild>
</Target>

<Target Name="AfterBuild">
<ItemGroup>
<TestAssemblies Include="$(MSBuildProjectDirectory)\**\bin\$(Configuration)\*.Test.dll"/>
</ItemGroup>

<PropertyGroup>
<MsTestCommand>"$(MsTestExePath)" @(TestAssemblies->'/testcontainer:"%(FullPath)"', ' ') /resultsfile:"TestResults\Results.trx""</MsTestCommand>
</PropertyGroup>

<Message Text="MsTestCommand: @(TestAssemblies->'/testcontainer:$(DoubleQuotes)%(FullPath)$(DoubleQuotes)', ' ')"
Importance="high"/>

<RemoveDir Directories="TestResults"
Condition="Exists('TestResults')" />
<MakeDir Directories="TestResults" />

<Exec Command="$(MsTestCommand)"
ContinueOnError="true" />
</Target>

</Project>

2012 GN125H For Sale

Time to upgrade to something with a little more grunt. That means my little GN125 is now surplus to requirements.  Get in contact with me at James@TheFlightlessGeek.co.nz if you would like to purchase the bike.

This is a great commuter and learner bike. I've managed to reliably get 2.5L/100km around Wellington streets. Handling around town is light and easy. Super simple to maintain as well.

Comes with the pictured saddle container. 

Only a couple of scrapes and a cracked right wing mirror from one low speed spill. See attached pictures.

 

2012 GN125H   

Odometer: 4,090km

Registration: Valid through to 3/3/2014

WoF: Valid through to September 2013

 

Asking price: $1,700

Some good quotes from the homosexual marraige bill third reading

Some of the speeches last night were just awesome. So I've gone and skimmed the draft transcript and selected the lines that I thought were some of the best of the entire evening.

Maurice Williamson

I have had a reverend in my local electorate call and say that the gay onslaught will start the day after this bill is passed. We are really struggling to know what the gay onslaught will look like. We do not know whether it will come down the Pakuranga Highway as a series of troops, or whether it will be a gas that flows in over the electorate and blocks us all in. I also had a Catholic priest tell me that I was supporting an unnatural act. I found that quite interesting coming from someone who has taken an oath of celibacy for his whole life.

I also had a letter telling me that I would burn in the fires of hell for eternity. That was a bad mistake, because I have got a degree in physics. I used the thermodynamic laws of physics. I put in my body weight and my humidity and so on. I assumed the furnace to be at 5,000 degrees. I will last for just on 2.1 seconds. It is hardly eternity. What do you think?

Let me repeat to them now that all we are doing with this bill is allowing two people who love each other to have that love recognised by way of marriage. That is all we are doing. We are not declaring nuclear war on a foreign State. We are not bringing a virus in that could wipe out our agricultural sector for ever. We are allowing two people who love each other to have that recognised, and I cannot see what is wrong with that for neither love nor money. I just cannot.

But I give a promise to those people who are opposed to this bill right now. I give you a watertight guaranteed promise. The sun will still rise tomorrow. Your teenage daughter will still argue back to you as if she knows everything. Your mortgage will not grow. You will not have skin diseases or rashes, or toads in your bed. The world will just carry on. So do not make this into a big deal. This bill is fantastic for the people it affects, but for the rest of us, life will go on.

Jami-Lee Ross

I simply do not believe that it is right to determine an issue that affects only minorities by way of a referendum. If that was the case, I doubt New Zealand would have given women the right to vote when this country did, nor would this country have legalised abortion when it did, nor would this country have decriminalised sex between two consenting males when it did. Minority rights issues are not referendum issues.

 I want to briefly talk also about the question of children, because it is a common theme that some opponents have been raising. The prevailing wisdom seems to be that every child must have a mother and a father. I know that it is a touchy subject, but as someone who actually grew up without a mother and without a father, I think I am somewhat qualified to speak on the issue. A child does need both male and female influences in their life, but those influences do not necessarily have to come from their biological parents. What is most important is that a child is raised in a loving and caring environment. What is most important is that the people who are raising that child give them a home that is safe, warm, educating, and nurturing. If that environment just so happens to be a same-sex marriage, then that child is just as fortunate as every other loved and cared for child.

Grant Robinson

This bill is also about inclusion. Quite simply we will not succeed as a country or society if we continually find reasons to exclude people. The only place that takes us is division and hatred. Why on earth would we want to stop a couple who love each other and who want to make a commitment to one and other from doing that? Why would we want to exclude some people from a cherished social institution?

Nothing about this legislation will affect anyone else’s marriage. Husbands will still call their wives their wife and vice versa. I will let you all in on a secret, we have all been calling our partners husbands for years. Normally it is when I am being told off.

Tau Henare

I did have a speech prepared, but that speech shot it to bits. Here is the bona fides on the New Zealand First referendum of the 1990s. The National Party said no to a bill. That is why we went to a referendum, and when we went to a referendum, 82 percent of the country said: “No, Winston. We don’t believe in you any more.” That is what it said. It never went through caucus. It never went through caucus. And that speech that I heard tonight was the biggest shyster speech I have ever heard—the biggest shyster speech I have ever heard.

But I tell you what: that speech tonight is nothing more than pandering to the 10 percent on either side of this argument. It is nothing more than pandering to those racist, redneck people who just love to get on the email.

I want to say that I have been appalled with some of the behaviour of those for the bill and against the bill, because I for one do not think that those who are against the bill are homophobic just because they are voting against it. It is their right to vote against it, and I will back my colleagues who vote against it all the way. I just do not agree with them.

If it does belong to the Church, as I have been told by so many people on the email, then why do we have legislation outlining who can and who cannot? If there was no legislation, I would back the Church 100 percent. But it is not theirs. It actually belongs to the Government. It actually belongs to this Parliament. It is a creature now of Parliament. It is not a creature any more of either the Bible or the Church.

Nikki Kaye

I want to acknowledge Chris Auchinvole and Paul Hutchison. They have shown us in this debate the true power of conscience. When Paul said: “I … cannot construct a strong enough intellectual, moral, health, or … spiritual argument against it.”, he struck a chord with so many New Zealanders, because he showed us openness and he showed us compassion for people. Our Parliament can be very proud that this vote is actually less about political divides but more about religious and generational divides.

Kevin Hague

I remember travelling to Auckland’s North Shore to protest against one of our opponents, Pastor Richard Flynn, who called publicly for homosexuals like me to be put to death. Over the years I have campaigned hard for the right of our communities not to be outsiders anymore and to assume a full place in New Zealand society. With every new reform, the same group uses the same strategy, raising fears of terrible consequences that always fail to materialise. There would be few New Zealanders today who would support re-criminalising sex between men. The cost of being outsiders is enormous. The stigma associated with our “inferior” status is associated with substantially higher rates of suicide, depression, HIV risk, violence, and other risks to our health and well-being.

Their problem with this bill is that they believe that we gay and lesbian people are morally inferior. They do not want to include us as full participants in New Zealand society. They recognise correctly what full legal equality—this signal—means, and they do not like it. That is why we have seen people with placards declaring that gay people are mentally ill and less than human. That is why we have seen Family First’s campaign, firstly, of fear and misinformation and, latterly, of stand-over tactics and blackmail. That is why we have seen Catholic Action, just like Richard Flynn, writing to all MPs and telling us that homosexuals are worthy of death and then describing in great detail the eternal agony we should expect to experience in hell. They have tried to attract more people to their cause by scaring people with imaginary consequences—people will marry their pets, ministers will be thrown in prison, and people will not be able to call each other husband and wife anymore! Just like every time before, these fears will not be realised. The consequences of this bill will be that same-sex couples will marry. Transsexual people will no longer have to divorce. Prejudice and violence will be undermined.

John Banks

The privilege we have to be in this House is counterbalanced by the need to stand up and be counted. I am one of a handful of members who was here in the very early days of these debates. After three decades and 10 Parliaments, I have had time to reflect—to reflect on what I said and to reflect on what I did. If I knew then what I have since learnt, I would have acted differently. I see this as a debate more about human rights, predicated on the basis that we are all entitled to live our lives to the fullest extent of human happiness, while respecting the rights and beliefs of others. I believe all New Zealanders should be free to pursue their own happiness.

Te Ururoa Flavell

In 1888 the Supreme Court of New Zealand made a decision that has been described as “doubtful legally and deplorable socially”. That doubtful and deplorable decision was to reject the customary marriages that had existed mai rānō, and to assume that the marriage law of England took precedence. In fact, the colonial law from another land was considered of such importance that the children of Māori customary marriages were then described as “illegitimate”,

So when opponents of this bill criticise a change to the definition of marriage as contravening our sacred traditions, I would have to say “Whose traditions are we talking about?”

Jonathan Young

A tradition is a convention, a belief, or a behaviour that stands the test of time. A tradition is the institutional memory of a society. It is not to be cast off or cast away quickly or easily, because it is the touchstone of a value that perhaps younger minds may not fully understand, yet enter into, because it is there. Traditions are what we use to guide people, I believe, into the things of life that have been proven to work.

Kris Faafoi

I know there are strong religious veins in the Pacific community, and I respect that and the views that they have, but many young, gay Pacific Islanders have found this debate difficult. Many have grown up and maintain strong religious beliefs. They have told me one of the hardest things in the public debate has been hearing that the God that they worship seems to see them differently. My God does not. I hope that our community can embrace that there are many in our families who on a daily basis struggle to be openly who they are.

Paul Hutchinson

At one of my electorate meetings a highly intelligent, crusty, salt of the earth farmer urged me to vote against the bill, but he later joked that over the last few generations the sequence of events has gone like this: in the first instance parents such as himself used to tell their daughters not to come home with someone from a different religion, then not to come home with someone from a different race, then definitely not to come home single and pregnant, and, today, then not to come home with someone from the same sex, let alone marry them. He encapsulates the fact that society has evolved enormously within a few generations, just as marriage has been evolving as a civil and religious institution throughout human history.

As a former specialist obstetrician and gynaecologist, extremely poignant experiences for me were the rare occurrences where at the birth of a baby, when the parents instinctively asked: “Is it a boy or a girl?”, I had been literally unable to tell them. This has been because of ambiguous genitalia or a unique physical abnormality. It may take some weeks to fully assess a child, have genetic testing carried out, and assign a sex. Even that may be later changed. This illustrates the dramatic new knowledge available in the modern world to better understand the spectrum of physical, genetic, and social expression of gender and sexuality that was simply not possible in the past. I ask anyone, on either side of the debate, whether they would not hope that their newborn could be brought up in a society that is both tolerant and as caring about their child’s status and aspirations as any other child’s—a society that is inclusive, fair, and committed to respecting one another.

In the first reading of this bill I said that despite trying hard, I could not construct a strong enough intellectual, moral, health, or even spiritual reason to vote against it. I am now quite convinced that, at the end of the day, the strength of any human union is about love, tolerance, giving, forgiving, sharing, inclusiveness, commitment, and fairness irrespective of gender. These are universal qualities that have no boundaries.

Chris Auchinvole

We have faced many issues of conscience in our nation’s relatively short history, and I think we have grown stronger by facing them together, not always as adversaries but as fellow members of a small and empathetic nation that often gives fine examples to the rest of the world.

As an older person I would ask that the younger generation—epitomised, of course, in my colleague Nikki Kaye—show some patience and consideration for those of my generation who will need time to adjust to a change that will be very, very new to us. By the same token we cannot move forward as a nation if we older ones ignore or reject the heartfelt pleas for respect by the lesbian, gay, bisexual, and transgender community and the younger brigade. We need their acceptance as they are entitled to our acceptance.

Ruth Dyson

The Marriage Act has since 1955 said that celebrants can do that, presumably to protect celebrants from being forced to marry heterosexual couples of different religions or—heaven forbid—marry somebody who was divorced.

Moana Mackey

And although I respect the beliefs of those who oppose the bill on religious grounds, I strongly believe that although it is the role of the State to protect freedom of religious expression—and this bill reaffirms that—it is not the role of the State to uphold one group’s religious beliefs over another’s.

This debate is not about special rights for some; it is, in fact, the very opposite. It is about acknowledging that something that used to be seen as so scary, immoral, and different that my mother felt compelled to be an active member of a group called HUG—Heterosexuals Unafraid of Gays—is, in fact, completely normal.

Gay, lesbian, bisexual, transgender, and intersex people will not be any better or worse at marriage than us straights. They will face the same challenges, the highs and lows, the successes, and the failures.

My late grandmother always had a wonderfully uncomplicated approach to life. At one point she became quite taken with Brendan, the partner of one of my best friends from high school, Peter. She told me that she would not be at all disappointed if Brendan were to become her grandson-in-law. I said to her “But, Grandma, he’s gay.”, to which she responded “Well, your grandfather wasn’t the easiest person to live with, but you make marriage work.”

The full video of the speeches can be found on the ParliamentTV YouTube channel.

And the full transcript of the reading.

How not to draw too much from the Hutt Aquifer

Before the recently ended water restrictions it was my belief the Waiwhetu (Hutt) quifer was only used when the Hutt river was unable to provide enough. As it turned out the aquifer is used everyday.

This raised a question in my mind. Water enters aquifers at a specific rate that can be a lot lower than the rate we are able to remove it at. The current iconic example of this is one of the big aquifers under the north central US where we are draining it faster than it is replenished. So how does the Wellington Regional Council stop this from happening?

To try and get an answer I shot off a quick email to the Wellington Regional Council and got a response the next day.

...

We have a resource consent to take up to 115 MLD provided we do not lower the pressure in the aquifer beyond 2.3 metres, as measured at the Petone foreshore.  There is also a practical limit to how much water we can draw from the aquifer due to pumping and system capacity constraints. This is around 100 MLD.

The aquifer pressure is monitored continuously and our supervisory, control and data acquisition (SCADA) system will alert operations staff if the pressure approaches the lower limit.

...

A quick and useful answer and no one even had to protest. ;) It's as though they're human. :p

Anyways, I was pleased to see that there are rules in place that make sense for the Waiwhetu aquifer. A minimum pressure requirement definitely stops us from removing at a faster rate than replenishment and is much more responsive to changes in the recharge rate. More importantly it also stops aquifer from being infiltrated by salt water from the harbor; that would be very bad.

Mythical Man Month

This is such an awesome book I thought it useful to educate more people on its existence.

The iconic book by Fred Brooks covers many of the lessons he learnt during his time as a project manager of the IBM System 360 project. The book is separated into sections that cover a topic at a time and have suggestions for avoiding the issues he ran into. 40 years later we are still running into the same problems on projects today. A must read for any tech lead and highly recommended for any developer who thinks they will end up on a project where they are either the sole dev or one of a couple, basically any dev ever.

Using a script to set the Copy Local flag to false

As with my previous post I recently came across a repeatable task that we will probably want to repeat in the future so with my aim from The Pragmatic Programmer I decided to automate it.

The problem was that an architecual requirement of this project was to rely on DependencyInjection for all library references. To help enforce this every project outside of the DI one would require the Copy Local flag on all references set to false.

I started doing this manually but figured out it'd take a long time to go through all 40+ projects and this would happen in the future. So automation time it was.

A quick web search did not show that anyone had solved this problem before so I figured out I would have to learn some Powershell and make it myself.

As csproj files are simply XML I did some research to find out how easy it was to manipulate XML in Powershell. It turned out this is one of Powershell's strengths. However the first implementation had issues with namesapces so I had to use the Select-Xml command introduced in Powershell v2.

Building the XPath queries was fairly simple. The one hiccup to remember is that csproj xml has a default namespace of "http://schemas.microsoft.com/developer/msbuild/2003" so you need to remember to use that and the msb namespace prefix when making your XPath queries. To specify the namespace in Select-Xml you use the -namespace option.

Select-Xml -namespace @{msb = $projectNamespace} -xpath $privateXPath

The next step was saving out the changes. This proved to be an initial roadblock as all the files were set to readonly. As we are using TFS you have to explicitly checkout the files before you can edit them. This resulted in me looking into how to use the TFS command line executable "tf.exe". This proved to be fairly nice as I could simply pipe the collection of csproj files I wanted checked out to a chunk of script that would iterate through the collection and execute the checkout command on each file with the provided TFS credentials.

I explicitly did not attempt to check in the changes as I want the user to review the changes and make sure the solutions are still working. This is something you'd run once a month to make sure the requirement is still being followed.

The final hiccup was that the .NET XML classes Powershell uses has an issue with putting in a default empty namespace whenever you create a new element. This caused the project to fail to load in VisualStudio as the namespace was incorrect. The fix for this was pretty quick and easy. Take the file and replace any occurance of xmlns="" with an empty string. This is accomplished in Powershell with line

(Get-Content $projFilenameFull) | Foreach-Object {$_ -replace ' xmlns=""', ""} | Set-Content $projFilenameFull

So my first non-trivial powershell script was a fun and fiddly dive into scripting all my troubles away. So far so good. ;)

SetCopyLocalInAllCsProjFiles.ps1

Deleting all bin and obj folders from a solution

Quick little post.

Since reading The Pragmatic Programmer by Andrew Hunt and David Thomas I've been looking for ways to automate tasks whenever I find myself doing something I know I'm going to repeat later or I'm repeating right there and then.

The other day I was working on a VisualStudio Solution someone else had started and when trying to build it found they had checked in some of the bin and obj folders.

So I open up the root folder of the solution and prepare to trawl through about a dozen projects to delete all the bin and obj files. Obviously noticing that I'm about to do the same steps repeatedly and this will happen in the future I went and did a quick search to see if anyone else had already solved this.

Awesomely someone had.

So a huge thanks to Glenn at Development on a shoestring for providing exactly what I needed. I'm putting this here just in case his site should disappear and take the knowledge with it.

I threw the following into a powershell script that sits in source control ready for use in the future

# Iterate through all subdirectories and delete all bin and obj folders
# http://blog.slaven.net.au/2006/11/22/use-powershell-to-delete-all-bin-obj-folders/
# Had to use it for getting rid of a bunch of bin and obj folders in a PoC but thought it smart to put in here for other to use
Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }
RemoveAllBinAndObjFolders.ps1

Connecting an iOS device to a mixed 802.11b/n WiFi network

In a recent visit to home I was presented with an old problem that had become a real annoyance. The iOS devices owned by the family (minus the iPad) including my iPhone would not connect to the house WiFi network. They would happily detect them but the moment they tried to connect they would time out.

It took a bit of pecking around and trial and error but I found a single change that then allowed all the devices to connect.

It boils down to only allowing 802.11b to operate on the 2.4GHz band instead of the default dual b/n. It see,ms the iPhone and iPod Touch devices do not play nicely with dual use of that band by the b and n standards.