Saturday, December 17, 2011

Backups


Here's my save function:

function global:save-checkbook ($checkbook) { #save-checkbook
$checkbook | export-clixml -path checkbook.xml
$a = (Get-Host).UI.RawUI
$a.ForegroundColor = "cyan"
$a.BackgroundColor = "darkcyan"

}

What happens if I type “save” and give it the wrong variable?

All my data is over-written. I shouldn't have to worry about that.

Here's my load function:

function global:get-checkbook {
import-clixml -path checkbook.xml
}

I want to make a copy of my checkbook before I open it, so, here's the code:

function global:get-checkbook {
$tempdate = get-date
$path = "checkbook"
$path += $tempdate.year
$path += $tempdate.month
$path += $tempdate.day
$path += $tempdate.hour
$path += $tempdate.minute
copy-item checkbook.xml $path
import-clixml -path checkbook.xml
}

This works fine, but I'll add an XML extension for consistency.

(I know that this only keeps one backup per minute, but I think that's enough. The problem will be lots and lots of backups piling up. I guess I could write script that kept just one per day, or something, or delete them by hand, from time to time.

But that will wait.

Since the function is more complicated, it needs to be documented, plus, with the complicated hash table that I use for transactions, this might get disorienting. How about this:

function remind {
" "
" "
"get-checkbook [load]"
"save-checkbook [save]"

"new-transaction [nt]:"
"-month -day -payee -amount -cat -debit (default TRUE) -year (Currently 2011)"

}

Powershell provides all this information, of course, to people who know how to look for it, but this is all I expect to be trying to remember at any given moment.

And here's the revised get-checkbook:

function global:get-checkbook {
.SYNOPSIS
Loads the checkbook array into a variable you provide.

.DESCRIPTION
Gets the contents of a file called "checkbook.xml" after saving the current contents in a dated backup file.


$tempdate = get-date
$path = "checkbook"
$path += $tempdate.year
$path += $tempdate.month
$path += $tempdate.day
$path += $tempdate.hour
$path += $tempdate.minute
$path += ".xml"
copy-item checkbook.xml $path
import-clixml -path checkbook.xml
}

The long term plan for this is to do finances with it for the month of January, see how easy it is to use, add and revise functions as I go.

Saturday, December 10, 2011

Some setup

My housekeeping:

I've created a new directory and created a new script file for my finances functions.

Back in my profile, I made a little function that will change to the new directory:

function do-finances {

    cd MyDir

    $a = (Get-Host).UI.RawUI
    $a.ForegroundColor = "blue"
    $a.BackgroundColor = "white"

    clear
}

set-alias df do-finances


So, if I type "df", I'm moved to the right directory - and that other stuff? Well, if I'm actually going to try this as a place where I keep my account information, it would be nice to know, for sure, that I'm using PS for something different than I usually do.

And it gives me another option.

I can add the following lines to the new-transaction function from a couple of days ago:


    $a = (Get-Host).UI.RawUI
    $a.ForegroundColor = "magenta"


Which means that every time I have unsaved data - the transaction just created - the shell will have a different appearance.

Next time, persisting data.


Thursday, December 8, 2011

A Pilot Project


Now that I have a transaction record, I need something to use for all the transactions. I thought about using a hash table again, but then I would have to figure out what to use for a key and that seems unnecessary. PowerShell arrays are OK for little stuff, but there's a lot more built into System.Collections.ArrayList.

PowerShell: $a = new System.Collections.ArrayList
PowerShell:
PowerShell: $b1 = nt
PowerShell: $b2 = nt 12 7 -cat groceries

Create an array list and create two transaction objects. This is what they have in them:

PowerShell: $b1

Name Value
---- -----
year 2011
payee blank
amount 0
cat blank
month 0
day 0


PowerShell: $b2

Name Value
---- -----
year 2011
payee blank
amount 0
cat groceries
month 12
day 7

Going to add one and then the other:

PowerShell: $a.Add($b1)
0
PowerShell: $a

Name Value
---- -----
year 2011
payee blank
amount 0
cat blank
month 0
day 0


PowerShell: $a.Add($b2)
1

And here's what the array looks like now:

PowerShell: $a

Name Value
---- -----
year 2011
payee blank
amount 0
cat blank
month 0
day 0
year 2011
payee blank
amount 0
cat groceries
month 12
day 7

One of the sheets on my spreadsheet has the current balance of our checking account, a list of outstanding payments, and remaining balance. I'm going to try to implement that now.

OK, here's my first draft:

PowerShell: function currentBalance ($checkbook) {
>> foreach ($a in $checkbook) { $total = $total - $a.amount}
>> $total
>> }
>>

I know you can see the problems with it.

  • It assumes $total will be blank.
  • It assumes that the amount in the first entry of $checkbook will be a negative number.
I could make a function with two parameters: one for the bank balance and one for the outstanding transactions, but I don't want to – running that is almost as complicated as just using a calculator. Let's try something else.

I added a payee field to the bank_balance transaction:

PowerShell: $bank_balance = @{amount=75;payee="balance"}

And I wrote the function as follows:

PowerShell: function get-balance ($checkbook) {
>> $total = 0
>> foreach ($a in $checkbook) {
>> if ($a.payee -eq "balance") { $total = $total + $a.amount }
>> else { $total = $total - $a.amount }
>> }
>> $total
>> }
>>

And now I'm going to test it:

PowerShell: get-balance $checkbook
-43.56

And that is correct.

So all I need to do is tidy it up and save it in my profile, for now.

function get-balance ($checkbook) {
<#
.SYNOPSIS
Calculate the outstanding balance on an object representing the known balance and outstanding transations.

.DESCRIPTION
Assume that transation amounts with the payee of "balance" is positive and that other payees are to be subtracted from that value.

.PARAMETER month
Array of transactions.
#>
$total = 0
foreach ($a in $checkbook) {
if ($a.payee -eq "balance") { $total = $total + $a.amount }
else { $total = $total - $a.amount }
}
$total
}

set-alias gb get-balance


Next up: some housekeeping. I want to save these functions to their own script and set up a directory for this stuff.

After that, I will be saving the accounts as XML files. Hey, this stuff is no good if I have to enter it every time I want to enter things into my accounts.

Wednesday, December 7, 2011

Everything we need is here

I keep a spreadsheet with our (my wife's and mine) finances. Not super-detailed, just enough to keep track of where the money goes.

I don't mind spreadsheet programs, but there is a lot of mousing around - and I wonder if that's all that necessary. Then it occurred to me that PowerShell has the kinds of data types necessary to keep track of this without adding anything fundamental.

So, I'll see what something like that would look like.

We need a record. That is, every transaction needs to have a certain amount type of information. A hash table stores key value pairs. How about this:

PowerShell: $a = {month=0;day=0;payee=blank;amount=0;category=blank;year=0000}

PowerShell: $a

month=0;day=0;payee=blank;amount=0;category=blank;year=0000


Some design decisions:

Why month and day instead of a date object? Seems like overkill. I guess I can implement it with date objects later.

Why is the year last? I plan on using default values, so that will only have to be set once per year.

So, let's make a function out of this:

PowerShell: function new-transaction ($month = 0, $day=0, $payee="blank", $amount=0, $cat="blank", $year=2011)

>> {


>> @{month=$month;day=$day;payee=$payee;amount=$amount;cat=$cat;year=$year}


>> }


>>



And how does it work?

PowerShell: $a = new-transaction

PowerShell: $a



Name Value


---- -----


year 2011


payee blank


amount 0


cat blank


month 0


day 0




PowerShell: $a = new-transaction 12 8 test 4.35 groceries

PowerShell: $a



Name Value


---- -----


year 2011


payee test


amount 4.35


cat groceries


month 12


day 8


And now this needs to live in a script file - my profile, for now.

Here's what I put in:

function new-transaction ($month = 0, $day=0, $payee="blank", $amount=0, $cat="blank", $year=2011)


{


<#


.SYNOPSIS


Create a new transaction hash table.




.DESCRIPTION


Creates a new hash table with vaues for required parameters. Default values are
provided.




.PARAMETER month


Month from 1-12. No verification




.PARAMETER day


Day from 1-31. No verification.




.PARAMETER payee


Payee string.




.PARAMETER amount


Amount.




.PARAMETER cat


Spending category.




.PARAMETER year


Year.


#>







@{month=$month;day=$day;payee=$payee;amount=$amount;cat=$cat;year=$year}



}



set-alias nt new-transaction



Yes, I wrote help for my function - you should, too.

Here's what the output looks like:


PowerShell: nt




Name Value


---- -----


year 2011


payee blank


amount 0


cat blank


month 0


day 0




PowerShell: get-help nt



NAME


new-transaction




SYNOPSIS


Create a new transaction hash table.






SYNTAX


new-transaction [[-month] Object>] [[-day] Object>] [[-payee]
Object>] [[-amount] Object>] [[-cat] Object>] [[

-year] Object>] []




DESCRIPTION

Creates a new hash table with vaues for required parameters. Default values are provided.




RELATED LINKS



REMARKS


To see the examples, type: "get-help new-transaction -examples".


For more information, type: "get-help new-transaction -detailed".


For technical information, type: "get-help new-transaction -full".





PowerShell:



Next up: Put the transaction records into an array.

Tuesday, August 30, 2011

CQ Simulation: Fixing the HasAbandoned Problem

So, I've been struggling with some code for the last couple of weeks. My problem was that I was using a foreach loop in a context where the contents of the loop might change the iteration list.

Because foreach loops do not guarantee the order in which things are done, it's not valid to have the list change halfway though.

My solution – or hack – was to assign each member of the list that matched a certain criterion – the “has abandoned” method – to a second list and then cycle through the second list, deleting items from the first list.

Here's the code:


private List[LESSTHAN]DataUser[GREATERTHAN] tempList;

...

public void tick()

{


...

foreach (DataUser a in computerQueue) {

a.tick(simTick, results);

if (a.hasAbandoned(simTick))

{

tempList.Add(a);

}

}


...

foreach (DataUser d in tempList)

{

computerQueue.Remove(d);

}


As I implied, it seems like a hack to me.

The real problem, I suppose, is that I used C# lists which don't play nicely with foreach in these circumstances.

But I don't want to re-architect the thing, so let's leave well enough alone and go back to working on the program.

Tuesday, August 23, 2011

CQ Simulation: More Tests 2

More method tests today.

I wanted to make sure that these tests are testing the methods themselves, without mixing up the different things to be tested. This means some of these are quite boring:


# Test the timeLeft method


$testSeat = new Seat(60)

if (!($testSeat.timeLeft())) {"FAIL: Time Left should be true."}


Well, maybe there's more later, but for now, next: DataUser constructor:


# queue up time, patience time, desired time.

$testDataUser = new DataUser(1, 2, 3)


And now for 0 values:


$testDataUser = new DataUser(0, 0, 0)

This one caused an exception. Just one problem – well, look at the code:


if (queueUpTime [LESSTHAN] 0) { throw new Exception(); }

if (patienceTime [LESSTHAN] 0) { throw new Exception(); }

if (desiredTime [LESSTHAN] 0) { throw new Exception(); }

Zero is not less than zero. Here – let's try something:


// if (queueUpTime [LESSTHAN] 0) { throw new Exception(); }

// if (patienceTime [LESSTHAN] 0) { throw new Exception(); }

// if (desiredTime [LESSTHAN] 0) { throw new Exception(); }

Same error:

New-Object : Exception calling ".ctor" with "3" argument(s): "Exception of type 'System.Exception' was thrown."

I suspected as much. It seems there is another place in the code that is throwing this exception.

Oh, I was looking at the wrong place in the code. Here's the code for verifying the constructor:

if (X_queueUpTime [LESSTHAN] 0) { throw new Exception(); }

if (X_patienceTime [LESSTHAN] 1) { throw new Exception(); }

if (X_desiredTime [LESSTHAN] 1) { throw new Exception(); }

So, let's make this into an expected fail and we're done.

try {

$testDataUser = new DataUser(0, 0, 1)

"FAIL: Accepting input outside acceptable range."

} catch {}


try {

$testDataUser = new DataUser(0, 1, 0)

"FAIL: Accepting input outside acceptable range."

} catch {}

More next time.


Monday, August 22, 2011

CQ Simulation: Revising and Extending Tests

Over the last couple of weeks, I've letting coding get ahead of testing. The point of this methodology – with testing proceeding at the same time as coding – is to let the testing inform the coding.

I've decided to get back to it. I'm going to make sure I have tests for each method and constructor. I'm also going to make sure they are in files that are clearly named and have enough comments to follow the intent.

For instance, here is ClassSeatConstructor.ps1:

# Testing Seat Constructor

#

#

# Expected success:


$testSeat = new Seat(60)



# Test the Free property: On creation, should be Free.


$testSeat.Free = $true

if (!($testSeat.Free)) {"FAIL: Free should be True."}


$testSeat.Free = $false

if ($testSeat.Free) {"FAIL: Free should be False."}



# unacceptable values: 0, -1



try {

$testSeat = new Seat(0)

"FAIL: Invalid value did not cause exception."

}

catch {}

try {

$testSeat = new Seat(-1)

"FAIL: Invalid value did not cause exception."

}

catch {}


This script verifies that the constructor works. The initial state of the object has Free = True.

Then it tests to see that two unacceptable values are not permitted.

That test relies on testing code, so I should note that in the script.

What this test doesn't do is verify that the initial value is assigned. That will involve more testing code:

public int getUseTime()

{

return useTime;

}


And the test:

#verify initial state:

#USES TESTING CODE


$testSeat = new Seat(20)

if (!($testSeat.getUseTime() -eq 20)) {"FAIL: Initial state of Seat object should be 20."}


One down, 16 to go.