Cash Talks - BS Walks RSS 2.0
# Saturday, 22 March 2008

Buck Hodges' VSTS 2005 and 2008: Building Database Projects with Team Build

While this is specifically about Team Build, it applies to any kind of automated build process using MSBuild.  We're still using CCNet as our primary Build engine but Team Build is looking more appealing with 2008.

Saturday, 22 March 2008 01:15:26 (GMT Standard Time, UTC+00:00)  #    Comments [37] -
Visual Studio | MSBuild
# Monday, 10 March 2008

In my previous blog entry, Easily setting Tags on Media Files using PowerShell, I described how to set the media tags used by common MP3 players.

The reason I had this need stemed from a frustration from RIPing Audio Books into MP3s.  For example, let's say I'm compressing a 10 CD book.  Even with "good" audio naming from Internet Naming sources, you get 10 different albums with numberd tracks from 1 to whatever.  Sometimes the naming fixes this and sometimes it does a miserable job.  Copying and renaming the files doesn't do the job.  When you RIP the CD the encoder creates Meta Tags Used by MP3 players.

When your favorite tool is a hammer...

I didn't even look for a tool to solve this problem so if there is one... that's not really the point.  I was curious if I could solve it very easily using Powershell.  This is what I want:

  • Copy all files to a single directory
  • Name all files with some base name with a Zero padded count.
  • Provide for a flexible means for setting Tags on all Files.  For example, Author
  • Set the Album Tag so all files will appear as a single album
  • Set Meta Track number to coorespond the the Count and Title to the Filename

When I RIP the CDs it easy to get them all under a single directory and organize the directories Alphabetically so the CDs are in order.  The individually named where they also sort alphabetically.  As such the following line will return all MP3s under a directory in the order they should be played:

dir -Recurse -Filter *.mp3

As such, I need a CmdLet where I can pipe these.  This CmdLet will also take an Array parameter if that is your preference.

function Copy-NumberFile
 
( [
system.IO.FileInfo] $file=$(Throw "File is required"
)
 
, [string] $BaseName=$(Throw "BaseName is required"
)
  ,
$DestDir=$(Throw "DestDir is required"
)
  , [
int] $Count=$(Throw "Count is required"
)
  , [
int] $Digits=
1
  , [
switch]
$Verbose
 
, [switch]
$PassThru
 
)
{
 
$nbrStr = "{0:d$Digits}" -f
$Count
 
$NewName =
"$($BaseName)$($nbrStr)$($file.Extension)"
 
$NewFileName = [System.IO.Path]::Combine($DestDir.FullName,$NewName
)
 
if ($Verbose
)
  {
   
Write-Host
"Copy $($file.fullname) to $NewFileName"
 
}
  
Copy-Item $file.FullName -Destination $NewFileName -PassThru:
$PassThru
}

Function
Organize-AudioBookFiles 
 
( [
System.IO.DirectoryInfo]
$DestDir
 
, [hashtable]
$Tags
 
, [string]
$BaseName
 
, [int]$CountStart=
1
  ,
$Digits=-
1
  , [
array]$Files
)
{
 
begin
 
{
    [
array] $fileList =
$null
   
function AddFile( $FileToCheck
)
    {
     
if ($fileToCheck -ne $null
)
      {
        [
system.IO.FileInfo] $file =
$FileToCheck
       
if (!$file.Exists) { Throw "File does Not Exist"
}
       
$file
     
}
    }
    
    if (!$DestDir.Exists
)
    {
      $DestDir.Create
()
    }
    
if ((dir $DestDir.FullName | Measure-Object).Count -gt
0)
    {
     
Throw
"Destination Directory $($DestDir.FullName) is not empty"
    
}
   
foreach ($file in $files
)
    {
     
$fileList += AddFile($file

    }
  }
 
 
process
 
{
   
$fileList += AddFile($_
)
  }

  end
 
{
    $Count =
$CountStart
    
if ($digits -lt
0)
    {
      [
int]$Digits = [System.Math]::Truncate(([System.Math]::Log10($fileList.Count + $Count)))+
1
    }
   
foreach ($file in $fileList
)
    {
     
$file = Copy-NumberFile -file $file -DestDir $DestDir -BaseName $BaseName
`
       
-Digits $digits -Count ($Count) -Verbose
-PassThru
     
$filename = $file.
Name
     
$Tags.Track =
$Count
     
$Tags.Title = $filename.Substring(0,($filename.length-$file.extension.length
))
     
SetMedia-Tags -file $file -Tags
$Tags
     
$Count
++
   
}
  }
}

I have a helper function "Copy-NumberFile".  While I'm not sure if I'll ever need it in another operation, I can imagine it.  It copies a file to a Destination Directory, renames it with a BaseName followed by a Number and preserving the extension.  The number of Zero padded digits is specified in the $Digits parameter.  The $PassThru allows the caller to get the FileInfo for the created file.

An example usage might look like:

$Tags = @{Artists="Book Author";Album="Book Title";Comment="This is a comment";Genres=@("Fiction")}
$files = dir -Recurse -Filter *.mp3
Organize-AudioBookFiles -Files $files -DestDir "C:\temp\Book" -BaseName "BookName " -Tags $Tags

Monday, 10 March 2008 02:27:18 (GMT Standard Time, UTC+00:00)  #    Comments [42] -
Powershell

This weekend I found the need to set the Media Meta Tags in MP3 files I have RIPed.  I found this Huddled Masses article for using the taglib-sharp library.  I find Hashtables as a convenient machine for passing Pthese kinds of adhoc Name\Value pairs.

[void] [Reflection.Assembly]::LoadFile(".\taglib-sharp.dll")

function SetMedia-Tags
 
( [System.IO.FileInfo] $File=$(Throw "File is required")
  , [
hashtable] $Tags=$(Throw "Tags are required"
))
{
  $media = [TagLib.File]::Create($file.FullName
)
  foreach ($tag in $Tags.keys
)
  {
    $media.Tag.$tag = $Tags[$tag
]
  }
  $media.Save
()
}

Example Usage:

$Tags = @{Artists="Max Headgroom";Album="Smoke";Comment="This is a comment";Genres=@("Crazy")}
SetMedia-Tags -File ".\file1.mp3" -Tags $Tags

I used this code in a more specific project for organizing Audio Book MP3s I'll describe in a subsequent post.

Monday, 10 March 2008 01:12:26 (GMT Standard Time, UTC+00:00)  #    Comments [36] -
Powershell
# Friday, 07 March 2008

One of the interesting things about having a blog is seeing what people are searching for when they navigate to an entry.  On at least a dozen occasions I've seen searches where people were obviously trying to invoke NAnt from PowerShell.  Because I've talked about both NAnt and PowerShell without speaking to this subject, they have been disappointed in what they've found in my blogs.  Indeed, when I've performed my own searches, I've noticed there isn't a lot of useful info on doing this subject.  Especially at detecting an error in the NAnt script.

This isn't the most comprehensive script but it does the basics:

function Invoke-NAnt ($NantFile,$target,[hashtable]$Properties)
{
  $sb = New-Object
"System.Text.StringBuilder"
 
if ($properties -ne $null)
  {
    foreach ($key in $Properties.Keys)
    {
      [void] $sb.Append( '"' + "-D:$key=$($Properties.$key)" + '" ' )
    }
  }
  
  nant "-f:$NantFile" $target $sb.ToString()

 
if (-not $?)
  {
    Throw
"Nant Failed"
 
}
}

Example Usage:

Invoke-NAnt Test.build "TestTarget" @{Test1="Value1";Test2="Value2"}

Test.Build contains:

<project>
  <
target name="TestTarget"
>
    <
echo message="Test1=${Test1}"
/>
    <
echo message="Test2=${Test2}"
/>
    <
fail message="This is a failure"
/>
  </
target
>
</
project>

Output looks like:

NAnt 0.85 (Build 0.85.2478.0; release; 10/14/2006)
Copyright (C) 2001-2006 Gerry Shaw
http://nant.sourceforge.net

Buildfile: file:///C:/Projects/PSNant/Test.build
Target framework: Microsoft .NET Framework 2.0
Target(s) specified: TestTarget

TestTarget:

     [echo] Test1=Value1
     [echo] Test2=Value2

BUILD FAILED

C:\Projects\PSNant\Test.build(6,6):
This is a failure

Total time: 0 seconds.

Nant Failed
At C:\Projects\PSNant\InvokeNant.PS1:19 char:10
+     Throw  <<<< "Nant Failed"

This particular script is designed to fail with the 'fail task'.  This is because I was having trouble detecting errors.

  if (-not $?)
  {
    Throw
"Nant Failed"
 
}

The $? variable is set to $true if the previous instruction succeeded.  As of yet, I'm not getting the actual failure message.  If someone can help with that, I'd appreciate it.

Other usage comments:

The $properties parameter takes a hash table that gets marshaled into -D:<propname>=<propvalue> line arguments. I find the syntax of @{Test1="Value1";Test2="Value2"} to be more natural for PowerShell.

This function will return an array of text lines which are the output from NAnt.  If you don't want them to pipe out you'll need to assign it to a variable or [void] it.

$NantOutput = Invoke-NAnt Test.build "TestTarget" @{Test1="Value1";Test2="Value2"}

Finally:  Obviously this needs to be dressed out a little more for supporting some useful parameters to NAnt like Logger and Default Framework. 

Friday, 07 March 2008 23:26:48 (GMT Standard Time, UTC+00:00)  #    Comments [1] -
Powershell
# Sunday, 24 February 2008

Good writeup on installing Ubuntu 7.10 on Virtual PC.  However, it hung for me right after the first screen with two different ISO downloads.  I was trying this at home on my AMD Vista Laptop.  Some comments on the page makes me suspicious that I'll need use my Virtual Server at work.

Update:

With an RDP connection to an XP system at work I was able to get the Ubuntu to install.  I'll conclude, for now, there is some issue with VPC on Vista.

The mouse continued to be flaky but it could be the system within system within system connection I was using.  I'm on a Vista laptop with a touchpad, running an XP VPC with VPN RDP connection to an XP System running the Ubuntu VPC! Now why can't my mouse work?! :)

I guess on Monday I'll see how well the mouse works when I can get direct access to the VPC.  Next hurdle... get it on the network.  Then to see if I can Admin the thing through Powershell!

Sunday, 24 February 2008 01:33:58 (GMT Standard Time, UTC+00:00)  #    Comments [32] -
Virtual Linux
# Saturday, 23 February 2008

I'm in the initial stages of attempting to control Linux servers from Windows using PowerShell.

The obvious path is using SSH.  The question is how.  Unfortunately with all the buzz around PowerShell Remoting, what I'm finding is a lot of the reverse... accessing PowerShell through SSH.  The reciprocity of this may make the reverse true but I haven't found the confirmation link yet.

The long way around the block might be through Cygwin and Putty.  The link is a little old but it shows a way.  I'm hoping for a direct path from PowerShell so I can minimize installation dependencies.

Update:

NetCmdlets is the "almost" direct path.  It looks good but too pricy for the way I want use it.  Besides, it's "just" a wrapper for rsh.exe.  Looks like I'll be attempting my own wrapper.  Anyone else try to do this?

Saturday, 23 February 2008 05:11:47 (GMT Standard Time, UTC+00:00)  #    Comments [49] -
Powershell | Virtual Linux
# Monday, 18 February 2008

The other day I was given a hard drive and asked to analyze what was on it.  While it was easy to determine it had over 300,000 files and about 10 Gigs I didn’t want to navigate through the whole thing looking in the hundreds of folders.  I figured a good thing to know was the number of files and size by extension.

 

Powershell to the rescue.  After several iterations of various techniques I came up with a CmdLet allowing me to measure any kind of object.  You can specify which property to use as the Group and for measurement.  I’m not sure what else I’ll use it for, but I love making things generic.

 

function MeasureGroup-Object

  ( [string]$group=$(Throw "Group Name is Required")

  , [string]$property=$(Throw "Property Name is Required")

  , $items

  )

{

  begin

  {

    function processItem($item)

    {

      $key = $item.$group

     

      if ($Aggregate.$key -eq $null)

      {

        $Aggregate.$key = @{Count=0;Sum=0}

      }

      $Aggregate.$key.Count += 1

      $Aggregate.$key.Sum += $item.$property

    }

 

    # Hash table to collect stats

    $Aggregate = @{}

 

    if ($items -ne $null)

    {

      foreach ($item in $items)

      {

        processItem $item

      }

    }

  }

  process

  {

    if ($_ -ne $null)

    {

      processItem $_

    }

  }

  end

  {

    function AddProperty ($object,$name,$value)

    {

      $member = new-object management.automation.PSNoteProperty $name,$value

      $object.psobject.members.Add($member)

    }

 

    foreach ($key  in $Aggregate.Keys)

    {

      $obj = new-object management.automation.psobject

      AddProperty $obj $group $key

      AddProperty $obj Count $Aggregate.$key.Count

      AddProperty $obj Sum $Aggregate.$key.Sum

      $obj

    }

  }

}

 

 

So let’s put it to work.  First you have to collect the objects you want to measure.

 

$files = Get-ChildItem -Recurse | where {$_ -is [System.IO.FileInfo]}

 

This will recursively collect all the files under the current directory.  It helps to filter out the Directories.  Because they don’t have Extensions, they would end up inflating the stats for files without extensions.

 

Now to use the MeasureGroup-Object.

 

$stats = MeasureGroup-Object Extension Length $files

 

The $stats variable will contain an array with an entry for each extension type.  Each entry will have an Extension, Count and Sum value.

 

The following will display the results but not in any particular order.

 

$stats

 

This will be more interesting.

 

# Get Top 5 file types by count

$stats | Sort-Object Count -Descending | Select-Object -First 5

 

Extension                Count                     Sum

---------                -----                     ---

.cs                        842                 3018481

.hxs                       765               980371275

.cab                       756              1801724080

.sql                       538                 6734980

.dll                       367                79635976

 

These are also interesting views.

 

# Get Top 5 file types by total Length

$stats | Sort-Object Sum -Descending | Select-Object -First 5

 

# Display all Extensions

$stats | Sort-Object Extension

 

Some comments about the implementation.

 

The End processing loops through the $Aggregate results and builds PSObjects with Note values.  The PSObjects play nice with the Sort, Select and default display.

 

Related Post: PowerShell Directory Size

Monday, 18 February 2008 00:57:25 (GMT Standard Time, UTC+00:00)  #    Comments [712] -
Powershell
# Sunday, 17 February 2008

This is a useful template for starting a CmdLet that needs to work in a PipeLine or by passing parameters.

 

Processing is implemented in the processItem sub-function.  All the “–ne $null” conditions handle the differences between pipeline and parameter invocation.

 

function Test-PipelineOrParm ($parm)

{

  begin

  {

    function processItem($item)

    {

      # Implement processing in this function

      "processItem $item"

    }

   

    if ($parm -ne $null)

    {

      foreach ($item in $parm)

      {

        "begin $(processItem $item)"

      }

    }

  }

  process

  {

    if ($_ -ne $null)

    {

      "process $(processItem $_)"

    }

  }

  end

  {

    Write-Host "Done"

  }

}

 

These two examples demonstrate calling the template.

 

Write-Host "Test Pipeline processing"

Get-ChildItem | Test-PipelineOrParm

 

Write-Host "Test Parm processing"

Test-PipelineOrParm $(Get-ChildItem)

 

Sunday, 17 February 2008 23:26:38 (GMT Standard Time, UTC+00:00)  #    Comments [76] -
Powershell

The past few weeks I’ve been working on a Powershell OO scripting framework.  I figure I better go ahead and publish it because I could keep tinkering on it for a long time.  I suspect it’s not done and even has a bug or two but it’s in decent shape.  While this is not “real” Object Oriented it does support:

 

·         Polymorphism

·         Encapsulation

·         Constructors with parameters

·         Notes – read-write variables

·         Methods – scriptblocks

·         Properties with Get scriptblocks and optional Set scriptblocks

·         Static and Private Notes and Methods

 

The New-PSClass cmdlet takes a script which acts as Class Definition.  Keywords note, method, property and constructor are local functions in New-PSClass and act as Class Definition by attaching objects to a PSClass Object returned by the CmdLet.

 

The PSClass has a New() method.  Parameters to New are passed to the constructor script.  Due to a bug in V1.0 of PowerShell, the Param statement does not work in the scriptblocks in PSClass.  While I have not tried it yet, I have good reason to believe that it will work in V2.0.  While it’s not as nice, the $Args variable works fine.

 

Instead of trying to describe all the syntax as small points in the blog entry, I’ll present an example Animal Class with a Dog and Bird Classes that inherit from it.  While looking through it take note of:

·         Private Notes use a –private switch.  Within the class, scripts access them through a $private variable.  Encapsulatioen isolates them from inherited classes and easy public access.

·         Static Notes and Methods are attached to the PSClass object.  This example shows a Static Note accessed in the Constructors.  This may seem non-intuitive considering the Class Object used in the Constructor is not created until New-PSClass is completed.   This is because the constructor script is not executed until an action Object is created using the New() method.

·         While not demonstrated, private methods are supported and attached to the $private variable available in script execution.

·         Note the use the –override switch on the ToString() method on the Dog Class.  It can call methods on the base class through Invoke-BaseClassMethod

·         Base function in constructors to call inherited constructors

 

 

$AnimalClass = New-PSClass Animal {

 

  note -static ObjectCount 0

  method -static DisplayObjectCount {

    "$($this.ClassName) has $($this.ObjectCount) instances"

  }

 

  note -private Name

  note -private Legs

 

  constructor {

    $private.Name = $Args[0]

    $private.Legs = $Args[1]

   

    $AnimalClass.ObjectCount += 1

  }

 

  property Name {

    $private.Name

  } -set {

    Write-Host "Renaming $($this.Class.ClassName) '$($private.Name)' to '$($Args[0])'"

    $private.Name = $Args[0]

  }

 

  property Legs {

    $private.Legs

  }

 

  method -override ToString {

    "A $($this.Class.ClassName) named $($this.name) with $($this.Legs) Legs"

  }

 

  method Speak {

    Throw "not implemented"

  }

}

 

$DogClass = New-PSClass -inherit $AnimalClass Dog {

  note -static ObjectCount 0

  method -static DisplayObjectCount {

    "$($this.ClassName) has $($this.ObjectCount) instances"

  }

 

  constructor {

    Base $Args[0] 4  

 

    $DogClass.ObjectCount += 1

  }

 

  method -override ToString  {

    "$(Invoke-BaseClassMethod 'ToString') with extra"

  }

 

  method -override Speak {

    "Arf"

  }

}

 

$BirdClass = New-PSClass -inherit $AnimalClass Bird {

  note -static ObjectCount 0

  method -static DisplayObjectCount {

    "$($this.ClassName) has $($this.ObjectCount) instances"

  }

 

  constructor {

    Base $Args[0] 2 

 

    $BirdClass.ObjectCount += 1

  }

 

  method -override Speak {

    "Squawk"

  }

}

 

$Dog = $DogClass.New("Bowser")

$Dog.ToString()

$Dog.Name = "Duke"

$Dog.ToString()

$Dog.Speak()

 

$Bird = $BirdClass.New("Tweedy")

$Bird.ToString()

$Bird.Speak()

 

$DogClass.DisplayObjectCount()

$BirdClass.DisplayObjectCount()

$AnimalClass.DisplayObjectCount()

 

Output:

A Dog named Bowser with 4 Legs with extra

Renaming Dog 'Bowser' to 'Duke'

A Dog named Duke with 4 Legs with extra

Arf

A Bird named Tweedy with 2 Legs

Squawk

Dog has 1 instances

Bird has 1 instances

Animal has 2 instances

 

The cool thing about the implementation is it’s all in PowerShell.  It’s a big chunk of code and I’m sure it’s not its final version, but it has a lot of cool techniques and some that should be fixed up.  Also, I’ve been working on an XMS Serialization, Attribute support, and the ability to attach PSClass objects to any PowerShell object.

 

These PowerShell Scripts are in the attached zip file.

 

# ===================================================================================

# New-PSClass

#     Object Oriented Scripting in Powershell

#     http://www.cashfoley.com/

# ===================================================================================

# Inspired by Bruce Payette's "Windows PowerShell in Action"

# Chapter 8 Script to add a CustomClass "keyword" to PowerShell

# http://manning.com/payette/

# ===================================================================================

 

function New-PSClass

  ( [string] $ClassName = { Throw "ClassName required for New-PSClass"}

  , [scriptblock] $definition = { Throw "Definition required for New-PSClass"}

  , $Inherit

  )

 

{

  #======================================================================

  # These Subfunctions are used in Class Definition Scripts

  #======================================================================

 

  # - - - - - - - - - - - - - - - - - - - - - - - -

  # Subfunction: constructor

  #   Assigns Constructor script to Class

  # - - - - - - - - - - - - - - - - - - - - - - - -

  function constructor ( [scriptblock] $script=$(Throw "Script is required for 'constructor'"))

  {

    if ($class.ConstructorScript)

    {

      Throw "Only one Constructor is allowed"

    }

    $class.ConstructorScript = $script

  }

 

  # - - - - - - - - - - - - - - - - - - - - - - - -

  # Subfunction: note

  #   Adds Notes record to class if non-static

  # - - - - - - - - - - - - - - - - - - - - - - - -

  function note

  {

    param ( [string]$name={Throw "Note Name is Required"}

          , $value=""

          , [switch] $private

          , [switch] $static

          )

   

    if ($static)

    {

      if ($private)

      {

          Throw "Private Static Notes are not supported"

      }

      Attach-PSNote $class $name $value

    }

    else

    {

      $class.Notes += @{Name=$name;DefaultValue=$value;Private=$private}

    }

  }

 

  # - - - - - - - - - - - - - - - - - - - - - - - -

  # Subfunction: method

  #   Add a method script to Class definition or

  #   attaches it to the Class if it is static

  # - - - - - - - - - - - - - - - - - - - - - - - -

  function method ([string]$name=$(Throw "Name is required for 'method'"), [scriptblock] $script=$(Throw "Script is required for 'method'"), [switch] $static, [switch]$private, [switch]$override )

  {

    if ($static)

    {

      if ($private)

      {

          Throw "Private Static Methods not supported"

      }

      Attach-PSScriptMethod $class $name $script

    }

    else

    {

      $class.Methods[$name] = @{Name=$name;Script=$script;Private=$private;Override=$override}

    }

  }

 

  # - - - - - - - - - - - - - - - - - - - - - - - -

  # Subfunction: property

  #   Add a property to Class definition or

  #   attaches it to the Class if it is static

  # - - - - - - - - - - - - - - - - - - - - - - - -

  function property ([string]$name, [scriptblock] $get=$(Throw "Get Script is required for 'property'"), [scriptblock] $set, [switch] $static, [switch]$private, [switch]$override )

  {

    if ($static)

    {

      if ($private)

      {

          Throw "Private Static Properties not supported"

      }

      Attach-PSProperty $class $name $get $set

    }

    else

    {

      $class.Properties[$name] = @{Name=$name;GetScript=$get;SetScript=$set;Private=$private;Override=$override}

    }

  }

 

  $class = new-object Management.Automation.PSObject

 

  # Class Internals

  Attach-PSNote $class ClassName $ClassName

  Attach-PSNote $class Notes @()

  Attach-PSNote $class Methods @{}

  Attach-PSNote $class Properties @{}

  Attach-PSNote $class BaseClass $Inherit

  Attach-PSNote $class ConstructorScript

  Attach-PSNote $class PrivateName "__$($ClassName)_Private"

 

  Attach-PSScriptMethod $class New {

    $instance = new-object Management.Automation.PSObject

 

    $this.AttachObject( $instance

    $this.Initialize( $instance, $Args )

   

    $instance

  }

 

  Attach-PSScriptMethod $class Initialize {

    if ($this.ConstructorScript -ne $null)

    {

      __PSClass-Initialize $Args[0] $Args[1]

    }

  }

 

  Attach-PSScriptMethod $class AttachObject {

    __PSClass-AttachObject $Args[0]

  }

 

  Attach-PSScriptMethod $class __LookupClassObject {

    __PSClass-LookupClassObject $Args[0] $Args[1]

  }

 

  Attach-PSScriptMethod $class InvokeMethod {

    __PSClass-InvokeMethod $Args[0] $Args[1] $Args[2]

  }

 

  Attach-PSScriptMethod $class InvokeProperty {

    __PSClass-InvokePropertyMethod $Args[0] $Args[1] $Args[2] $Args[3]

  }

 

  # At last, execute definition script

  &$definition

 

  # return constructed class

  $class

}

 

# ===================================================================================

# These helper Cmdlets should only be called by New-PSClass.  They exist to reduce

# the amount of code attached to each PSClass object.  They rely on context

# variables not passed as parameters.

# ===================================================================================

# __PSClass-Initialize

#    Invokes Constructor Script and provides helper Base function to facilitate

#    Inherited Constructors

# ===================================================================================

function __PSClass-Initialize ($instance, $params)

{

  function Base

  {

    if ($this.Class.BaseClass -eq $null)

    {

      Throw "No BaseClass implemented for $($this.Class.ClassName)"

    }

    $this.Class.BaseClass.Initialize($this,$Args)

  }

 

  trap {

    $errorMsg = $_.Exception.Message + $_.Exception.ErrorRecord.InvocationInfo.PositionMessage

    Throw $errorMsg

    $_.ErrorDetails = $_.Exception.ErrorRecord.InvocationInfo.PositionMessage

  }

 

  $constructor = $this.ConstructorScript

 

  $private = $Instance.($this.privateName)

  $this = $instance

 

  $constructor.InvokeReturnAsIs( $params )

}

 

# ===================================================================================

# __PSClass-AttachObject

#    Attaches Notes, Methods, and Properties to Instance Object

# ===================================================================================

function __PSClass-AttachObject ($instance)

{

  function AssurePrivate

  {

    if ($instance.($this.privateName) -eq $null)

    {

      Attach-PSNote $instance ($this.privateName) (new-object Management.Automation.PSObject)

      Attach-PSNote $instance.($this.privateName) __Parent $instance

    }

  }

 

  # - - - - - - - - - - - - - - - - - - - - - - - -

  #  Attach BaseClass

  # - - - - - - - - - - - - - - - - - - - - - - - -

  if ($this.BaseClass -ne $null)

  {

    $this.BaseClass.AttachObject($instance)

  }

 

  Attach-PSNote $instance Class $this

 

  # - - - - - - - - - - - - - - - - - - - - - - - -

  #  Attach Notes

  # - - - - - - - - - - - - - - - - - - - - - - - -

  foreach ($note in $this.Notes)

  {

    if ($note.private)

    {

      AssurePrivate

      Attach-PSNote $instance.($this.privateName) $note.Name $note.DefaultValue

    }

    else

    {

      Attach-PSNote $instance $note.Name $note.DefaultValue

    }

  }

 

  # - - - - - - - - - - - - - - - - - - - - - - - -

  #  Attach Methods

  # - - - - - - - - - - - - - - - - - - - - - - - -

  foreach ($key in $this.Methods.keys)

  {

    $method = $this.Methods[$key]

    $targetObject = $instance

 

    # Private Methods are attached to the Private Object.

    # However, when the script gets invoked, $this needs to be

    # pointing to the instance object. $ObjectString resolves

    # this for InvokeMethod

    if ($method.private)

    {

        AssurePrivate

        $targetObject = $instance.($this.privateName)

        $ObjectString = '$this.__Parent'

    }

    else

    {

        $targetObject = $instance

        $ObjectString = '$this'

    }

 

    # The actual script is not attached to the object.  The Script attached to Object calls

    # InvokeMethod on the Class.  It looks up the script and executes it

    $instanceScriptText = $ObjectString + '.Class.InvokeMethod( "' + $method.name + '", ' + $ObjectString + ', $Args )'

    $instanceScript = $ExecutionContext.InvokeCommand.NewScriptBlock( $instanceScriptText )

 

    Attach-PSScriptMethod $targetObject $method.Name $instanceScript  -override:$method.override

  }

 

  # - - - - - - - - - - - - - - - - - - - - - - - -

  #  Attach Properties

  # - - - - - - - - - - - - - - - - - - - - - - - -

  foreach ($key in $this.Properties.keys)

  {

    $Property = $this.Properties[$key]

    $targetObject = $instance

 

    # Private Properties are attached to the Private Object.

    # However, when the script gets invoked, $this needs to be

    # pointing to the instance object. $ObjectString resolves

    # this for InvokeMethod

    if ($Property.private)

    {

      AssurePrivate

      $targetObject = $instance.($this.privateName)

      $ObjectString = '$this.__Parent'

    }

    else

    {

      $targetObject = $instance

      $ObjectString = '$this'

    }

 

    # The actual script is not attached to the object.  The Script attached to Object calls

    # InvokeMethod on the Class.  It looks up the script and executes it

    $instanceScriptText = $ObjectString + '.Class.InvokeProperty( "GET", "' + $Property.name + '", ' + $ObjectString + ', $Args )'

    $getScript = $ExecutionContext.InvokeCommand.NewScriptBlock( $instanceScriptText )

 

    if ($Property.SetScript -ne $null)

    {

      $instanceScriptText = $ObjectString + '.Class.InvokeProperty( "SET", "' + $Property.name + '", ' + $ObjectString + ', $Args )'

      $setScript = $ExecutionContext.InvokeCommand.NewScriptBlock( $instanceScriptText )

    }

    else

    {

      $setScript = $null

    }

 

    Attach-PSProperty $targetObject $Property.Name $getScript $setScript -override:$Property.override

  }

}

 

# ===================================================================================

# __PSClass-LookupClassObject

#   intended to look up methods and property objects on the Class.  However,

#   it can be used to look up any Hash Table entry on the class.

#

#   if the object is not found on the instance class, it searches all Base Classes

#  

#   $ObjectType is the HashTable Member

#   $ObjectName is the HashTable Key

#

#   it returns the Class and Hashtable entry it was found in

# ===================================================================================

function __PSClass-LookupClassObject ($ObjectType, $ObjectName)

{

  $object = $this.$ObjectType[$ObjectName]

  if ($object -ne $null)

  {

    $this

    $object

  }

  else

  {

    if ($this.BaseClass -ne $null)

    {

      $this.BaseClass.__LookupClassObject($ObjectType, $ObjectName)

    }

  }

}

 

# ===================================================================================

# __PSClass-InvokeScript

#   Used to invoke Method and Property scripts

#     It adds an error handler so Script Info can be seen in the error

#     It marshals $this and $private variables for the context of the script

#     It provides a helper Invoke-BaseClassMethod for invoking base class methods

# ===================================================================================

function __PSClass-InvokeScript ($class, $script, $object, $parms )

{

  function Invoke-BaseClassMethod ($methodName, $parms)

  {

              if ($this.Class.BaseClass -eq $null)

              {

                     Throw "$($this.Class.ClassName) does not have a BaseClass"

              }

              $class,$method = $this.Class.BaseClass.__LookupClassObject('Methods', $MethodName)

   

    if ($method -eq $null)

    {

      Throw "Method $MethodName not defined for $className"

    }

    __PSClass-InvokeScript $class $method.Script $this $parms

  }

 

  trap {

      $errorMsg = $_.Exception.Message + $_.Exception.ErrorRecord.InvocationInfo.PositionMessage

      Throw $errorMsg

      $_.ErrorDetails = $_.Exception.ErrorRecord.InvocationInfo.PositionMessage

  }

 

  $this = $object

  $private = $this.($Class.privateName)

 

  $script.InvokeReturnAsIs( $parms )

}

 

# ===================================================================================

# __PSClass-InvokeMethod

#   Script called by methods attached to instances.  Looks up Method Script

#   in instance class or in inherited class

# ===================================================================================

function __PSClass-InvokeMethod($MethodName, $instance, $parms)

{

  $class,$method = $this.__LookupClassObject('Methods', $MethodName)

 

  if ($method -eq $null)

  {

      Throw "Method $MethodName not defined for $($this.ClassName)"

  }

 

  __PSClass-InvokeScript $class $method.Script $instance $parms

}

 

# ===================================================================================

# __PSClass-InvokePropertyMethod

#   Script called by property scripts attached to instances.  Looks up property Script

#   in instance class or in inherited class

# ===================================================================================

function __PSClass-InvokePropertyMethod ($PropertyType, $PropertyName, $instance, $parms)

{

  $class,$property = $this.__LookupClassObject('Properties', $PropertyName)

 

  if ($property -eq $null)

  {

    Throw "Property $PropertyName not defined for $($this.ClassName)"

  }

 

  if ($PropertyType -eq "GET")

  {

    __PSClass-InvokeScript $class $property.GetScript $instance $parms

  }

  else

  {

    __PSClass-InvokeScript $class $property.SetScript $instance $parms

  }

}

 

# ===================================================================================

function Attach-PSNote

{

  param ( [PSObject]$object=$(Throw "Object is required")

        , [string]$name=$(Throw "Note Name is Required")

        , $value

        )

 

  if (! $object.psobject.members[$name])

  {

    $member = new-object management.automation.PSNoteProperty `

          $name,$value

   

    $object.psobject.members.Add($member)

  }

  else

  {

    if($value)

    {

      $object.$name = $value

    }

  }

}

 

# ===================================================================================

function Attach-PSScriptMethod

{

  param ( [PSObject]$object=$(Throw "Object is required")

        , [string]$name=$(Throw "Method Name is Required")

        , [scriptblock] $script

        , [switch] $override

        )

 

  $member = new-object management.automation.PSScriptMethod `

      $name,$script

 

  if ($object.psobject.members[$name] -ne $null)

  {

    if ($override)

    {

      $object.psobject.members.Remove($name)

    }

    else

    {

      Throw "Method '$name' already exists with out 'override'"

    }

  }

 

  $object.psobject.members.Add($member)

}

 

# ===================================================================================

function Attach-PSProperty

{

  param ( [PSObject]$object=$(Throw "Object is required")

        , [string]$name=$(Throw "Method Name is Required")

        , [scriptblock] $get=$(Throw "get script is required")

        , [scriptblock] $set

        , [switch] $override

        )

  if ($set)

  {

    $scriptProperty = new-object management.automation.PsScriptProperty `

      $name,$get,$set

  }   

  else

  {

    $scriptProperty = new-object management.automation.PsScriptProperty `

      $name,$get

  }   

 

  if ( $object.psobject.properties[$name] -and $override)

  {

    $object.psobject.properties.Remove($name)

  }

 

  $object.psobject.properties.add($scriptProperty)

}

PSClass.zip (4.24 KB)
Sunday, 17 February 2008 20:19:52 (GMT Standard Time, UTC+00:00)  #    Comments [0] -
Powershell
# Thursday, 17 January 2008

Last year I was contacted by Brian Bagnall, the author of "On the Edge: The Spectacular Rise and Fall of Commodore" about the founding of MicroGraphicImage.  The following is the synopsis I sent him.

MicroGraphicImage was started by former employees of a company called "Games By Apollo".  It had been among the companies that had pumped out fairly crummy games for the Atari 2600.  Companies like GPA, overproduced games creating a glut of cheap games.  In the pre-Christmas market of 1982 the company became filed for Chapter 11 Bankruptcy.  Unfortunately, they had a lot of really good games in the works for a number of platforms, including the Atari 800/400.  I had been one of the lead developers on the 800 platform and Tim Martin had been on the Atari 2600.
 
When GPA went broke, Tim Martin and another ex-GPA 2600 developer, Robert Barber, developed a game entitled "Halloween" based on the infamous movie.  The contract funded the founding of MicroGraphicImage(MGI).  Unfortunately, the company holding the rights to Halloween went bankrupt in the video game depression of 1982-83.  This was a shame because the game was really very good considering the restrictions of the the Atari 2600 and was ahead of its time in content and usage of the Halloween theme music.
 
Tim and Robert's expertise was with the Atari 2600.  Furthermore they were dis-satisfied with kind of money being made through contract game development.  Their strategy was to utilize the contract programming to leverage the funding of a Software Publishing company.  The brought me in as technical specialist with Atari and Apple computer programming.  We went to the January '83 CES in Las Vegas.  It was there we developed a relationship with Gary Carlson, one of the founding brothers of Broderbund.  BTW, Gary and Broderbund were the class act in an industry of quick con artists.
 
In early 1983 MGI developed games under contract for Broderbund, Parker Brothers, and CBS Electronics while developing Spelunker for ourselves.  Tim and Robert had been developing the game design for quite a while.  However, it was too ambitious for the Atari 2600.  Tim, Robert and myself co-developed the game.  Tim was responsible for "game logic", I developed the graphic engine and Game Level Editor, and Robert was the graphic designer and Level Editor.
 
Technically, it used the Atari Graphics Mode 4.  GM4 provided for 4+1 color characters.  This means a color character had 4 colors with a 5th alternate based on the high bit of the character.  The "Spelunker Dude", Bats, Ghosts and flares were done using Sprites.  Because two sprites were dedicated to the Dude, it left 2 sprites for the rest.  It took two sprites to make a 3 color image.  This is what we used for the Dude.  The remaining sprites made single color images.  The massive amount of screen movement (relative to the day) was done by animating the GM4 characters.  Sequencing changes to the character definitions provided for the instantaneous movement where ever the characters appeared on the screen.  Elevators, moving earth, and animated treasures were accomplished using this technique. The 5th color was the "deadly pink" that was so lethal to the Dude.  We used hardware sprite collision detection to trigger the quick death that would occur whenever contact was made.  The Atari 800 had a programmable graphics chip we exploited for the smooth scrolling of the large cavern.  This was critical for giving the sense of the "huge unknown".  Most games at the time flipped screens whenever a character ran off the side.
 
Robert Barber was a really talented game designer and was responsible for the Cavern layout and the look and feel of the graphics.  One of the things that added to the strength of Spelunker was the team development.  1983, most games were designed and developed by a single guy.  This explains why the graphics was frequently poor.  The guy who was great at writing extraordinary bit-twiddling wasn't necessarily a good artists.  The good artist wasn't necessarily a great game visionary.  With Spelunker, I was the bit-twiddler.  Tim and Robert were the game visionaries.  Today, it's not unusual to see a couple hundred contributors on a game. 

In 1983, all computer games had a "name" attached to it.  It was sort of a "rock star" mentality. Spelunker was Tim's original idea and programmed the game logic. When the game was released, we made a strategic decision to put Tim name out front.  Besides, we were all convinced this was the first of many games and we would all have our turn.  Unfortunately, the game recession that started in the winter of 82, only got worse.  It was very difficult to get game distributors to take games from small single game publishers.  Even though we were able to maintain a steady stream of contract work, the overhead of financial business focus going into publishing, we weren't able to make ends meet.
 
In 1984, we turned publication over to Broderbund and made the Commodore 64 version.  The C64 was very similar to the Atari.  In fact, very little had to be changed.  It had a Character Graphic mode compatible with the Atari GM1.  It had better Sprite and sound support but we didn't do much to exploit this.  It was primarily a "port".
 
At MGI, we loved the Atari and really didn't care much for the C64.  We always found it to be a bit ironic that the Atari had a reputation as a "Game Machine" and the C64 was a more serious computer.  From our perspective, the C64 had an edge when it came to sprites and sound.  However the Disk OS was really bad.  It couldn't even boot from a floppy!  Not only did the Atari have a much better Disk, but the OS was much more well rounded with multi-device support.  In short, the C64 was a better game machine and the Atari was a more serious computer!
 
Eventually, MGI ran out of money and closed its doors.  In didn't really go bankrupt, it simply stopped operation.  Tim continued working with Broderbund on a business level and was able recover all debt through the NES and Coin-op versions.
 
Tim and I continued to work together including an Amiga Publishing company by the name of Inovatronics.  Eventually, Tim was a founder of the Internet Provider, Internet America.  I'm still a bit twiddler and currently work at Perot Systems.

Thursday, 17 January 2008 13:56:47 (GMT Standard Time, UTC+00:00)  #    Comments [740] -
Personal
Archive
<2008 March>
SunMonTueWedThuFriSat
2425262728291
2345678
9101112131415
16171819202122
23242526272829
303112345
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2017
Cash Foley
Sign In
Statistics
Total Posts: 20
This Year: 0
This Month: 0
This Week: 0
Comments: 5993
Themes
Pick a theme:
All Content © 2017, Cash Foley
DasBlog theme 'Business' created by Christoph De Baene (delarou)