Downloads:

4,672

Downloads of v 2.0.0-alpha06:

293

Last Update:

18 Sep 2015

Package Maintainer(s):

Software Author(s):

  • Akira Sugiura

Tags:

tdd isolation mock mocks mocking fake fakes faking unittest unittesting

Prig: Open Source Alternative to Microsoft Fakes

This is a prerelease version of Prig: Open Source Alternative to Microsoft Fakes.

2.0.0-alpha06 | Updated: 18 Sep 2015

Downloads:

4,672

Downloads of v 2.0.0-alpha06:

293

Maintainer(s):

Software Author(s):

  • Akira Sugiura

Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha06

This is a prerelease version of Prig: Open Source Alternative to Microsoft Fakes.

All Checks are Unknown

2 Test of Unknown Status


Validation Testing Unknown


Verification Testing Unknown

To install Prig: Open Source Alternative to Microsoft Fakes, run the following command from the command line or from PowerShell:

>

To upgrade Prig: Open Source Alternative to Microsoft Fakes, run the following command from the command line or from PowerShell:

>

To uninstall Prig: Open Source Alternative to Microsoft Fakes, run the following command from the command line or from PowerShell:

>

NOTE: This applies to both open source and commercial editions of Chocolatey.

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

  • Open Source or Commercial:
    • Proxy Repository - Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://chocolatey.org/api/v2. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
    • You can also just download the package and push it to a repository Download

3. Enter your internal repository url

(this should look similar to https://chocolatey.org/api/v2)

4. Choose your deployment method:


choco upgrade prig -y --source="'STEP 3 URL'" [other options]

See options you can pass to upgrade.

See best practices for scripting.

Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.

If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:


choco upgrade prig -y --source="'STEP 3 URL'"
$exitCode = $LASTEXITCODE

Write-Verbose "Exit code was $exitCode"
$validExitCodes = @(0, 1605, 1614, 1641, 3010)
if ($validExitCodes -contains $exitCode) {
  Exit 0
}

Exit $exitCode

- name: Ensure prig installed
  win_chocolatey:
    name: prig
    state: present
    version: 2.0.0-alpha06
    source: STEP 3 URL

See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.

Coming early 2020! Central Managment Reporting available now! More information...


chocolatey_package 'prig' do
  action    :install
  version  '2.0.0-alpha06'
  source   'STEP 3 URL'
end

See docs at https://docs.chef.io/resource_chocolatey_package.html.


Chocolatey::Ensure-Package
(
    Name: prig,
    Version: 2.0.0-alpha06,
    Source: STEP 3 URL
);

Requires Otter Chocolatey Extension. See docs at https://inedo.com/den/otter/chocolatey.


cChocoPackageInstaller prig
{
   Name     = 'prig'
   Ensure   = 'Present'
   Version  = '2.0.0-alpha06'
   Source   = 'STEP 3 URL'
}

Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.


package { 'prig':
  provider => 'chocolatey',
  ensure   => '2.0.0-alpha06',
  source   => 'STEP 3 URL',
}

Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.


salt '*' chocolatey.install prig version="2.0.0-alpha06" source="STEP 3 URL"

See docs at https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.chocolatey.html.

5. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

This package is exempt from moderation. While it is likely safe for you, there is more risk involved.
Description

Prig(PRototyping jIG) is a framework that generates a Test Double like Microsoft Fakes/Typemock Isolator/Telerik JustMock based on Unmanaged Profiler APIs. This framework enables that any methods are replaced with mocks. For example, a static property, a private method, a non-virtual member and so on.


lib\Urasandesu.NAnonym.dll
 
lib\Urasandesu.Prig.Delegates.0404.dll
 
lib\Urasandesu.Prig.Delegates.0804.dll
 
lib\Urasandesu.Prig.Delegates.1205.dll
 
lib\Urasandesu.Prig.Delegates.dll
 
lib\Urasandesu.Prig.Framework.dll
 
tools\Add-PrigAssembly.ps1
# 
# File: Add-PrigAssembly.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

[CmdletBinding()]
param (
    [Parameter(Mandatory = $True)]
    [string]
    $ProjectFullName, 

    [Parameter(Mandatory = $True)]
    [string]
    $TargetFrameworkVersion, 

    [string]
    $Assembly, 

    [string]
    $AssemblyFrom
)

Write-Verbose ('ProjectFullName          : {0}' -f $ProjectFullName)
Write-Verbose ('TargetFrameworkVersion   : {0}' -f $TargetFrameworkVersion)
Write-Verbose ('Assembly                 : {0}' -f $Assembly)
Write-Verbose ('AssemblyFrom             : {0}' -f $AssemblyFrom)



Import-Module ([System.IO.Path]::Combine((Split-Path $MyInvocation.MyCommand.Path), 'Urasandesu.Prig'))



function SetPrigAssemblyReferenceItem {

    param (
        [Parameter(Mandatory = $true)]
        [Microsoft.Build.Evaluation.Project]
        $MSBuildProject,

        [Parameter(Mandatory = $true)]
        $AssemblyNameEx,

        [Parameter(Mandatory = $true)]
        [string]
        $Platform
    )

    $reference = $MSBuildProject.AddItem('Reference', (ConvertTo-PrigAssemblyName $AssemblyNameEx))
    if ($Platform -match 'AnyCPU') {
        $reference[0].Xml.Condition = "'`$(Platform)|`$(Prefer32Bit)' == '$Platform'"
    } else {
        $reference[0].Xml.Condition = "'`$(Platform)' == '$Platform'"
    }
}



function SetStubberPreBuildEventProperty {

    param (
        [Parameter(Mandatory = $true)]
        [Microsoft.Build.Evaluation.Project]
        $MSBuildProject,

        [Parameter(Mandatory = $true)]
        [string]
        $TargetFrameworkVersion,

        [Parameter(Mandatory = $true)]
        $AssemblyNameEx,

        [Parameter(Mandatory = $true)]
        [string]
        $Platform, 

        [Parameter(Mandatory = $true)]
        [System.Reflection.ProcessorArchitecture]
        $ProcessorArchitecture
    )

    $toolsPath = [IO.Path]::Combine($env:URASANDESU_PRIG_PACKAGE_FOLDER, 'tools')
    $libPath = [IO.Path]::Combine($env:URASANDESU_PRIG_PACKAGE_FOLDER, 'lib')
    $powershell = $(if ($ProcessorArchitecture -eq 'Amd64') { '%windir%\SysNative\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass' } else { '%windir%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass' })
    $argFile = '-File "{0}\Invoke-PilotStubber.ps1"' -f $toolsPath
    $argAssembly = '-AssemblyFrom "{0}"' -f $AssemblyNameEx.Location
    $argTargetFrameworkVersion = '-TargetFrameworkVersion {0}' -f $TargetFrameworkVersion
    if ($TargetFrameworkVersion -eq 'v3.5') {
        $argOther = '-Version 2.0 -NoLogo -NoProfile'
    } else {
        $argOther = '-NoLogo -NoProfile'
    }
    $argReferenceFrom = '-ReferenceFrom "@(''{0}\Urasandesu.NAnonym.dll'',''{0}\Urasandesu.Prig.Framework.dll'')"' -f $libPath
    $argKeyFile = '-KeyFile "{0}\Urasandesu.Prig.snk"' -f $toolsPath
    $argOutputPath = '-OutputPath "$(TargetDir)."'
    $argSettings = '-Settings "$(ProjectDir){0}.{1}.v{2}.prig"' -f $AssemblyNameEx.Name, $AssemblyNameEx.ImageRuntimeVersion, $AssemblyNameEx.Version

    if ($Platform -match 'AnyCPU') {
        $condition = "'`$(Platform)|`$(Prefer32Bit)' == '$Platform'"
    } else {
        $condition = "'`$(Platform)' == '$Platform'"
    }

    $vscomntoolsPaths = gci env:vs* | ? { $_.name -match 'VS\d{3}COMNTOOLS' } | sort name -Descending | % { $_.value }
    $vsDevCmdPath = [System.IO.Path]::Combine($vscomntoolsPaths[0], 'VsDevCmd.bat')
    $targetNames = 'BeforeBuild', 'BeforeRebuild'
    foreach ($targetName in $targetNames) {
        $argBuildTarget = '-BuildTarget {0}' -f $targetName
        $cmd = 'cmd /c " "{0}" & {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} "' -f 
                    $vsDevCmdPath, 
                    $powershell, 
                    $argOther, 
                    $argFile, 
                    $argReferenceFrom, 
                    $argAssembly, 
                    $argTargetFrameworkVersion, 
                    $argKeyFile, 
                    $argOutputPath, 
                    $argSettings, 
                    $argBuildTarget
        
        $targets = 
            $MSBuildProject.Xml.Targets | 
                Where-Object { $_.Name -eq $targetName }
        
        if ($targets.Length -eq 0) {
            $targets = $MSBuildProject.Xml.CreateTargetElement($targetName)
            $MSBuildProject.Xml.InsertAfterChild($targets, @($MSBuildProject.Xml.Imports)[-1])
        }

        $execs = 
            $targets[0].Children | 
                Where-Object { $_.Name -eq 'Exec' } | 
                Where-Object { $_.Condition -eq $condition }
    
        if ($execs.Length -eq 0) {
            $execs = $targets[0].AddTask('Exec')
            $execs.Condition = $condition
        }
        $command = $execs[0].GetParameter('Command')
        if (![string]::IsNullOrEmpty($command)) {
            $command += "`r`n"
        }
        $command += $cmd
        $execs[0].SetParameter('Command', $command)
    }
}



function SetStubSettingNoneItem {

    param (
        [Parameter(Mandatory = $true)]
        [Microsoft.Build.Evaluation.Project]
        $MSBuildProject,

        [Parameter(Mandatory = $true)]
        $AssemblyNameEx,

        [Parameter(Mandatory = $true)]
        [string]
        $ProjectFullName
    )

    $stubSettingName = "{0}.{1}.v{2}.prig" -f $AssemblyNameEx.Name, $AssemblyNameEx.ImageRuntimeVersion, $AssemblyNameEx.Version
    [void]$MSBuildProject.AddItem('None', $stubSettingName)
    $stubSetting = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($ProjectFullName), $stubSettingName)
    if (![System.IO.File]::Exists($stubSetting)) {
        $stubSettingTemplate = [System.IO.Path]::Combine((Get-PackageToolsPath), 'PilotStubber.prig')
        Copy-Item $stubSettingTemplate $stubSetting -ErrorAction Stop | Out-Null
    }
}



function HasAlreadyExistedStubSettingNoneItem {

    param (
        [Parameter(Mandatory = $true)]
        [Microsoft.Build.Evaluation.Project]
        $MSBuildProject,

        [Parameter(Mandatory = $true)]
        $AssemblyNameEx
    )

    $prigAssembly = "{0}.{1}.v{2}" -f $AssemblyNameEx.Name, $AssemblyNameEx.ImageRuntimeVersion, $AssemblyNameEx.Version
    $escapedPrigAssembly = [regex]::Escape($prigAssembly)
    $items = 
        $MSBuildProject.ItemsIgnoringCondition | 
            Where-Object { $_.ItemType -eq "None" } | 
            Where-Object { $_.EvaluatedInclude -match "\.prig\b" } | 
            Where-Object { $_.EvaluatedInclude -match $escapedPrigAssembly }
    
    $items.Length -ne 0
}



$os = Get-WmiObject Win32_OperatingSystem
[System.Reflection.ProcessorArchitecture]$osArch = 0
$osArch = $(if ($os.OSArchitecture -match '64') { 'Amd64' } else { 'X86' })

[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Build')
$msbProjCollection = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection

$curMsbProj = $msbProjCollection.LoadProject($ProjectFullName)

$platformTargets = New-Object 'System.Collections.Generic.Dictionary[string, System.Collections.Generic.List[System.Reflection.ProcessorArchitecture]]'
if (!$curMsbProj.ConditionedProperties.ContainsKey('Platform')) {
    $platformTargets['AnyCPU'] = New-Object 'System.Collections.Generic.List[System.Reflection.ProcessorArchitecture]'
    $platformTargets['AnyCPU'].Add($osArch)
    $platformTargets['AnyCPU'].Add('MSIL')
} else {
    $conditionedProperties = New-Object 'System.Collections.Generic.List[string]'
    foreach ($conditionedProperty in $curMsbProj.ConditionedProperties['Platform']) {
        if ($conditionedProperty -eq 'AnyCPU') {
            $conditionedProperties.Add($conditionedProperty + '|true')
            $conditionedProperties.Add($conditionedProperty + '|false')
        } else {
            $conditionedProperties.Add($conditionedProperty)
        }
    }
    foreach ($conditionedProperty in $conditionedProperties) {
        $platformTargets[$conditionedProperty] = New-Object 'System.Collections.Generic.List[System.Reflection.ProcessorArchitecture]'
        [System.Reflection.ProcessorArchitecture]$1stCandidateArch = 0
        $1stCandidateArch = ConvertTo-ProcessorArchitectureString $conditionedProperty
        $1stCandidateArch = $(if ($1stCandidateArch -eq 'MSIL') { $osArch } else { $1stCandidateArch })
        $platformTargets[$conditionedProperty].Add($1stCandidateArch)
        $platformTargets[$conditionedProperty].Add('MSIL')
    }
}

$curMsbProj.MarkDirty()

$candidateNames = $(if ([string]::IsNullOrEmpty($Assembly)) { Get-AssemblyNameExsFrom $AssemblyFrom } else { Get-AssemblyNameExs $Assembly })
if ($candidateNames.Length -eq 0) {
    $identifier = $(if ([string]::IsNullOrEmpty($Assembly)) { $AssemblyFrom } else { $Assembly })
    $Host.UI.WriteErrorLine(('Assembly ''{0}'' is not found.' -f $identifier))
    exit 964834411
}

$isPlatformMatched = $false
foreach ($platformTarget in $platformTargets.GetEnumerator()) {
    $actualNames = New-Object System.Collections.ArrayList
    foreach ($candidateName in $candidateNames) {
        if ($platformTarget.Value.Contains($candidateName.ProcessorArchitecture)) {
            [void]$actualNames.Add($candidateName)
        }
    }
    if ($actualNames.Count -eq 0) {
        continue
    }
    if (1 -lt $actualNames.Count) {
        $Host.UI.WriteErrorLine(("Ambiguous match found: `r`n{0}" -f ([string]::Join("`r`n", ($actualNames | % { $_.FullName })))))
        exit -1786925265
    }
    if (!$isPlatformMatched -and (HasAlreadyExistedStubSettingNoneItem $curMsbProj $actualNames[0])) {
        $Host.UI.WriteErrorLine(("The Prig assembly for {0} has already been added." -f $actualNames[0].Name))
        exit -1863575335
    }
        
    SetPrigAssemblyReferenceItem $curMsbProj $actualNames[0] $platformTarget.Key
    SetStubberPreBuildEventProperty $curMsbProj $TargetFrameworkVersion $actualNames[0] $platformTarget.Key $platformTarget.Value[0]
    $isPlatformMatched = $true
}
if (!$isPlatformMatched) {
    $identifier = $(if ([string]::IsNullOrEmpty($Assembly)) { $AssemblyFrom } else { $Assembly })
    $Host.UI.WriteErrorLine(('Assembly ''{0}'' is mismatch to the any platforms ''{1}''.' -f $identifier, ($platformTargets.Keys -join ', ')))
    exit 1553812715
}

SetStubSettingNoneItem $curMsbProj $actualNames[0] $ProjectFullName

$curMsbProj.Save()
tools\ChocolateyInstall.ps1
# 
# File: ChocolateyInstall.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2015 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#


$chocoToolsPath = [IO.Path]::Combine($env:chocolateyPackageFolder, 'tools')


foreach ($hedge in (dir $env:chocolateyPackageFolder -r | ? { $_.Extension -eq '.hedge' })) {
    $src = $hedge.FullName
    $dst = $src -replace '\.hedge$', ''
    "  Renaming '$src' to '$dst'..."
    Move-Item $src $dst -Force
}


$packageName = "Prig"
"  Creating the nuget package '$packageName'..."
$nugetPackageFolder = [IO.Path]::Combine($chocoToolsPath, 'NuGet')
nuget pack ([IO.Path]::Combine($nugetPackageFolder, "Prig.nuspec")) -OutputDirectory $chocoToolsPath


$name = "Prig Source"
$source = $chocoToolsPath
"  Registering the nuget source '$source' as '$name'..."
if (0 -lt @(nuget sources list | ? { $_ -match 'Prig Source' }).Length) {
    nuget sources update -name $name -source "$source"
} else {
    nuget sources add -name $name -source "$source"
}


$variableName = "URASANDESU_PRIG_PACKAGE_FOLDER"
$variableValue = $env:chocolateyPackageFolder
"  Registering the environment variable '$variableValue' as '$variableName'..."
Install-ChocolateyEnvironmentVariable $variableName $variableValue


$profilers = [System.IO.Path]::Combine($env:chocolateyPackageFolder, 'tools\x64\Urasandesu.Prig.dll'), 
             [System.IO.Path]::Combine($env:chocolateyPackageFolder, 'tools\x86\Urasandesu.Prig.dll')
foreach ($profiler in $profilers) {
    "  Registering the profiler '$profiler' to Registry..."
    regsvr32 /s /i $profiler
}


$prig = [IO.Path]::Combine($chocoToolsPath, 'prig.exe')
$packageName = "TestWindow"
$msvsdirPaths = dir 'C:\Program Files (x86)\Microsoft Visual Studio *' | ? { $_.name -match 'Microsoft Visual Studio \d+\.\d+' } | sort name -Descending | % { $_.FullName }
$source = [IO.Path]::Combine($msvsdirPaths[0], "Common7\IDE\CommonExtensions\Microsoft\TestWindow")
"  Installing the default source '$source' as the package '$packageName'..."
& $prig install $packageName -source $source


$packageName = 'Prig'
$vsixPath = [IO.Path]::Combine($chocoToolsPath, 'Prig.vsix')
$vsixUrl = ([uri]$vsixPath).AbsoluteUri

Install-ChocolateyVsixPackage $packageName $vsixUrl
tools\ChocolateyUninstall.ps1
# 
# File: ChocolateyUninstall.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2015 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#


$chocoToolsPath = [IO.Path]::Combine($env:chocolateyPackageFolder, 'tools')


'  Uninstalling Prig.vsix...'
$vscomntoolsPaths = gci env:vs* | ? { $_.name -match 'VS\d{3}COMNTOOLS' } | sort name -Descending | % { $_.value }
if (0 -eq $vscomntoolsPaths.Length) {
    Write-Error "'VsDevCmd.bat' is not found."
    exit 1805378044
}
$vsDevCmdPath = [System.IO.Path]::Combine($vscomntoolsPaths[0], 'VsDevCmd.bat')
if (![System.IO.File]::Exists($vsDevCmdPath)) {
    Write-Error "'VsDevCmd.bat' is not found."
    exit 1805378044
}
cmd /c ('" "{0}" & vsixinstaller /q /u:0a06101d-8de3-40c4-b083-c5c16ca227ae "' -f $vsDevCmdPath)


$prig = [IO.Path]::Combine($chocoToolsPath, 'prig.exe')
$packageName = "All"
"  Uninstalling the all package..."
& $prig uninstall $packageName


$profilers = [System.IO.Path]::Combine($env:chocolateyPackageFolder, 'tools\x64\Urasandesu.Prig.dll'), 
             [System.IO.Path]::Combine($env:chocolateyPackageFolder, 'tools\x86\Urasandesu.Prig.dll')
foreach ($profiler in $profilers) {
    "  Unregistering the profiler '$profiler' from Registry..."
    regsvr32 /s /u $profiler
}


$variableName = "URASANDESU_PRIG_PACKAGE_FOLDER"
"  Unregistering the environment variable '$variableName'..."
[System.Environment]::SetEnvironmentVariable($variableName, $null, 'User')


$name = "Prig Source"
"  Unregistering the nuget source '$name'..."
if (0 -lt @(nuget sources list | ? { $_ -match 'Prig Source' }).Length) {
    nuget sources remove -name $name
}
tools\Import-PrigSetupSession.ps1
# 
# File: Import-PrigSetupSession.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

[CmdletBinding()]
param (
    [Parameter(Mandatory = $True)]
    [string]
    $ProjectName, 

    [Parameter(Mandatory = $True)]
    [string]
    $ProjectFullName, 

    [Parameter(Mandatory = $True)]
    [string]
    $TargetFrameworkVersion, 

    [Parameter(Mandatory = $True)]
    [string]
    $OutputPath, 

    [string]
    $ReferenceInclude, 

    [string]
    $ReferenceHintPath, 

    [string]
    $ProjectReferenceInclude, 

    [switch]
    $NoIntro, 

    [string]
    $AdditionalInclude, 

    [string]
    $EditorialInclude, 

    [string]
    $DeletionalInclude
)

Write-Verbose ('ProjectName              : {0}' -f $ProjectName)
Write-Verbose ('ProjectFullName          : {0}' -f $ProjectFullName)
Write-Verbose ('TargetFrameworkVersion   : {0}' -f $TargetFrameworkVersion)
Write-Verbose ('OutputPath               : {0}' -f $OutputPath)
Write-Verbose ('ReferenceInclude         : {0}' -f $ReferenceInclude)
Write-Verbose ('ReferenceHintPath        : {0}' -f $ReferenceHintPath)
Write-Verbose ('ProjectReferenceInclude  : {0}' -f $ProjectReferenceInclude)
Write-Verbose ('NoIntro                  : {0}' -f $NoIntro)
Write-Verbose ('AdditionalInclude        : {0}' -f $AdditionalInclude)
Write-Verbose ('EditorialInclude         : {0}' -f $EditorialInclude)
Write-Verbose ('DeletionalInclude        : {0}' -f $DeletionalInclude)

if (!$NoIntro) {
@'
Welcome to Prig setup session!!


You can add the indirection settings from here. In this session, you can use `$ReferencedAssemblies` that contains all referenced assemblies information of current project. For example, if you want to get the indirection settings for all members of the type `Foo` that belongs to the referenced assembly `UntestableLibrary`, the following commands will achieve it: 

PS> $ReferencedAssemblies

FullName
--------
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
MyLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
UntestableLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null


PS> padd -ra $ReferencedAssemblies[-1]
PS> $ReferencedAssemblies[-1].GetTypes() | ? { $_.Name -eq 'Foo' } | pfind | pget | clip
PS> exit   # Then, paste the content on the clipboard to the stub setting file(e.g. `UntestableLibrary.v4.0.30319.v1.0.0.0.prig`).



See also the command's help `padd`, `pfind` and `pget`.



'@
}

'Current Project: {0}' -f $ProjectName
Write-Warning 'Change the Current Project from `Default Project: ` on the Package Manager Console if it isn''t what you want.'
''
''

$ImportPrigSetupSessionDetail = 'Import-PrigSetupSessionDetail' | New-Module {

    function ResolveAssemblyByReference {
        
        param (
            [string]
            $ProjectDirectory, 

            [string]
            $OutputPath, 

            [string]
            $ReferenceInclude, 

            [string]
            $ReferenceHintPath
        )

        Set-Location $OutputPath
        [System.Environment]::CurrentDirectory = $PWD

        $refAsmInfo = [System.Reflection.Assembly]::LoadWithPartialName($ReferenceInclude)
        if ($null -eq $refAsmInfo) {
            if (![string]::IsNullOrEmpty($ReferenceHintPath)) {
                $refAsmPath = [System.IO.Path]::Combine($ProjectDirectory, $ReferenceHintPath)

                Set-Location ([System.IO.Path]::GetDirectoryName($refAsmPath))
                [System.Environment]::CurrentDirectory = $PWD
                    
                try {
                    $refAsmInfo = [System.Reflection.Assembly]::LoadFrom($refAsmPath)
                }
                catch {
                    Write-Warning $_.Exception.Message
                }
            } else {
                $refAsmPathWithoutExtension = [System.IO.Path]::Combine($PWD.Path, ($ReferenceInclude -replace ',.*$', ''))
                $refAsmPath = $refAsmPathWithoutExtension + ".dll"
                try {
                    $refAsmInfo = [System.Reflection.Assembly]::LoadFrom($refAsmPath)
                }
                catch {
                    Write-Warning $_.Exception.Message

                    try {
                        $refAsmPath = $refAsmPathWithoutExtension + ".exe"
                        $refAsmInfo = [System.Reflection.Assembly]::LoadFrom($refAsmPath)
                    }
                    catch {
                        Write-Warning $_.Exception.Message
                    }
                }
            }
        }

        $refAsmInfo
    }



    function ResolveAssemblyByProjectReference {
        
        param (
            [string]
            $ProjectReferenceInclude
        )

        $outPath = [System.IO.Path]::GetDirectoryName($ProjectReferenceInclude)
        Set-Location $outPath
        [System.Environment]::CurrentDirectory = $PWD

        $refAsmInfo = $null
        try {
            $refAsmInfo = [System.Reflection.Assembly]::LoadFrom($ProjectReferenceInclude)
        }
        catch {
            Write-Warning $_.Exception.Message
        }

        $refAsmInfo
    }



    function Main {

        param (
            [string]
            $Here
        )

        $orgPath = $PWD.Path

        $projDir = [System.IO.Path]::GetDirectoryName($ProjectFullName)
        $outPathResolved = [System.IO.Path]::Combine($projDir, $OutputPath)

        
        $refAsmInfos = New-Object 'System.Collections.Generic.List[System.Reflection.Assembly]'

        $refAsmInfo = [System.Reflection.Assembly]::LoadWithPartialName('mscorlib')
        [void]$refAsmInfos.Add($refAsmInfo)

        if (![string]::IsNullOrEmpty($ReferenceInclude) -and ![string]::IsNullOrEmpty($ReferenceHintPath)) {
            $refIncludes = $ReferenceInclude -split ';'
            $refHints =  $ReferenceHintPath -split ';'
            for ($i = 0; $i -lt $refIncludes.Length; $i++) {
                $refInclude = $refIncludes[$i]
                $refHint = $refHints[$i]
                if ($refInclude -cmatch '\bUrasandesu\b' -or $refInclude -cmatch '\.Prig$') {
                    continue
                }
            
                $refAsmInfo = ResolveAssemblyByReference $projDir $outPathResolved $refInclude $refHint
                if ($null -ne $refAsmInfo) {
                    [void]$refAsmInfos.Add($refAsmInfo)
                }
            }
        }

        if (![string]::IsNullOrEmpty($ProjectReferenceInclude)) {
            $projRefIncludes = $ProjectReferenceInclude -split ';'
            for ($i = 0; $i -lt $projRefIncludes.Length; $i++) {
                $projRefInclude = $projRefIncludes[$i]
            
                $refAsmInfo = ResolveAssemblyByProjectReference $projRefInclude
                if ($null -ne  $refAsmInfo) {
                    [void]$refAsmInfos.Add($refAsmInfo)
                }
            }
        }


        Set-Variable ReferencedAssemblies $refAsmInfos.ToArray() -Scope Global -Option ReadOnly

        Set-Location $orgPath
    }
} | Import-Module -PassThru



Import-Module ([System.IO.Path]::Combine((Split-Path $MyInvocation.MyCommand.Path), 'Urasandesu.Prig'))
& $ImportPrigSetupSessionDetail { Main $args[0] } (Split-Path $MyInvocation.MyCommand.Path)
Remove-Module $ImportPrigSetupSessionDetail

if (![string]::IsNullOrEmpty($DeletionalInclude)) {
    Remove-PrigAssembly -pa $DeletionalInclude
}

if (![string]::IsNullOrEmpty($AdditionalInclude)) {
    foreach ($refAsm in $ReferencedAssemblies | ? { $_.GetName().Name -eq $AdditionalInclude }) {
        Add-PrigAssembly -ra $refAsm
    }
}

if (![string]::IsNullOrEmpty($EditorialInclude)) {
'-EditorialInclude parameter is specified. You can also use the global variable $TargetReferencedAssembly in addition to $ReferencedAssemblies. Currently $TargetReferencedAssembly is: '
    foreach ($refAsm in $ReferencedAssemblies | ? { $_.GetName().Name -eq $EditorialInclude }) {
        Set-Variable TargetReferencedAssembly $refAsm -Scope Global -Option ReadOnly
        break
    }
    $TargetReferencedAssembly
''
''
}
tools\Invoke-PilotStubber.ps1
# 
# File: Invoke-PilotStubber.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

[CmdletBinding()]
param (
    [Parameter(Mandatory = $True)]
    $ReferenceFrom, 

    [string]
    $Assembly, 

    [string]
    $AssemblyFrom, 

    [string]
    $TargetFrameworkVersion,

    [string]
    $KeyFile,

    [string]
    $OutputPath, 
    
    [Parameter(Mandatory = $True)]
    [string]
    $Settings, 

    [string]
    $BuildTarget = 'BeforeRebuild', 
    
    [switch]
    $WhatIf
)

trap {
    Write-Error ($Error[0] | Out-String)
    exit -1
}

Write-Verbose ('ReferenceFrom            : {0}(Type: {1})' -f $ReferenceFrom, ($ReferenceFrom.GetType()))
Write-Verbose ('Assembly                 : {0}' -f $Assembly)
Write-Verbose ('AssemblyFrom             : {0}' -f $AssemblyFrom)
Write-Verbose ('Target Framework Version : {0}' -f $TargetFrameworkVersion)
Write-Verbose ('Key File                 : {0}' -f $KeyFile)
Write-Verbose ('Output Path              : {0}' -f $OutputPath)
Write-Verbose ('Settings                 : {0}' -f $Settings)
Write-Verbose ('Build Target             : {0}' -f $BuildTarget)


$here = Split-Path $MyInvocation.MyCommand.Path
Write-Verbose ('Invocation From          : {0}' -f $here)
Import-Module ([System.IO.Path]::Combine($here, 'Urasandesu.Prig'))

Write-Verbose 'Load Settings ...'

if (![string]::IsNullOrEmpty($Assembly)) {
    $asmInfo = [System.Reflection.Assembly]::Load($Assembly)
} elseif (![string]::IsNullOrEmpty($AssemblyFrom)) {
    $asmInfo = [System.Reflection.Assembly]::LoadFrom($AssemblyFrom)
}
if ($null -eq $asmInfo) {
    Write-Error 'The parameter ''Assembly'' or ''AssemblyFrom'' is mandatory.'
    exit -403162398
}

$asmName = ConvertTo-PrigAssemblyName $asmInfo
$targetInfo = dir ([System.IO.Path]::Combine($OutputPath, $asmName) + ".dll")
if ($BuildTarget -eq 'BeforeBuild' -and 
    $targetInfo.Exists -and [System.IO.File]::GetLastWriteTime($Settings) -lt $targetInfo.LastWriteTime -and 
    $targetInfo.Exists -and [System.IO.File]::Exists($asmInfo.Location) -and [System.IO.File]::GetLastWriteTime($asmInfo.Location) -lt $targetInfo.LastWriteTime) {
    Write-Host ('The indirection stub dll "{0}" has been already existed. Skip the processing to make it ...' -f $targetInfo.FullName)
    exit 0
}
 
$refAsmInfos = New-Object 'System.Collections.Generic.List[System.Reflection.Assembly]'
$refFroms = $ReferenceFrom
if ($refFroms -is [string]) {
    try
    {
        $refFroms = Invoke-Expression $refFroms
    }
    catch
    { }
}
foreach ($refFrom in $refFroms) {
    Write-Verbose ('    ReferenceFrom        : {0}' -f $refFrom)
    $refAsmInfos.Add([System.Reflection.Assembly]::LoadFrom($refFrom))
}
$refAsmInfos.Add($asmInfo)
foreach ($refAsmName in $asmInfo.GetReferencedAssemblies()) {
    try {
        $refAsmInfos.Add([System.Reflection.Assembly]::Load($refAsmName.FullName))
    }
    catch {
        if ([string]::IsNullOrEmpty($AssemblyFrom)) {
            $candidateDir = $OutputPath
        } else {
            $candidateDir = [System.IO.Path]::GetDirectoryName($AssemblyFrom)
        }
        $refAsmPathWithoutExtension = [System.IO.Path]::Combine($candidateDir, $refAsmName.Name)
        try {
            $refAsmInfos.Add([System.Reflection.Assembly]::LoadFrom($refAsmPathWithoutExtension + ".dll"))
        }
        catch {
            try {
                $refAsmInfos.Add([System.Reflection.Assembly]::LoadFrom($refAsmPathWithoutExtension + ".exe"))
            }
            catch {
                Write-Warning ($_ | Out-String)
            }
        }
    }
}

$confAsmInfo = [System.Reflection.Assembly]::LoadWithPartialName('System.Configuration')
if ($refAsmInfos -notcontains $confAsmInfo) {
    $refAsmInfos.Add($confAsmInfo)
}

$systemAsmInfo = [System.Reflection.Assembly]::LoadWithPartialName('System')
if ($refAsmInfos -notcontains $systemAsmInfo) {
    $refAsmInfos.Add($systemAsmInfo)
}


$onAsmInfoResolve = [System.ResolveEventHandler] {
    param($Sender, $E)
    foreach($curAsmInfo in [System.AppDomain]::CurrentDomain.GetAssemblies()) {
        if ($curAsmInfo.FullName -match $E.Name) {
            return $curAsmInfo
        }
    }
    return $null
}

[System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAsmInfoResolve)

$fileMap = New-Object System.Configuration.ExeConfigurationFileMap
$fileMap.ExeConfigFilename = $Settings
$config = [System.Configuration.ConfigurationManager]::OpenMappedExeConfiguration($fileMap, [System.Configuration.ConfigurationUserLevel]::None)
$section = $config.GetSection("prig")
$unintendedSettings = @($section.Stubs | ? { $_.Target.Module.Assembly -ne $asmInfo })
if (0 -lt $unintendedSettings.Length) {
    Write-Error ('Now the indirection settings for "{0}" is being analysed, but the settings for "{1}" was detected.' -f $asmInfo.FullName, $unintendedSettings[0].Target.Module.Assembly.FullName)
    exit -1944878741
}

$additionalAsmInfos = @($section.Stubs | % { $_.IndirectionDelegate.Module.Assembly })
foreach ($additionalAsmInfo in $additionalAsmInfos) {
    if ($refAsmInfos -notcontains $additionalAsmInfo) {
        $refAsmInfos.Add($additionalAsmInfo)
    }
}

$workDir = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($Settings), (ConvertTo-PrigAssemblyName $asmInfo))
Write-Verbose ('    Work Directory {0} ...' -f $workDir)
if (![string]::IsNullOrEmpty($workDir) -and [IO.Directory]::Exists($workDir)) {
    Remove-Item $workDir -Force -Recurse -WhatIf:$WhatIf -ErrorAction Stop | Out-Null
}
New-Item $workDir -ItemType Directory -WhatIf:$WhatIf -ErrorAction Stop | Out-Null


Write-Verbose 'Generate Tokens.g.cs ...'
$tokensCsInfo = New-PrigTokensCs $workDir $asmInfo $section $TargetFrameworkVersion
$tokensCsDir = [System.IO.Path]::GetDirectoryName($tokensCsInfo.Path)
if (![string]::IsNullOrEmpty($tokensCsDir) -and ![IO.Directory]::Exists($tokensCsDir)) {
    New-Item $tokensCsDir -ItemType Directory -WhatIf:$WhatIf -ErrorAction Stop | Out-Null
    Write-Verbose ('    Make Directory to {0} ...' -f $tokensCsDir)
}
$tokensCsInfo.Content | Out-File $tokensCsInfo.Path -Encoding utf8 -WhatIf:$WhatIf -ErrorAction Stop | Out-Null
Write-Verbose ('    Output to {0} ...' -f $tokensCsInfo.Path)


$stubsCsInfos = New-PrigStubsCs $workDir $asmInfo $section $TargetFrameworkVersion
Write-Verbose ('Generate stubs *.g.cs(Count: {0}) ...' -f $stubsCsInfos.Count)
foreach ($stubsCsInfo in $stubsCsInfos) {
    $stubsCsDir = [System.IO.Path]::GetDirectoryName($stubsCsInfo.Path)
    Write-Verbose ('    Check Directory existence {0} ...' -f $stubsCsDir)
    if (![string]::IsNullOrEmpty($stubsCsDir) -and ![IO.Directory]::Exists($stubsCsDir)) {
        New-Item $stubsCsDir -ItemType Directory -WhatIf:$WhatIf -ErrorAction Stop | Out-Null
        Write-Verbose ('    Make Directory to {0} ...' -f $stubsCsDir)
    }
    Write-Verbose ('    Check File existence {0} ...' -f $stubsCsInfo.Path)
    $stubsCsInfo.Content | Out-File $stubsCsInfo.Path -Encoding utf8 -WhatIf:$WhatIf -ErrorAction Stop | Out-Null
    Write-Verbose ('    Output to {0} ...' -f $stubsCsInfo.Path)
}


$proxiesCsInfos = New-PrigProxiesCs $workDir $asmInfo $section $TargetFrameworkVersion
Write-Verbose ('Generate proxies *.g.cs(Count: {0}) ...' -f $proxiesCsInfos.Count)
foreach ($proxiesCsInfo in $proxiesCsInfos) {
    $proxiesCsDir = [System.IO.Path]::GetDirectoryName($proxiesCsInfo.Path)
    Write-Verbose ('    Check Directory existence {0} ...' -f $proxiesCsDir)
    if (![string]::IsNullOrEmpty($proxiesCsDir) -and ![IO.Directory]::Exists($proxiesCsDir)) {
        New-Item $proxiesCsDir -ItemType Directory -WhatIf:$WhatIf -ErrorAction Stop | Out-Null
        Write-Verbose ('    Make Directory to {0} ...' -f $proxiesCsDir)
    }
    Write-Verbose ('    Check File existence {0} ...' -f $proxiesCsInfo.Path)
    $proxiesCsInfo.Content | Out-File $proxiesCsInfo.Path -Encoding utf8 -WhatIf:$WhatIf -ErrorAction Stop | Out-Null
    Write-Verbose ('    Output to {0} ...' -f $proxiesCsInfo.Path)
}


Write-Verbose 'Generate *.g.csproj ...'
$csprojInfo = New-PrigCsproj $workDir $asmInfo $refAsmInfos $KeyFile $TargetFrameworkVersion $OutputPath
$csprojDir = [System.IO.Path]::GetDirectoryName($csprojInfo.Path)
if (![string]::IsNullOrEmpty($csprojDir) -and ![IO.Directory]::Exists($csprojDir)) {
    New-Item $csprojDir -ItemType Directory -WhatIf:$WhatIf -ErrorAction Stop | Out-Null
}
$csprojInfo.XmlDocument.Save($csprojInfo.Path)
Write-Verbose ('Output to {0} ...' -f $csprojInfo.Path)


Write-Verbose 'Build all *.cs files ...'
msbuild $csprojInfo.Path /t:rebuild
tools\NuGet\Prig.nuspec.hedge
 
tools\NuGet\tools\Init.ps1
# 
# File: Init.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

[CmdletBinding()]
param (
    $InstallPath, 

    $ToolsPath, 

    $Package, 

    $Project
)

$ToolsPath = [IO.Path]::Combine($env:URASANDESU_PRIG_PACKAGE_FOLDER, 'tools')
Import-Module ([System.IO.Path]::Combine($ToolsPath, 'Urasandesu.Prig'))

tools\NuGet\tools\Install.ps1
# 
# File: Install.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

[CmdletBinding()]
param (
    $InstallPath, 

    $ToolsPath, 

    $Package, 

    $Project
)

$chocoLibPath = [IO.Path]::Combine($env:URASANDESU_PRIG_PACKAGE_FOLDER, 'lib')
$chocoToolsPath = [IO.Path]::Combine($env:URASANDESU_PRIG_PACKAGE_FOLDER, 'tools')


Import-Module ([System.IO.Path]::Combine($chocoToolsPath, 'Urasandesu.Prig'))


$here = Split-Path $MyInvocation.MyCommand.Path
$nugetLibPath = [IO.Path]::Combine([IO.Path]::GetDirectoryName($here), 'lib')
$nugetToolsPath = [IO.Path]::Combine($nugetPackageFolder, 'tools')
rmdir $nugetLibPath -Recurse -ErrorAction SilentlyContinue
mkdir $nugetLibPath | Out-Null
foreach ($dll in (dir $chocoLibPath)) {
    $target = [IO.Path]::Combine($nugetLibPath, $dll.Name)
    $source = $dll.FullName
    cmd /c ('" mklink "{0}" "{1}" "' -f $target, $source)
}
tools\NuGet\tools\Uninstall.ps1
# 
# File: Uninstall.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

[CmdletBinding()]
param (
    $InstallPath, 

    $ToolsPath, 

    $Package, 

    $Project
)

tools\NUnitTestAdapterForPrig.2.0.0.nupkg.hedge
 
tools\PilotStubber.prig
 
tools\prig.exe
md5: 651BA71457FFC5DFA95B0B379A7CB8FC | sha1: 6B4D1103AF07362296E595A45659CF0459C6C220
tools\Prig.vsix
 
tools\Remove-PrigAssembly.ps1
# 
# File: Remove-PrigAssembly.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

[CmdletBinding()]
param (
    [Parameter(Mandatory = $True)]
    [string]
    $ProjectFullName, 

    [Parameter(Mandatory = $True)]
    [string]
    $PrigAssembly
)

Write-Verbose ('ProjectFullName          : {0}' -f $ProjectFullName)
Write-Verbose ('PrigAssembly             : {0}' -f $PrigAssembly)



Import-Module ([System.IO.Path]::Combine((Split-Path $MyInvocation.MyCommand.Path), 'Urasandesu.Prig'))



function EraseStubberPreBuildEventProperty {

    param (
        [Parameter(Mandatory = $true)]
        [Microsoft.Build.Evaluation.Project]
        $MSBuildProject,

        [Parameter(Mandatory = $true)]
        [string]
        $EscapedPrigAssembly
    )
    
    $targetNames = 'BeforeBuild', 'BeforeRebuild'
    foreach ($targetName in $targetNames) {
        $targets = 
            $MSBuildProject.Xml.Targets | 
                Where-Object { $_.Name -eq $targetName }
        if ($targets.Length -eq 0) {
            continue;
        }

        $execs = 
            $targets[0].Children | 
                Where-Object { $_.Name -eq 'Exec' } | 
                Where-Object { $_.GetParameter('Command') -cmatch '\bPrig\b' }
        if ($execs.Length -eq 0) {
            continue;
        }

        for ($i = 0; $i -lt $execs.Length; $i++) {
            $command = $execs[$i].GetParameter('Command')
            $cmds = @($command -split "`r`n")
            $remainings = @($cmds | ? { $_ -notmatch $EscapedPrigAssembly })
            $command = $remainings -join "`r`n"
            if ([string]::IsNullOrEmpty($command)) {
                $targets[0].RemoveChild($execs[$i])
            } else {
                $execs[$i].SetParameter('Command', $command)
            }
        }

        if ($targets[0].Children.Count -eq 0) {
            $MSBuildProject.Xml.RemoveChild($targets[0])
        }
    }
}



function EraseStubItem {

    param (
        [Parameter(Mandatory = $true)]
        [Microsoft.Build.Evaluation.Project]
        $MSBuildProject,

        [Parameter(Mandatory = $true)]
        [string]
        $EscapedPrigAssembly
    )

    $items = $MSBuildProject.ItemsIgnoringCondition | ? { $_.EvaluatedInclude -match "\.prig\b" } | ? { $_.EvaluatedInclude -match $EscapedPrigAssembly }
    foreach ($item in $items) {
        [void]$MSBuildProject.RemoveItem($item)
    }
}



[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Build')
$msbProjCollection = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection

$curMsbProj = $msbProjCollection.LoadProject($ProjectFullName)
$curMsbProj.MarkDirty()

$escapedPrigAssembly = [regex]::Escape($PrigAssembly)
$items = 
    $curMsbProj.ItemsIgnoringCondition | 
        Where-Object { $_.ItemType -eq "None" } | 
        Where-Object { $_.EvaluatedInclude -match "\.prig\b" } | 
        Where-Object { $_.EvaluatedInclude -match $escapedPrigAssembly }

if ($items.Length -eq 0) {
    $Host.UI.WriteErrorLine(('Prig Assembly ''{0}'' is not found.' -f $PrigAssembly))
    exit 737914319
}

if (1 -lt $items.Count) {
    $Host.UI.WriteErrorLine(("Ambiguous match found: `r`n{0}" -f ([string]::Join("`r`n", ($items | % { $_.EvaluatedInclude })))))
    exit -1786925265
}

EraseStubberPreBuildEventProperty $curMsbProj $escapedPrigAssembly
EraseStubItem $curMsbProj $escapedPrigAssembly

$curMsbProj.Save()
tools\Urasandesu.Prig.snk
 
tools\Urasandesu.Prig\format.ps1xml
 
tools\Urasandesu.Prig\Urasandesu.Prig.psd1
 
tools\Urasandesu.Prig\Urasandesu.Prig.psm1
# 
# File: Urasandesu.Prig.psm1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



$here = Split-Path $MyInvocation.MyCommand.Path
Update-FormatData -PrependPath ([System.IO.Path]::Combine($here, 'format.ps1xml'))

Export-ModuleMember -Function *-* -Alias *
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Add-PrigAssembly.ps1
# 
# File: Chocolatey.Add-PrigAssembly.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

function Add-PrigAssembly {
<#
    .SYNOPSIS
        Creates the stub settings file for the specified assembly on the Package Manager Console or the Prig setup session.

    .DESCRIPTION
        This command adds the stub setting file that sets up the indirection settings for specified assembly to a project on the Package Manager Console or the Prig setup session.
        Target project is the value that is selected as `Default project: ` on the Package Manager Console. The stub setting file is named like `<assembly name>.<runtime version>.v<assembly version>.prig`. After the file is added, you will get the confirmation message that the project has been modified externally, so reload the project.
        Also, you can't add the setting file for same assembly. If you want to add it again, execute `Remove-PrigAssembly` command once to remove the setting file.

    .PARAMETER  Assembly
        A display name recognizing uniquely an assembly. 
        Use this parameter if adding the stub setting file for a GAC registered assembly. If it can't recognize uniquely, the error "Ambiguous match found" will be occurred. So, you have to specify a more detailed display name.
        You can also refer to the Assembly parameter by its built-in alias, "as".

    .PARAMETER  AssemblyFrom
        A full path recognizing uniquely an assembly. 
        Use this parameter if adding the stub setting file for a GAC unregistered assembly. Also, you have to change to the directory where specified assembly exists if using this parameter; otherwise referenced assemblies may not resolved.
        You can also refer to the AssemblyFrom parameter by its built-in alias, "af".

    .PARAMETER  ReferencedAssembly
        A referenced assembly object. 
        You can use this parameter only in the Prig setup session. If you specify this parameter in another environment, the error "Invalid operation is detected" will be occurred. For more detail, please see the help for `Start-PrigSetup`.
        You can also refer to the ReferencedAssembly parameter by its built-in alias, "ra".

    .PARAMETER  Project
        A `EnvDTE.DTE` object that adds Prig assembly.
        This API supports the Prig infrastructure and is not intended to be used directly from your code.

    .EXAMPLE
        Add-PrigAssembly -Assembly "mscorlib, Version=4.0.0.0"
        
        DESCRIPTION
        -----------
        This command adds the stub setting file for the assembly `mscorlib` to the target project.

    .EXAMPLE
        padd -as mscorlib
        Ambiguous match found: 
        mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        
        DESCRIPTION
        -----------
        This is example that "You try to add the stub setting file for the assembly `mscorlib`, but the error 'Ambiguous match found' is occurred". In this error, candidate assemblies are listed at the time. So, select again more detailed display name from them.

    .EXAMPLE
        C:\users\akira\documents\visual studio 2013\Projects\Demo\Demo\bin\Debug>dir


        Directory: C:\users\akira\documents\visual studio 2013\Projects\Demo\Demo\bin\Debug


        Mode                LastWriteTime     Length Name
        ----                -------------     ------ ----
        -a---        2014/10/10      9:31       4096 DependentLibrary1.dll
        -a---        2014/10/10      9:31       7680 DependentLibrary1.pdb
        -a---        2014/10/10      9:31       4608 DependentLibrary2.dll
        -a---        2014/10/10      9:31       7680 DependentLibrary2.pdb
        -a---        2014/10/10      9:31       7680 DemoLibrary.dll
        -a---        2014/10/10      9:31      28160 DemoLibrary.pdb


        C:\users\akira\documents\visual studio 2013\Projects\Demo\Demo\bin\Debug>padd -af (dir .\DemoLibrary.dll).FullName
        
        DESCRIPTION
        -----------
        This command adds the stub setting file for the GAC unregistered assembly `DemoLibrary` to the target project. If you specify `-AssemblyFrom` parameter, you have to execute this command in the directory that the target assembly exists like the example.

    .EXAMPLE
        padd -ra $ReferencedAssemblies[0]
        
        DESCRIPTION
        -----------
        This command adds the stub setting file for the assembly `mscorlib` in the Prig setup session. In the session, you can confirm the referenced assemblies of current project through the global variable `$ReferencedAssemblies`, also you can pass it to `Add-PrigAssembly` command as it is. For more detail, please see the help for `Start-PrigSetup`.

    .INPUTS
        System.String, System.Reflection.Assembly

    .OUTPUTS
        None

    .NOTES
        You can also refer to the Add-PrigAssembly command by its built-in alias, "PAdd".

    .LINK
        Find-IndirectionTarget

    .LINK
        Get-IndirectionStubSetting

    .LINK
        Remove-PrigAssembly

    .LINK
        Start-PrigSetup

#>

    [CmdletBinding()]
    param (
        [Alias("as")]
        [Parameter(Mandatory = $true, ParameterSetName = 'Assembly')]
        [string]
        $Assembly, 

        [Alias("af")]
        [Parameter(Mandatory = $true, ParameterSetName = 'AssemblyFrom')]
        [string]
        $AssemblyFrom, 

        [Alias("ra")]
        [Parameter(Mandatory = $true, ParameterSetName = 'ReferencedAssembly')]
        [System.Reflection.Assembly]
        $ReferencedAssembly, 

        $Project
    )

    # $ProjectFullName and $TargetFrameworkVersion are only enabled in Prig setup session. See also `Import-PrigSetupSession.ps1`.
    $projFullName = $ProjectFullName
    $targetFrmwrkVer = $TargetFrameworkVersion
    if ($null -eq $projFullName) {
        if(![string]::IsNullOrEmpty($ReferencedAssembly)) {
            throw New-Object System.InvalidOperationException 'The parameter "ReferencedAssembly" can specify only in the Prig setup session. Please see the help "pstart" for more details.'
        }

        $envProj = $(if ($null -eq $Project) { (Get-Project).Object.Project } else { $Project.Object.Project })
        $projFullName = $envProj.FullName

        [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Build')
        $msbProjCollection = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection
        $allMsbProjs = $msbProjCollection.GetLoadedProjects($projFullName).GetEnumerator()
        if(!$allMsbProjs.MoveNext()) {
            throw New-Object System.InvalidOperationException ('"{0}" has not been loaded.' -f $projFullName)
        }
        $curMsbProj = $allMsbProjs.Current
        $targetFrmwrkVer = $curMsbProj.GetProperty('TargetFrameworkVersion').EvaluatedValue
    }

    if ($null -ne $ReferencedAssembly) {
        if ($ReferencedAssembly.GlobalAssemblyCache) {
            $Assembly = $ReferencedAssembly.FullName
        } else {
            $AssemblyFrom = $ReferencedAssembly.Location
        }
    }

    $powershell = 'powershell'

    $addPrigAssembly = [System.IO.Path]::Combine((Get-PackageToolsPath), 'Add-PrigAssembly.ps1')
    $argList = '-NonInteractive', '-NoLogo', '-NoProfile', '-File', """$addPrigAssembly""", """$projFullName""", """$targetFrmwrkVer""", """$Assembly""", """$AssemblyFrom"""
    if ($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) {
        $argList += '-Verbose'
    }

    $tmpFileName = [System.IO.Path]::GetTempFileName()

    Start-Process $powershell $argList -Wait -RedirectStandardError $tmpFileName -NoNewWindow
    $errors = Get-Content $tmpFileName
    Remove-Item $tmpFileName -ErrorAction SilentlyContinue
    if (0 -lt $errors.Length) {
        $Host.UI.WriteErrorLine($errors -join "`r`n")
    }
}

New-Alias PAdd Add-PrigAssembly

tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.ConvertTo-PrigAssemblyName.ps1
# 
# File: Chocolatey.ConvertTo-PrigAssemblyName.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function ConvertTo-PrigAssemblyName {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        $Info
    )

    switch ($Info)
    {
        { $_.psobject.TypeNames -contains 'System.Reflection.Assembly' } {  
            $name = $Info.GetName().Name
            $runtimeVer = $Info.ImageRuntimeVersion
            $ver = $Info.GetName().Version
            $procArch = ConvertTo-ProcessorArchitectureString $Info
        }
        { $_.psobject.TypeNames -contains $AssemblyNameExTypeName } {  
            $name = $Info.Name
            $runtimeVer = $Info.ImageRuntimeVersion
            $ver = $Info.Version
            $procArch = ConvertTo-ProcessorArchitectureString $Info
        }
        Default {
            throw New-Object System.ArgumentException ('Info(Type: {0}) is not supported.' -f $Info.GetType())
        }
    }

    '{0}.{1}.v{2}.{3}.Prig' -f $name, $runtimeVer, $ver, $procArch
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.ConvertTo-ProcessorArchitectureString.ps1
# 
# File: Chocolatey.ConvertTo-ProcessorArchitectureString.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function ConvertTo-ProcessorArchitectureString {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $True)]
        $Info
    )

    switch ($Info)
    {
        { $_.psobject.TypeNames -contains 'System.Reflection.Assembly' } {  
            $procArch = [string]$Info.GetName().ProcessorArchitecture 
        }
        { $_.psobject.TypeNames -contains 'System.Reflection.AssemblyName' } {  
            $procArch = [string]$Info.ProcessorArchitecture 
        }
        { $_.psobject.TypeNames -contains $AssemblyNameExTypeName } {  
            $procArch = $Info.ProcessorArchitecture 
        }
        { $_ -is [string] } { 
            $procArch = $Info 
        }
        Default { 
            throw New-Object System.ArgumentException ('Parameter $Info({0}) is not supported.' -f $Info.GetType()) 
        }
    }

    switch ($procArch)
    {
        'X86'                           { "x86"; break }
        { $_ -match '(Amd64)|(x64)' }   { "AMD64"; break }
        { $_ -match 'AnyCPU\|true' }    { "x86"; break }
        { $_ -match '(MSIL)|(AnyCPU)' } { "MSIL"; break }
        Default                         { "MSIL"; break }
    }
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Disable-PrigTestAdapter.ps1
# 
# File: Chocolatey.Disable-PrigTestAdapter.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

function Disable-PrigTestAdapter {

    [CmdletBinding()]
    param (
    )

    [System.Environment]::SetEnvironmentVariable($EnableProfilingKey, $EnableProfilingValueDisabled)
    [System.Environment]::SetEnvironmentVariable($ProfilerKey, '')
    [System.Environment]::SetEnvironmentVariable($ProfilerCurrentDirectoryKey, '')
    [System.Environment]::SetEnvironmentVariable($ProfilerTargetProcessNameKey, '')
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Enable-PrigTestAdapter.ps1
# 
# File: Chocolatey.Enable-PrigTestAdapter.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

function Enable-PrigTestAdapter {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        $Project
    )

    $envProj = $Project.Object.Project

    try {
        $devenv = [System.Diagnostics.Process]::GetCurrentProcess()
        $devenvId = $devenv.Id
    }
    finally {
        if ($null -ne $devenv) {
            $devenv.Dispose()
        }
    }

    $executionEngineProcess = (Get-WmiObject Win32_Process | ? { $_.ParentProcessId -eq $devenvId -and $_.ProcessName -match 'vstest\.executionengine' })

    if ($null -ne $executionEngineProcess) {
        $executionengineId = $executionEngineProcess.ProcessId
        try {
            $executionengine = [System.Diagnostics.Process]::GetProcessById($executionengineId)
            if ($null -ne $executionengine) {
                $executionengine.Kill()
            }
        }
        finally {
            if ($null -ne $executionengine) {
                $executionengine.Dispose()
            }
        }
    }

    $projDir = [System.IO.Path]::GetDirectoryName($envProj.FullName)
    $outputPath = ($envProj.ConfigurationManager.ActiveConfiguration.Properties | ? { $_.Name -eq 'OutputPath' }).Value
    $targetDir = [System.IO.Path]::Combine($projDir, $outputPath)
    if ([string]::IsNullOrEmpty($targetDir)) {
        throw New-Object System.InvalidOperationException '"$(TargetDir)" has not been able to resolve.'
    }

    [System.Environment]::SetEnvironmentVariable($EnableProfilingKey, $EnableProfilingValueEnabled)
    [System.Environment]::SetEnvironmentVariable($ProfilerKey, $ProfilerValue)
    [System.Environment]::SetEnvironmentVariable($ProfilerCurrentDirectoryKey, $targetDir)
    [System.Environment]::SetEnvironmentVariable($ProfilerTargetProcessNameKey, $ProfilerTargetProcessNameValue)
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Find-IndirectionTarget.ps1
# 
# File: Chocolatey.Find-IndirectionTarget.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

function Find-IndirectionTarget {
<#
    .SYNOPSIS
        Finds the targets to create the indirection setting on the Package Console Manager, PowerShell or the Prig setup session.

    .DESCRIPTION
        This command finds the methods that are satisfied the search condition on the Package Manager Console, PowerShell or the Prig setup session.

        About the search way, first, it enumerates the members that are satisfied the following conditions from the specified parameter as `-InputObject`: 
        * a public member or a non-public member
        * a instance member or a static member
        * a only member declared at the level of the supplied type's hierarchy
        * a constructor(containing a type constructor) or a method
        * a non-abstract members
        
        From them, it narrow the search to the results that are matched to specified the parameter `-Method`. The string that is compared with `-Method` is same as the string that is listed as the results this command invoked.

    .PARAMETER  InputObject
        An array of type or an array of string that can be recognized as a type.
        "The string that can be recognized as a type" means that `Invoke-Expression ('[{0}]' -f $s)` - NOTE: $s is string - can evaluate to `Sytem.Type` object. Therefore, you can specify the parameter like `datetime`, `system.reflection.assembly`, `([int])` and so on.

    .PARAMETER  Method
        A search condition for the methods.
        You can use regular expression.

    .PARAMETER  PublicOnly
        Omits non-public members from the search results.

    .PARAMETER  IgnoreMockable
        Omits mockable members from the search results.

    .EXAMPLE
        Find-IndirectionTarget datetime '(today)|(now)'

        Method
        ------
        System.DateTime get_Now()
        System.DateTime get_UtcNow()
        System.DateTime get_Today()

        DESCRIPTION
        -----------
        This command finds the members that contain the string `today` or `now` from the type `System.DateTime`.

    .EXAMPLE
        PS C:\>$asmInfo = [System.Reflection.Assembly]::LoadWithPartialName("System.Web")
        PS C:\>$asmInfo.GetTypes() | ? { $_.Name -eq 'httpcontext' }
        
        IsPublic IsSerial Name                                     BaseType
        -------- -------- ----                                     --------
        True     False    HttpContext                              System.Object
        
        
        PS C:\>$asmInfo.GetTypes() | ? { $_.Name -eq 'httpcontext' } | pfind -m 'get_current\b'
        
        Method
        ------
        System.Web.HttpContext get_Current()
        
        DESCRIPTION
        -----------
        In this example, first, it finds the types that is named `httpcontext` from the assembly `System.Web`. Against the results, use this command, and find the members that are matched the regular expression `get_current\b`.

    .EXAMPLE
        C:\users\akira\documents\visual studio 2013\Projects\Demo\Demo\bin\Debug>ipmo ..\..\..\packages\Prig.0.0.0-alpha10\tools\Urasandesu.Prig
        C:\users\akira\documents\visual studio 2013\Projects\Demo\Demo\bin\Debug>$asmInfo = [System.Reflection.Assembly]::LoadFrom((dir .\DemoLibrary.dll).FullName)
        C:\users\akira\documents\visual studio 2013\Projects\Demo\Demo\bin\Debug>$asmInfo.GetTypes()
        
        IsPublic IsSerial Name                                     BaseType
        -------- -------- ----                                     --------
        True     False    Foo                                      System.Object
        
        
        C:\users\akira\documents\visual studio 2013\Projects\Demo\Demo\bin\Debug>$asmInfo.GetTypes() | pfind
        
        Method
        ------
        Void .ctor()
        
        DESCRIPTION
        -----------
        This is the example that doesn't use the Package Manager Console but use PowerShell.

        The Package Manager Console doesn't support nested prompt by its design. Therefore, there is the problem that it can never release the assemblies if it loaded the assemblies to analyze indirection targets once. In the first place, the features that are used mundanely - such as autocompletion, commands history and so on - are less functionality than PowerShell's. I highly recommend that you always use PowerShell when analyzing the indirection targets.

    .INPUTS
        System.String, System.String[], System.Type, System.Type[]

    .OUTPUTS
        None, System.Reflection.MethodBase, System.Reflection.MethodBase[]

    .NOTES
        You have to import the module `Urasandesu.Prig` explicitly if you use this command on PowerShell directly. The module `Urasandesu.Prig` is placed the directory `tools` of the package directory by NuGet when you installed Prig. So, execute `Import-Module` from there. By the way, this step requires a little labor. Using the Prig setup session would be more easier. See also the help for `Start-PrigSetup` for more details.
        
        You can also refer to the Find-IndirectionTarget command by its built-in alias, "PFind".

    .LINK
        Add-PrigAssembly

    .LINK
        Get-IndirectionStubSetting

    .LINK
        Start-PrigSetup

#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        $InputObject, 
    
        [Parameter(Position = 1)]
        $Method, 
    
        [switch]
        $PublicOnly, 
    
        [switch]
        $IgnoreMockable 
    )

    begin {

    } process {
        if ($null -ne $InputObject) {
            foreach ($type in $InputObject) {
                $typeInfo = $type
                if ($typeInfo -is [string]) {
                    $typeInfo = $(try { Invoke-Expression $type } catch { })
                    if ($null -eq $typeInfo) {
                        $typeInfo = $(try { Invoke-Expression ('[{0}]' -f $type) } catch { })
                    }
                }
                if ($typeInfo -isnot [type]) {
                    throw New-Object System.ArgumentException '-Type option must be a type or a string that can parse to a type(e.g. -Type ([datetime]) or -Type datetime).'
                }

                $memberInfos = $typeInfo.GetMembers([System.Reflection.BindingFlags]'Public, NonPublic, Instance, Static, DeclaredOnly')
                $indirectlyCallables = $memberInfos | ? { $_ -is [System.Reflection.MethodBase] } | ? { !$_.IsAbstract }

                if ($null -ne $Method) {
                    $indirectlyCallables = $indirectlyCallables | ? { $_.ToString() -match $Method }
                }

                if ($PublicOnly) {
                    $indirectlyCallables = $indirectlyCallables | ? { $_.IsPublic -or ($_ -is [System.Reflection.MethodInfo] -and $null -ne (GetImplementedInterface $_)) }
                }

                if ($IgnoreMockable -and !$typeInfo.IsSealed) {
                    $indirectlyCallables = $indirectlyCallables | ? { !$_.IsVirtual }
                }

                $indirectlyCallables
            }
        }
    } end {

    }
}

New-Alias PFind Find-IndirectionTarget
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Get-AssemblyNameExs.ps1
# 
# File: Chocolatey.Get-AssemblyNameExs.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function Get-AssemblyNameExs {

    [CmdletBinding()]
    param (
        $Assembly
    )

    $results = prig dasm -assembly $Assembly | ConvertFrom-Csv
    foreach ($result in $results) {
        $result.psobject.TypeNames.Insert(0, $AssemblyNameExTypeName)
        $result
    }
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Get-AssemblyNameExsFrom.ps1
# 
# File: Chocolatey.Get-AssemblyNameExsFrom.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function Get-AssemblyNameExsFrom {

    [CmdletBinding()]
    param (
        $AssemblyFrom
    )

    $results = prig dasm -assemblyfrom $AssemblyFrom | ConvertFrom-Csv
    foreach ($result in $results) {
        $result.psobject.TypeNames.Insert(0, $AssemblyNameExTypeName)
        $result
    }
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Get-IndirectionStubSetting.ps1
# 
# File: Chocolatey.Get-IndirectionStubSetting.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

function Get-IndirectionStubSetting {
<#
    .SYNOPSIS
        Gets the indirection stub settings on the Package Manager Console, PowerShell or the Prig setup session.

    .DESCRIPTION
        This command creates XML tags that can be used as the indirection settings for the target method on the Package Manager Console, PowerShell or the Prig setup session, and gets them.

        The indirection stub settings mean the tags that can be added to the stub setting file(`*.prig`) that is set up by the command `Add-PrigAssembly`. In particular, the tag is `add`. You can insert it to between the tag `<stubs>...</stubs>` of the file.

        Note that you have to typically generate unique name, and set to the tag(its attribute `name` and `alias`) in the type the target method is declared. However, you can get easily such name by using this command.

        The naming convention is similar to Microsoft Fakes's, but there is also a little different: 
        * The namespace that the stubs are located is the original namespace + `.Prig`.  
          For example, the stubs for the types under `System` are located at the namespace `System.Prig`.

        * The prefix of the stub is `P`(no conditions) or `PProxy`(specified instance of a class).  
          For example, the stub for `System.DateTime` is `System.Prig.PDateTime`. However, the stub `PProxyDateTime` isn't generated, because it is a structure.
          The stub for `System.Net.HttpWebRequest` is `System.Net.Prig.PHttpWebRequest`. Also, `System.Net.Prig.PProxyHttpWebRequest` is generated, because it is a class.

        See also [Code generation, compilation, and naming conventions in Microsoft Fakes](http://msdn.microsoft.com/en-us/library/hh708916.aspx).

        The results are output as plain text, so I recommend that you use in combination with `clip` command.

    .PARAMETER  InputObject
        A array of `System.Reflection.MethodBase` object which is target to get the indirection settings.

    .EXAMPLE
        PS C:\>pfind datetime _now | pget
        <add name="NowGet" alias="NowGet">
        <RuntimeMethodInfo xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:x="http://www.w3.org/2001/XMLSchema" z:Id="1" z:FactoryType="MemberInfoSerializationHolder" z:Type="System.Reflection.MemberInfoSerializationHolder" z:Assembly="0" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns="http://schemas.datacontract.org/2004/07/System.Reflection">
          <Name z:Id="2" z:Type="System.String" z:Assembly="0" xmlns="">get_Now</Name>
          <AssemblyName z:Id="3" z:Type="System.String" z:Assembly="0" xmlns="">mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</AssemblyName>
          <ClassName z:Id="4" z:Type="System.String" z:Assembly="0" xmlns="">System.DateTime</ClassName>
          <Signature z:Id="5" z:Type="System.String" z:Assembly="0" xmlns="">System.DateTime get_Now()</Signature>
          <Signature2 z:Id="6" z:Type="System.String" z:Assembly="0" xmlns="">System.DateTime get_Now()</Signature2>
          <MemberType z:Id="7" z:Type="System.Int32" z:Assembly="0" xmlns="">8</MemberType>
          <GenericArguments i:nil="true" xmlns="" />
        </RuntimeMethodInfo>
        </add>
        
        PS C:\>pfind datetime _now | pget | clip
        
        DESCRIPTION
        -----------
        This is the example that is used in combination with `Find-IndirectionTarget`. Search the members that are matched to the regular expression `_now` from the type `System.DateTime`, and get the indirection stub settings. When confirmed that, it has no problem. So, copy it to clipboard, and paste it to the stub settings file.

    .INPUTS
        System.Reflection.MethodBase, System.Reflection.MethodBase[]

    .OUTPUTS
        System.String

    .NOTES
        You have to import the module `Urasandesu.Prig` explicitly if you use this command on PowerShell directly. The module `Urasandesu.Prig` is placed the directory `tools` of the package directory by NuGet when you installed Prig. So, execute `Import-Module` from there. By the way, this step requires a little labor. Using the Prig setup session would be more easier. See also the help for `Start-PrigSetup` for more details.
        
        You can also refer to the Get-IndirectionStubSetting command by its built-in alias, "PGet".

    .LINK
        Add-PrigAssembly

    .LINK
        Find-IndirectionTarget

    .LINK
        Start-PrigSetup

#>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        [System.Reflection.MethodBase[]]
        $InputObject
    )

    begin {
        [Void][System.Reflection.Assembly]::LoadWithPartialName('System.Runtime.Serialization')
    } process {
        if ($null -ne $InputObject) {
            foreach ($methodBase in $InputObject) {
                $ndcs = New-Object System.Runtime.Serialization.NetDataContractSerializer
                $sb = New-Object System.Text.StringBuilder
                $sw = New-Object System.IO.StringWriter $sb
                try {
                    $xw = New-Object System.Xml.XmlTextWriter $sw
                    $xw.Formatting = [System.Xml.Formatting]::Indented
                    $ndcs.WriteObject($xw, $methodBase);
                } finally {
                    if ($null -ne $xw) { $xw.Close() }
                }

                $content = $sb.ToString()
                $name = ConvertToIndirectionStubName $methodBase
                @"
<add name="$name" alias="$name">
$content
</add>

"@
            }
        }
    } end {

    }
}

New-Alias PGet Get-IndirectionStubSetting
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Get-PackageName.ps1
# 
# File: Chocolatey.Get-PackageName.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function Get-PackageName {
    
    # $(SolutionDir)packages\Prig.1.1.0\tools\Urasandesu.Prig\Urasandesu\Prig
    $curDirInfo = New-Object System.IO.DirectoryInfo $here
    
    # $(SolutionDir)packages\Prig.1.1.0\tools\Urasandesu.Prig\Urasandesu
    # $(SolutionDir)packages\Prig.1.1.0\tools\Urasandesu.Prig
    # $(SolutionDir)packages\Prig.1.1.0\tools
    # $(SolutionDir)packages\Prig.1.1.0
    # Prig.1.1.0
    $curDirInfo.Parent.Parent.Parent.Parent.Name
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Get-PackageToolsPath.ps1
# 
# File: Chocolatey.Get-PackageToolsPath.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function Get-PackageToolsPath {
    
    # $(SolutionDir)packages\Prig.1.1.0\tools\Urasandesu.Prig\Urasandesu\Prig
    $curDirInfo = New-Object System.IO.DirectoryInfo $here
    
    # $(SolutionDir)packages\Prig.1.1.0\tools\Urasandesu.Prig\Urasandesu
    # $(SolutionDir)packages\Prig.1.1.0\tools\Urasandesu.Prig
    # $(SolutionDir)packages\Prig.1.1.0\tools
    $curDirInfo.Parent.Parent.Parent.FullName
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.New-PrigCsproj.ps1
# 
# File: Chocolatey.New-PrigCsproj.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function New-PrigCsproj {
    param ($WorkDirectory, $AssemblyInfo, $ReferencedAssemblyInfos, $KeyFile, $TargetFrameworkVersion, $OutputPath)

    $rootNamespace = ToRootNamespace $AssemblyInfo
    $signAsm = ToSignAssembly $AssemblyInfo $KeyFile
    $defineConsts = ToDefineConstants $AssemblyInfo $TargetFrameworkVersion
    $platform = ToPlatformTarget $AssemblyInfo
    $asmName = ConvertTo-PrigAssemblyName $AssemblyInfo
    $refInc = ToReferenceInclude $ReferencedAssemblyInfos

    $csprojTemplate = [xml]@"
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <OutputType>Library</OutputType>
        <RootNamespace>$rootNamespace</RootNamespace>
        <FileAlignment>512</FileAlignment>
        <SignAssembly>$signAsm</SignAssembly>
        <AssemblyOriginatorKeyFile>$KeyFile</AssemblyOriginatorKeyFile>
        <OutputPath>$OutputPath</OutputPath>
        <DefineConstants>$defineConsts</DefineConstants>
        <PlatformTarget>$platform</PlatformTarget>
        <DebugType>pdbonly</DebugType>
        <Optimize>true</Optimize>
        <TargetFrameworkVersion>$TargetFrameworkVersion</TargetFrameworkVersion>
        <AssemblyName>$asmName</AssemblyName>
    </PropertyGroup>
    <ItemGroup>$refInc</ItemGroup>
    <ItemGroup>
        <Compile Include="**/*.cs" />
    </ItemGroup>
    <Import Project="`$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
"@

    New-Object psobject | 
        Add-Member NoteProperty 'Path' ([System.IO.Path]::Combine($WorkDirectory, "$rootNamespace.g.csproj")) -PassThru | 
        Add-Member NoteProperty 'XmlDocument' $csprojTemplate -PassThru
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.New-PrigProxiesCs.ps1
# 
# File: Chocolatey.New-PrigProxiesCs.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function New-PrigProxiesCs {
    param ($WorkDirectory, $AssemblyInfo, $Section, $TargetFrameworkVersion)

    $results = New-Object System.Collections.ArrayList
    
    foreach ($namespaceGrouped in $Section.GroupedStubs) {
        $dir = $namespaceGrouped.Key -replace '\.', '\'

        foreach ($declTypeGrouped in $namespaceGrouped) {
            if (!(IsPublic $declTypeGrouped.Key) -or $declTypeGrouped.Key.IsValueType) { continue }
            $hasAnyInstanceMember = $false
            $content = @"

using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using Urasandesu.NAnonym;
using Urasandesu.Prig.Delegates;
using Urasandesu.Prig.Framework;
using Urasandesu.Prig.Framework.PilotStubberConfiguration;

namespace $(ConcatIfNonEmpty $namespaceGrouped.Key '.')Prig
{
    public class PProxy$(ConvertTypeToClassName $declTypeGrouped.Key) $(ConvertTypeToGenericParameterConstraints $declTypeGrouped.Key)
    {
        $(ConvertTypeToFullName $declTypeGrouped.Key) m_target;
        
        public PProxy$(ConvertTypeToName $declTypeGrouped.Key)()
        {
            m_target = ($(ConvertTypeToFullName $declTypeGrouped.Key))FormatterServices.GetUninitializedObject(typeof($(ConvertTypeToFullName $declTypeGrouped.Key)));
        }

        public IndirectionBehaviors DefaultBehavior { get; internal set; }

"@ + $(foreach ($stub in $declTypeGrouped | ? { !$_.Target.IsStatic -and (IsSignaturePublic $_) -and ($_.Target -is [System.Reflection.MethodInfo]) }) {
        $hasAnyInstanceMember = $true
@"

        public zz$(ConvertStubToClassName $stub) $(ConvertStubToClassName $stub)() $(ConvertStubToGenericParameterConstraints $stub)
        {
            return new zz$(ConvertStubToClassName $stub)(m_target);
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public class zz$(ConvertStubToClassName $stub) : IBehaviorPreparable $(ConvertStubToGenericParameterConstraints $stub)
        {
            $(ConvertTypeToFullName $declTypeGrouped.Key) m_target;

            public zz$(StripGenericParameterCount $stub.Alias)($(ConvertTypeToFullName $declTypeGrouped.Key) target)
            {
                m_target = target;
            }

            public $(ConvertTypeToClassName $stub.IndirectionDelegate) Body
            {
                get
                {
                    return P$(ConvertTypeToClassName $declTypeGrouped.Key).$(ConvertStubToClassName $stub)().Body;
                }
                set
                {
                    if (value == null)
                        P$(ConvertTypeToClassName $declTypeGrouped.Key).$(ConvertStubToClassName $stub)().RemoveTargetInstanceBody(m_target);
                    else
                        P$(ConvertTypeToClassName $declTypeGrouped.Key).$(ConvertStubToClassName $stub)().SetTargetInstanceBody(m_target, value);
                }
            }

            public void Prepare(IndirectionBehaviors defaultBehavior)
            {
                var behavior = HelperFor$(ConvertTypeToClassName $stub.IndirectionDelegate).CreateDelegateOfDefaultBehavior(defaultBehavior);
                Body = behavior;
            }

            public IndirectionInfo Info
            {
                get { return P$(ConvertTypeToClassName $declTypeGrouped.Key).$(ConvertStubToClassName $stub)().Info; }
            }
        }
"@}) + @"

"@ + $(foreach ($stub in $declTypeGrouped | ? { !$_.Target.IsStatic -and !(IsSignaturePublic $_) -and ($_.Target -is [System.Reflection.MethodInfo]) }) {
        $hasAnyInstanceMember = $true
@"

        public zz$(ConvertStubToClassName $stub) $(ConvertStubToClassName $stub)() $(ConvertStubToGenericParameterConstraints $stub)
        {
            return new zz$(ConvertStubToClassName $stub)(m_target);
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public class zz$(ConvertStubToClassName $stub) : IBehaviorPreparable $(ConvertStubToGenericParameterConstraints $stub)
        {
            $(ConvertTypeToFullName $declTypeGrouped.Key) m_target;

            public zz$(StripGenericParameterCount $stub.Alias)($(ConvertTypeToFullName $declTypeGrouped.Key) target)
            {
                m_target = target;
            }

            public Work Body
            {
                get
                {
                    return P$(ConvertTypeToClassName $declTypeGrouped.Key).$(ConvertStubToClassName $stub)().Body;
                }
                set
                {
                    if (value == null)
                        P$(ConvertTypeToClassName $declTypeGrouped.Key).$(ConvertStubToClassName $stub)().RemoveTargetInstanceBody(m_target);
                    else
                        P$(ConvertTypeToClassName $declTypeGrouped.Key).$(ConvertStubToClassName $stub)().SetTargetInstanceBody(m_target, value);
                }
            }

            public void Prepare(IndirectionBehaviors defaultBehavior)
            {
                var indDlgt = IndirectionHolderUntyped.MakeGenericInstance(Stub.Target, Stub.IndirectionDelegate, $(ConvertTypeToGenericParameterArray $declTypeGrouped.Key), $(ConvertStubToGenericParameterArray $stub));
                var behavior = HelperForUntypedIndirectionDelegate.CreateDelegateOfDefaultBehavior(indDlgt, defaultBehavior);
                Body = behavior;
            }

            public IndirectionStub Stub
            {
                get { return P$(ConvertTypeToClassName $declTypeGrouped.Key).$(ConvertStubToClassName $stub)().Stub; }
            }

            public IndirectionInfo Info
            {
                get { return P$(ConvertTypeToClassName $declTypeGrouped.Key).$(ConvertStubToClassName $stub)().Info; }
            }
        }
"@}) + @"


        public static implicit operator $(ConvertTypeToFullName $declTypeGrouped.Key)(PProxy$(ConvertTypeToClassName $declTypeGrouped.Key) @this)
        {
            return @this.m_target;
        }

        public InstanceBehaviorSetting ExcludeGeneric()
        {
            var preparables = typeof(PProxy$(ConvertTypeToClassName $declTypeGrouped.Key)).GetNestedTypes().
                                          Where(_ => _.GetInterface(typeof(IBehaviorPreparable).FullName) != null).
                                          Where(_ => !_.IsGenericType).
                                          Select(_ => Activator.CreateInstance(_, new object[] { m_target })).
                                          Cast<IBehaviorPreparable>();
            var setting = new InstanceBehaviorSetting(this);
            foreach (var preparable in preparables)
                setting.Include(preparable);
            return setting;
        }

        public class InstanceBehaviorSetting : BehaviorSetting
        {
            private PProxy$(ConvertTypeToClassName $declTypeGrouped.Key) m_this;

            public InstanceBehaviorSetting(PProxy$(ConvertTypeToClassName $declTypeGrouped.Key) @this)
            {
                m_this = @this;
            }
"@ + $(foreach ($stub in $declTypeGrouped | ? { ($declTypeGrouped.Key.IsGenericType -or $_.Target.IsGenericMethod) -and (IsSignaturePublic $_) }) {
@"

            public InstanceBehaviorSetting Include$(ConvertStubToClassName $stub)() $(ConvertStubToGenericParameterConstraints $stub)
            {
                Include(m_this.$(ConvertStubToClassName $stub)());
                return this;
            }

"@}) + @"

            public override IndirectionBehaviors DefaultBehavior
            {
                set
                {
                    m_this.DefaultBehavior = value;
                    foreach (var preparable in Preparables)
                        preparable.Prepare(m_this.DefaultBehavior);
                }
            }
        }
    }
}
"@
            if (!$hasAnyInstanceMember) { continue }

            $result = 
                New-Object psobject | 
                    Add-Member NoteProperty 'Path' ([System.IO.Path]::Combine($WorkDirectory, "$(ConcatIfNonEmpty $dir '\')PProxy$(ConvertTypeToStubName $declTypeGrouped.Key).g.cs")) -PassThru | 
                    Add-Member NoteProperty 'Content' $content -PassThru
            [Void]$results.Add($result)
        }
    }

    ,$results
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.New-PrigStubsCs.ps1
# 
# File: Chocolatey.New-PrigStubsCs.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function New-PrigStubsCs {
    param ($WorkDirectory, $AssemblyInfo, $Section, $TargetFrameworkVersion)

    $results = New-Object System.Collections.ArrayList
    
    foreach ($namespaceGrouped in $Section.GroupedStubs) {
        $dir = $namespaceGrouped.Key -replace '\.', '\'

        foreach ($declTypeGrouped in $namespaceGrouped) {
            $content = @"

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Urasandesu.NAnonym;
using Urasandesu.Prig.Delegates;
using Urasandesu.Prig.Framework;
using Urasandesu.Prig.Framework.PilotStubberConfiguration;

namespace $(ConcatIfNonEmpty $namespaceGrouped.Key '.')Prig
{
    public class P$(ConvertTypeToClassName $declTypeGrouped.Key) : P$(ConvertTypeToBaseName $declTypeGrouped.Key) $(ConvertTypeToGenericParameterConstraints $declTypeGrouped.Key)
    {
        public static IndirectionBehaviors DefaultBehavior { get; internal set; }

"@ + $(foreach ($stub in $declTypeGrouped | ? { IsSignaturePublic $_ }) {
@"

        public static zz$(ConvertStubToClassName $stub) $(ConvertStubToClassName $stub)() $(ConvertStubToGenericParameterConstraints $stub)
        {
            return new zz$(ConvertStubToClassName $stub)();
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public class zz$(ConvertStubToClassName $stub) : IBehaviorPreparable $(ConvertStubToGenericParameterConstraints $stub)
        {
            public $(ConvertTypeToClassName $stub.IndirectionDelegate) Body
            {
                get
                {
                    var info = Info;
                    info.SetInstantiation(Stub.Target, Stub.IndirectionDelegate, $(ConvertTypeToGenericParameterArray $declTypeGrouped.Key), $(ConvertStubToGenericParameterArray $stub));
                    var holder = LooseCrossDomainAccessor.GetOrRegister<IndirectionHolder<Delegate>>();
                    return LooseCrossDomainAccessor.SafelyCast<$(ConvertTypeToClassName $stub.IndirectionDelegate)>(holder.GetOrDefault(info));
                }
                set
                {
                    var info = Info;
                    info.SetInstantiation(Stub.Target, Stub.IndirectionDelegate, $(ConvertTypeToGenericParameterArray $declTypeGrouped.Key), $(ConvertStubToGenericParameterArray $stub));
                    var holder = LooseCrossDomainAccessor.GetOrRegister<IndirectionHolder<Delegate>>();
                    if (value == null)
                    {
                        holder.Remove(info);
                    }
                    else
                    {
                        holder.AddOrUpdate(info, value);
                        RuntimeHelpers.PrepareDelegate(Body);
                    }
                }
            }

            public void Prepare(IndirectionBehaviors defaultBehavior)
            {
                var behavior = HelperFor$(ConvertTypeToClassName $stub.IndirectionDelegate).CreateDelegateOfDefaultBehavior(defaultBehavior);
                Body = behavior;
            }

            IndirectionStub m_stub;
            public IndirectionStub Stub
            {
                get
                {
                    if (m_stub == null)
                    {
                        var stubsXml = $(ConvertStubToStubsXml $stub);
                        var section = new PrigSection();
                        section.DeserializeStubs(stubsXml);
                        m_stub = section.Stubs.First();
                    }
                    return m_stub;
                }
            }

            public IndirectionInfo Info
            {
                get
                {
                    var info = new IndirectionInfo();
                    info.AssemblyName = "$($AssemblyInfo.FullName)";
                    info.Token = TokenOf$($stub.Name);
                    return info;
                }
            }
"@ + $(if (!$stub.Target.IsStatic -and !$declTypeGrouped.Key.IsValueType) {
@"

            internal void SetTargetInstanceBody($(ConvertTypeToFullName $declTypeGrouped.Key) target, $(ConvertTypeToClassName $stub.IndirectionDelegate) value)
            {
                RuntimeHelpers.PrepareDelegate(value);

                var holder = LooseCrossDomainAccessor.GetOrRegister<GenericHolder<TaggedBag<zz$(ConvertStubToClassName $stub), Dictionary<$(ConvertTypeToFullName $declTypeGrouped.Key), TargetSettingValue<$(ConvertTypeToClassName $stub.IndirectionDelegate)>>>>>();
                if (holder.Source.Value == null)
                    holder.Source = TaggedBagFactory<zz$(ConvertStubToClassName $stub)>.Make(new Dictionary<$(ConvertTypeToFullName $declTypeGrouped.Key), TargetSettingValue<$(ConvertTypeToClassName $stub.IndirectionDelegate)>>());

                if (holder.Source.Value.Count == 0)
                {
                    var behavior = Body == null ? HelperFor$(ConvertTypeToClassName $stub.IndirectionDelegate).CreateDelegateOfDefaultBehavior(IndirectionBehaviors.Fallthrough) : Body;
                    RuntimeHelpers.PrepareDelegate(behavior);
                    holder.Source.Value[target] = new TargetSettingValue<$(ConvertTypeToClassName $stub.IndirectionDelegate)>(behavior, value);
                    {
                        // Prepare JIT
                        var original = holder.Source.Value[target].Original;
                        var indirection = holder.Source.Value[target].Indirection;
                    }
                    Body = HelperFor$(ConvertTypeToClassName $stub.IndirectionDelegate).CreateDelegateExecutingDefaultOr(behavior, holder.Source.Value);
                }
                else
                {
                    Debug.Assert(Body != null);
                    var before = holder.Source.Value[target];
                    holder.Source.Value[target] = new TargetSettingValue<$(ConvertTypeToClassName $stub.IndirectionDelegate)>(before.Original, value);
                }
            }

            internal void RemoveTargetInstanceBody($(ConvertTypeToFullName $declTypeGrouped.Key) target)
            {
                var holder = LooseCrossDomainAccessor.GetOrRegister<GenericHolder<TaggedBag<zz$(ConvertStubToClassName $stub), Dictionary<$(ConvertTypeToFullName $declTypeGrouped.Key), TargetSettingValue<$(ConvertTypeToClassName $stub.IndirectionDelegate)>>>>>();
                if (holder.Source.Value == null)
                    return;

                if (holder.Source.Value.Count == 0)
                    return;

                var before = default(TargetSettingValue<$(ConvertTypeToClassName $stub.IndirectionDelegate)>);
                if (holder.Source.Value.ContainsKey(target))
                    before = holder.Source.Value[target];
                holder.Source.Value.Remove(target);
                if (holder.Source.Value.Count == 0)
                    Body = before.Original;
            }
"@}) + @"

        }

"@}) + @"

"@ + $(foreach ($stub in $declTypeGrouped | ? { !(IsSignaturePublic $_) }) {
@"

        public static zz$(ConvertStubToClassName $stub) $(ConvertStubToClassName $stub)() $(ConvertStubToGenericParameterConstraints $stub)
        {
            return new zz$(ConvertStubToClassName $stub)();
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public class zz$(ConvertStubToClassName $stub) : IBehaviorPreparable $(ConvertStubToGenericParameterConstraints $stub)
        {
            public Work Body
            {
                get
                {
                    var info = Info;
                    info.SetInstantiation(Stub.Target, Stub.IndirectionDelegate, $(ConvertTypeToGenericParameterArray $declTypeGrouped.Key), $(ConvertStubToGenericParameterArray $stub));
                    var holder = LooseCrossDomainAccessorUntyped.GetOrRegister(Stub.Target, Stub.IndirectionDelegate, $(ConvertTypeToGenericParameterArray $declTypeGrouped.Key), $(ConvertStubToGenericParameterArray $stub));
                    return holder.GetOrDefault(info);
                }
                set
                {
                    var info = Info;
                    info.SetInstantiation(Stub.Target, Stub.IndirectionDelegate, $(ConvertTypeToGenericParameterArray $declTypeGrouped.Key), $(ConvertStubToGenericParameterArray $stub));
                    var holder = LooseCrossDomainAccessorUntyped.GetOrRegister(Stub.Target, Stub.IndirectionDelegate, $(ConvertTypeToGenericParameterArray $declTypeGrouped.Key), $(ConvertStubToGenericParameterArray $stub));
                    if (value == null)
                    {
                        holder.Remove(info);
                    }
                    else
                    {
                        holder.AddOrUpdate(info, value);
                        RuntimeHelpers.PrepareDelegate(value);
                    }
                }
            }

            public void Prepare(IndirectionBehaviors defaultBehavior)
            {
                var indDlgt = IndirectionHolderUntyped.MakeGenericInstance(Stub.Target, Stub.IndirectionDelegate, $(ConvertTypeToGenericParameterArray $declTypeGrouped.Key), $(ConvertStubToGenericParameterArray $stub));
                var behavior = HelperForUntypedIndirectionDelegate.CreateDelegateOfDefaultBehavior(indDlgt, defaultBehavior);
                Body = behavior;
            }

            IndirectionStub m_stub;
            public IndirectionStub Stub
            {
                get
                {
                    if (m_stub == null)
                    {
                        var stubsXml = $(ConvertStubToStubsXml $stub);
                        var section = new PrigSection();
                        section.DeserializeStubs(stubsXml);
                        m_stub = section.Stubs.First();
                    }
                    return m_stub;
                }
            }

            public IndirectionInfo Info
            {
                get
                {
                    var info = new IndirectionInfo();
                    info.AssemblyName = "$($AssemblyInfo.FullName)";
                    info.Token = TokenOf$($stub.Name);
                    return info;
                }
            }
"@ + $(if (!$stub.Target.IsStatic -and !$declTypeGrouped.Key.IsValueType) {
@"

            internal void SetTargetInstanceBody(object target, Work value)
            {
                RuntimeHelpers.PrepareDelegate(value);

                var holder = LooseCrossDomainAccessor.GetOrRegister<GenericHolder<TaggedBag<zz$(ConvertStubToClassName $stub), Dictionary<object, TargetSettingValue<Work>>>>>();
                if (holder.Source.Value == null)
                    holder.Source = TaggedBagFactory<zz$(ConvertStubToClassName $stub)>.Make(new Dictionary<object, TargetSettingValue<Work>>());

                if (holder.Source.Value.Count == 0)
                {
                    var indDlgt = IndirectionHolderUntyped.MakeGenericInstance(Stub.Target, Stub.IndirectionDelegate, $(ConvertTypeToGenericParameterArray $declTypeGrouped.Key), $(ConvertStubToGenericParameterArray $stub));
                    var behavior = Body == null ? HelperForUntypedIndirectionDelegate.CreateDelegateOfDefaultBehavior(indDlgt, IndirectionBehaviors.Fallthrough) : Body;
                    RuntimeHelpers.PrepareDelegate(behavior);
                    holder.Source.Value[target] = new TargetSettingValue<Work>(behavior, value);
                    {
                        // Prepare JIT
                        var original = holder.Source.Value[target].Original;
                        var indirection = holder.Source.Value[target].Indirection;
                    }
                    Body = HelperForUntypedIndirectionDelegate.CreateDelegateExecutingDefaultOrUntypedDelegate(indDlgt, behavior, holder.Source.Value);
                }
                else
                {
                    Debug.Assert(Body != null);
                    var before = holder.Source.Value[target];
                    holder.Source.Value[target] = new TargetSettingValue<Work>(before.Original, value);
                }
            }

            internal void RemoveTargetInstanceBody(object target)
            {
                var holder = LooseCrossDomainAccessor.GetOrRegister<GenericHolder<TaggedBag<zz$(ConvertStubToClassName $stub), Dictionary<object, TargetSettingValue<Work>>>>>();
                if (holder.Source.Value == null)
                    return;

                if (holder.Source.Value.Count == 0)
                    return;

                var before = default(TargetSettingValue<Work>);
                if (holder.Source.Value.ContainsKey(target))
                    before = holder.Source.Value[target];
                holder.Source.Value.Remove(target);
                if (holder.Source.Value.Count == 0)
                    Body = before.Original;
            }
"@}) + @"

        }

"@}) + @"


        public static TypeBehaviorSetting ExcludeGeneric()
        {
            var preparables = typeof(P$(ConvertTypeToClassName $declTypeGrouped.Key)).GetNestedTypes().
                                          Where(_ => _.GetInterface(typeof(IBehaviorPreparable).FullName) != null).
                                          Where(_ => !_.IsGenericType).
                                          Select(_ => Activator.CreateInstance(_)).
                                          Cast<IBehaviorPreparable>();
            var setting = new TypeBehaviorSetting();
            foreach (var preparable in preparables)
                setting.Include(preparable);
            return setting;
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public class TypeBehaviorSetting : BehaviorSetting
        {
"@ + $(foreach ($stub in $declTypeGrouped | ? { ($declTypeGrouped.Key.IsGenericType -or $_.Target.IsGenericMethod) -and (IsSignaturePublic $_) }) {
@"

            public TypeBehaviorSetting Include$(ConvertStubToClassName $stub)() $(ConvertStubToGenericParameterConstraints $stub)
            {
                Include(P$(ConvertTypeToClassName $declTypeGrouped.Key).$(ConvertStubToClassName $stub)());
                return this;
            }

"@}) + @"

            public override IndirectionBehaviors DefaultBehavior
            {
                set
                {
                    P$(ConvertTypeToClassName $declTypeGrouped.Key).DefaultBehavior = value;
                    foreach (var preparable in Preparables)
                        preparable.Prepare(P$(ConvertTypeToClassName $declTypeGrouped.Key).DefaultBehavior);
                }
            }
        }
    }
}
"@
            $result = 
                New-Object psobject | 
                    Add-Member NoteProperty 'Path' ([System.IO.Path]::Combine($WorkDirectory, "$(ConcatIfNonEmpty $dir '\')P$(ConvertTypeToStubName $declTypeGrouped.Key).g.cs")) -PassThru | 
                    Add-Member NoteProperty 'Content' $content -PassThru
            [Void]$results.Add($result)
        }
    }

    ,$results
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.New-PrigTokensCs.ps1
# 
# File: Chocolatey.New-PrigTokensCs.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function New-PrigTokensCs {
    param ($WorkDirectory, $AssemblyInfo, $Section, $TargetFrameworkVersion)

    $content = @"
#if $(ToTargetFrameworkVersionConstant $TargetFrameworkVersion) && $(ToProcessorArchitectureConstant $AssemblyInfo)
//------------------------------------------------------------------------------ 
// <auto-generated> 
// This code was generated by a tool. 
// Assembly                 : $($AssemblyInfo.GetName().Name)
// Runtime Version          : $($AssemblyInfo.ImageRuntimeVersion)
// Assembly Version         : $($AssemblyInfo.GetName().Version.ToString())
// Processor Architecture   : $(ConvertTo-ProcessorArchitectureString $AssemblyInfo)
// 
// Changes to this file may cause incorrect behavior and will be lost if 
// the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------


using Urasandesu.Prig.Framework;

"@ + $(foreach ($stub in $Section.Stubs) {
@"

[assembly: Indirectable($(ConcatIfNonEmpty $stub.Target.DeclaringType.Namespace '.')Prig.P$(ConvertTypeToBaseName $stub.Target.DeclaringType).TokenOf$($stub.Name))]
"@}) + @"
"@ + $(foreach ($namespaceGrouped in $Section.GroupedStubs) {
@"


namespace $(ConcatIfNonEmpty $namespaceGrouped.Key '.')Prig
{
"@ + $(foreach ($declTypeGrouped in $namespaceGrouped) {
@"

    public abstract class P$(ConvertTypeToBaseName $declTypeGrouped.Key)
    {
"@ + $(foreach ($stub in $declTypeGrouped) {
@"

        internal const int TokenOf$($stub.Name) = 0x$($stub.Target.MetadataToken.ToString('X8'));
"@}) + @"

    }
"@}) + @"

}
"@}) + @"

#endif
"@
    
    New-Object psobject | 
        Add-Member NoteProperty 'Path' ([System.IO.Path]::Combine($WorkDirectory, 'AutoGen\Tokens.g.cs')) -PassThru | 
        Add-Member NoteProperty 'Content' $content -PassThru
}
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.psm1
# 
# File: Chocolatey.psm1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



$here = Split-Path $MyInvocation.MyCommand.Path





New-Variable AssemblyNameExTypeName 'Urasandesu.Prig.Chocolatey.AssemblyNameEx' -Option ReadOnly
New-Variable EnableProfilingKey 'COR_ENABLE_PROFILING' -Option ReadOnly
New-Variable EnableProfilingValueDisabled '0' -Option ReadOnly
New-Variable EnableProfilingValueEnabled '1' -Option ReadOnly
New-Variable ProfilerKey 'COR_PROFILER' -Option ReadOnly
New-Variable ProfilerValue '{532C1F05-F8F3-4FBA-8724-699A31756ABD}' -Option ReadOnly
New-Variable ProfilerCurrentDirectoryKey 'URASANDESU_PRIG_CURRENT_DIRECTORY' -Option ReadOnly
New-Variable ProfilerTargetProcessNameKey 'URASANDESU_PRIG_TARGET_PROCESS_NAME' -Option ReadOnly
New-Variable ProfilerTargetProcessNameValue 'vstest\.executionengine' -Option ReadOnly



function ConcatIfNonEmpty {
    param (
        [string]
        $String1,
         
        [string]
        $String2
    )

    if (![string]::IsNullOrEmpty($String1) -and ![string]::IsNullOrEmpty($String2)) {
        $String1 + $String2
    }
}



function ToRootNamespace {
    param (
        [System.Reflection.Assembly]
        $AssemblyInfo
    )

    $AssemblyInfo.GetName().Name + '.Prig'
}



function ToSignAssembly {
    param (
        [System.Reflection.Assembly]
        $AssemblyInfo, 

        [string]
        $KeyFile
    )
    
    if ($AssemblyInfo.GetName().GetPublicKeyToken().Length -eq 0) {
        $false
    } else {
        if ([string]::IsNullOrEmpty($KeyFile)) {
            $false
        } else {
            $true
        }
    }
}



function ToProcessorArchitectureConstant {
    param (
        [System.Reflection.Assembly]
        $AssemblyInfo
    )

    switch ($AssemblyInfo.GetName().ProcessorArchitecture)
    {
        'X86'       { "_M_IX86" }
        'Amd64'     { "_M_AMD64" }
        'MSIL'      { "_M_MSIL" }
        Default     { "_M_MSIL" }
    }
}



function ToTargetFrameworkVersionConstant {
    param (
        [string]
        $TargetFrameworkVersion
    )
    
    switch ($TargetFrameworkVersion)
    {
        'v3.5'      { "_NET_3_5" }
        'v4.0'      { "_NET_4" }
        'v4.5'      { "_NET_4_5" }
        'v4.5.1'    { "_NET_4_5_1" }
        Default     { "_NET_4" }
    }
}



function ToDefineConstants {
    param (
        [System.Reflection.Assembly]
        $AssemblyInfo, 

        [string]
        $TargetFrameworkVersion
    )
    
    $result = (ToProcessorArchitectureConstant $AssemblyInfo), (ToTargetFrameworkVersionConstant $TargetFrameworkVersion)
    $result -join ';'
}



function ToPlatformTarget {
    param (
        [System.Reflection.Assembly]
        $AssemblyInfo
    )

    switch ($AssemblyInfo.GetName().ProcessorArchitecture)
    {
        'X86'       { "x86" }
        'Amd64'     { "x64" }
        'MSIL'      { "AnyCPU" }
        Default     { "AnyCPU" }
    }
}



function ToReferenceInclude {
    param (
        [System.Reflection.Assembly[]]
        $ReferencedAssemblyInfos
    )
    
    foreach ($refAsmInfo in $ReferencedAssemblyInfos) {
        @"
        <Reference Include="$($refAsmInfo.GetName().Name)">
            <HintPath>$($refAsmInfo.Location)</HintPath>
        </Reference>
"@
    }
}



function StripGenericParameterCount {
    param (
        [string]
        $Name
    )

    $Name -replace '`\d+', ''
}



function ConvertTypeToFullName {
    param (
        [type]
        $Type, 

        [System.Collections.ArrayList]
        $List
    )
    
    $defName = $Type.FullName
    if ($defName -eq $null) {
        $defName = $Type.Name
    }
        
    if ($Type.IsGenericParameter -and !$Type.IsNested) {
        $defName = $Type.Name
    } elseif ($Type.IsGenericParameter) {
        $defName = ([string]$defName).Replace("+",".")
    } elseif (!$Type.IsGenericParameter -and $Type.IsNested) {
        $defName = (ConvertTypeToFullName $Type.DeclaringType) + '.' + $Type.Name
    } elseif ($Type.IsGenericType -and !$Type.IsGenericTypeDefinition) {
        $defName = $Type.Namespace + "." + $Type.Name
    } elseif ($Type.HasElementType -and $Type.IsArray) {
        if ($null -eq $List) {
            $List = New-Object System.Collections.ArrayList
        }
        [void]$List.Add(("[{0}]" -f (New-Object string ',', ($Type.GetArrayRank() - 1))))
        $defName = (ConvertTypeToFullName $Type.GetElementType() $List)
    } elseif ($Type.HasElementType) {
        $defName = ConvertTypeToFullName $Type.GetElementType()
    }

    if ($Type.IsGenericType) {
        if ($Type.HasElementType -and $Type.IsGenericTypeDefinition) {
            $defName = $Type.Name
        }
        $genericArgs = $Type.GetGenericArguments()
        if ($Type.Name -match '`(\d+)') {
            $genericArgs = $genericArgs[($genericArgs.Length - ([int]$Matches[1]))..($genericArgs.Length - 1)]
            $defName = StripGenericParameterCount $defName
            $genericArgNames = @()
            foreach ($genericArg in $genericArgs) {
                $genericArgNames += (ConvertTypeToFullName $genericArg)
            }
            $defName = ($defName + "<" + ($genericArgNames -join ', ') + ">")
        }
    }

    if (0 -lt $List.Count) {
        $defName += ($List -join '')
        $List.Clear()
    }
    $defName
}



function ConvertTypeToClassName {
    param (
        [type]
        $Type
    )
    
    if (!$Type.IsGenericParameter -and $Type.IsNested) {
        $defName = (ConvertTypeToStubName $Type.DeclaringType) + $Type.Name
    } else {
        $defName = $Type.Name
    }

    if ($Type.IsGenericType) {
        $defName = StripGenericParameterCount $defName
        $genericArgNames = @()
        foreach ($genericArg in $Type.GetGenericArguments()) {
            $genericArgNames += (ConvertTypeToFullName $genericArg)
        }
        $defName = ($defName + "<" + ($genericArgNames -join ', ') + ">")
    }
    $defName
}



function ConvertTypeToBaseName {
    param (
        [type]
        $Type
    )
    
    if (!$Type.IsGenericParameter -and $Type.IsNested) {
        $defName = (ConvertTypeToStubName $Type.DeclaringType) + $Type.Name
    } else {
        $defName = $Type.Name
    }

    if ($Type.IsGenericType) {
        $defName = StripGenericParameterCount $defName
    }
    $defName + "Base"
}



function ConvertTypeToName {
    param (
        [type]
        $Type
    )
    
    if (!$Type.IsGenericParameter -and $Type.IsNested) {
        $defName = (ConvertTypeToStubName $Type.DeclaringType) + $Type.Name
    } else {
        $defName = $Type.Name
    }

    if ($Type.IsGenericType) {
        $defName = StripGenericParameterCount $defName
    }
    $defName
}



function ConvertStubToClassName {
    param (
        [Urasandesu.Prig.Framework.PilotStubberConfiguration.IndirectionStub]
        $Stub
    )
    
    $defName = $Stub.Alias
    if ($Stub.Target.IsGenericMethod) {
        $defName = StripGenericParameterCount $defName
        $genericArgNames = @()
        foreach ($genericArg in $Stub.Target.GetGenericArguments()) {
            $genericArgNames += (ConvertTypeToFullName $genericArg)
        }
        $defName = ($defName + "<" + ($genericArgNames -join ', ') + ">")
    }
    $defName
}



function IsPublic {
    param (
        [type]
        $Type
    )
    
    $targetType = $Type
    if ($Type.HasElementType) { 
        $targetType = $Type.GetElementType()
    }
    $targetType.IsPublic -or $targetType.IsNestedPublic
}



function IsSignaturePublic {
    param (
        [Urasandesu.Prig.Framework.PilotStubberConfiguration.IndirectionStub]
        $Stub
    )

    $result = $true
    
    if (!$Stub.Target.IsStatic) {
        $result = $result -and (IsPublic $Stub.Target.DeclaringType)
    }

    $paramInfos = $Stub.Target.GetParameters()
    $result = $result -and !(0 -lt @($paramInfos | ? { !(IsPublic $_.ParameterType) }).Length)

    switch ($Stub.Target)
    {
        { $_ -is [System.Reflection.MethodInfo] } {
            [System.Reflection.MethodInfo]$methodInfo = $null
            $methodInfo = $Stub.Target
            $result = $result -and (IsPublic $methodInfo.ReturnType)
            break
        }
        { $_ -is [System.Reflection.ConstructorInfo] } {
            # nop
            break
        }
        Default {
            throw New-Object System.ArgumentException ('Parameter $Stub.Target({0}) is not supported.' -f $Stub.Target.GetType()) 
        }
    }
    $result
}



function GetImplementedInterface {
    param (
        [System.Reflection.MethodInfo]
        $MethodInfo
    )

    $declaringType = $MethodInfo.DeclaringType
    foreach ($interface in $declaringType.GetInterfaces()) {
        $mapping = $declaringType.GetInterfaceMap($interface)

        if ($mapping.TargetType -ne $declaringType) { 
            continue 
        }

        $index = [array]::IndexOf($mapping.TargetMethods, $MethodInfo)
        if ($index -eq -1) { 
            continue 
        }

        if (!$MethodInfo.IsFinal -or !$MethodInfo.IsVirtual) {
            return $null
        }

        if ($mapping.InterfaceMethods[$index] -ne $null) {
            $interfaceMethod = $mapping.InterfaceMethods[$index]
            return New-Object psobject | 
                        Add-Member NoteProperty 'Interface' $interface -PassThru | 
                        Add-Member NoteProperty 'InterfaceMethod' $interfaceMethod -PassThru
        }
    }

    $null
}



function GetExplicitlyImplementedInterface {
    param (
        [System.Reflection.MethodInfo]
        $MethodInfo
    )

    $result = GetImplementedInterface $MethodInfo
    if ($null -ne $result) {
        $name = $result.InterfaceMethod.Name
        if (!$MethodInfo.Name.Equals($name, [System.StringComparison]::Ordinal)) {
            $result
        }
    }
}



function GetDelegateParameters {
    param (
        [type]
        $Delegate
    )

    $invokeInfo = $Delegate.GetMethod('Invoke')
    if ($null -ne $invokeInfo) {
        $invokeInfo.GetParameters()
    }
}



function GetDelegateReturnType {
    param (
        [type]
        $Delegate
    )
    
    $invokeInfo = $Delegate.GetMethod('Invoke')
    if ($null -ne $invokeInfo) {
        $invokeInfo.ReturnType
    }
}



function DefineParameter {
    param (
        [System.Reflection.ParameterInfo]
        $ParameterInfo
    )
    
    $paramType = $ParameterInfo.ParameterType
    if ($paramType.HasElementType) {
        $elemType = $paramType.GetElementType()
        if ($paramType.IsByRef) {
            if (($ParameterInfo.Attributes -band [System.Reflection.ParameterAttributes]::Out) -ne 0) {
                "out $(ConvertTypeToFullName $elemType) $($ParameterInfo.Name)"
            } else {
                "ref $(ConvertTypeToFullName $elemType) $($ParameterInfo.Name)"
            }
        } else {
            "$(ConvertTypeToFullName $elemType)[] $($ParameterInfo.Name)"
        }
    } else {
        "$(ConvertTypeToFullName $paramType) $($ParameterInfo.Name)"
    }
}



function DefineAllParameters {
    param (
        [Urasandesu.Prig.Framework.PilotStubberConfiguration.IndirectionStub]
        $Stub
    )
    
    $paramInfos = GetDelegateParameters $Stub.IndirectionDelegate
    $paramNames = @()
    foreach ($paramInfo in $paramInfos) {
        $paramNames += DefineParameter $paramInfo
    }
    "($($paramNames -join ', '))"
}



function LoadParameter {
    param (
        [System.Reflection.ParameterInfo]
        $ParameterInfo
    )
    
    $paramType = $ParameterInfo.ParameterType
    if ($paramType.HasElementType) {
        $elemType = $paramType.GetElementType()
        if ($paramType.IsByRef) {
            if (($ParameterInfo.Attributes -band [System.Reflection.ParameterAttributes]::Out) -ne 0) {
                "out $($ParameterInfo.Name)"
            } else {
                "ref $($ParameterInfo.Name)"
            }
        } else {
            "$($ParameterInfo.Name)"
        }
    } else {
        "$($ParameterInfo.Name)"
    }
}



function LoadAllParameters {
    param (
        [Urasandesu.Prig.Framework.PilotStubberConfiguration.IndirectionStub]
        $Stub
    )
    
    $paramInfos = GetDelegateParameters $Stub.IndirectionDelegate
    $paramNames = @()
    foreach ($paramInfo in $paramInfos) {
        $paramNames += LoadParameter $paramInfo
    }
    $paramNames -join ', '
}



function Load1stParameter {
    param (
        [Urasandesu.Prig.Framework.PilotStubberConfiguration.IndirectionStub]
        $Stub
    )
    
    $paramInfos = GetDelegateParameters $Stub.IndirectionDelegate
    $paramNames = @()
    foreach ($paramInfo in $paramInfos) {
        $paramNames += LoadParameter $paramInfo
    }
    $paramNames[0]
}



function HasReturnType {
    param (
        [Urasandesu.Prig.Framework.PilotStubberConfiguration.IndirectionStub]
        $Stub
    )
    
    $retType = GetDelegateReturnType $Stub.IndirectionDelegate
    $retType -ne [void]
}



function ConvertTypeToGenericParameterConstraintClause {
    param (
        [type]
        $GenericArgument
    )

    $names = New-Object 'System.Collections.Generic.List[string]'
    $gpa = $GenericArgument.GenericParameterAttributes
    [System.Reflection.GenericParameterAttributes]$constraints = 0
    $constraints = $gpa -band [System.Reflection.GenericParameterAttributes]::SpecialConstraintMask
    if (($constraints -band [System.Reflection.GenericParameterAttributes]::NotNullableValueTypeConstraint) -ne 0) {
        $names.Add('struct')
    }

    if (($constraints -band [System.Reflection.GenericParameterAttributes]::ReferenceTypeConstraint) -ne 0) {
        $names.Add('class')
    }

    $typeConstraints = $GenericArgument.GetGenericParameterConstraints()
    foreach ($typeConstraint in $typeConstraints) {
        $fullName = ConvertTypeToFullName $typeConstraint
        if ($fullName -ne 'System.ValueType') {
            $names.Add($fullName)
        }
    }

    if (($constraints -band [System.Reflection.GenericParameterAttributes]::DefaultConstructorConstraint) -ne 0 -and 
        ($constraints -band [System.Reflection.GenericParameterAttributes]::NotNullableValueTypeConstraint) -eq 0) {
        $names.Add('new()')
    }

    if ($names.Count -eq 0) {
        $null
    } else {
        "where $($GenericArgument.Name) : $($names -join ', ')"
    }
}



function ConvertTypeToGenericParameterConstraints {
    param (
        [type]
        $Type
    )

    $constraintClauses = New-Object 'System.Collections.Generic.List[string]'
    if ($Type.IsGenericType) {
        foreach ($genericArg in $Type.GetGenericArguments()) {
            $constraintClause = ConvertTypeToGenericParameterConstraintClause $genericArg
            if ($null -eq $constraintClause) { continue }

            $constraintClauses.Add($constraintClause)
        }
    }

    $constraintClauses -join ' '
}



function ConvertStubToGenericParameterConstraints {
    param (
        [Urasandesu.Prig.Framework.PilotStubberConfiguration.IndirectionStub]
        $Stub
    )

    $constraintClauses = New-Object 'System.Collections.Generic.List[string]'
    if ($Stub.Target.IsGenericMethod) {
        foreach ($genericArg in $Stub.Target.GetGenericArguments()) {
            $constraintClause = ConvertTypeToGenericParameterConstraintClause $genericArg
            if ($null -eq $constraintClause) { continue }

            $constraintClauses.Add($constraintClause)
        }
    }

    $constraintClauses -join ' '
}



function ConvertTypeToStubName {
    param (
        [type]
        $Type
    )

    if ($Type.HasElementType) {
        $typeStubName = ConvertTypeToStubName $Type.GetElementType()
    } elseif (!$Type.IsGenericParameter -and $Type.IsNested) {
        $typeStubName = (ConvertTypeToStubName $Type.DeclaringType) + $Type.Name
    } else {
        $typeStubName = $Type.Name
    }

    if ($Type.IsByRef) {
        $typeStubName += "Ref"
    }

    if ($Type.IsArray) {
        if (1 -lt $Type.GetArrayRank()) {
            $typeStubName += $Type.GetArrayRank()
        } else {
            $typeStubName += "Array"
        }
    }

    if ($Type.IsPointer) {
        $typeStubName += "Ptr"
    }
    
    if ($Type.IsGenericType) {
        $genericArgs = $Type.GetGenericArguments()
        if ($Type.Name -match '`(\d+)') {
            $typeStubName = $typeStubName -replace '`\d+', ''
            $typeStubName += ConvertGenericArgumentsToStubName $genericArgs[($genericArgs.Length - ([int]$Matches[1]))..($genericArgs.Length - 1)]
        }
    }
    
    $typeStubName
}



function ConvertParameterInfoToStubName {
    param (
        [System.Reflection.ParameterInfo]
        $ParameterInfo
    )

    ConvertTypeToStubName $ParameterInfo.ParameterType
}



function ConvertGenericArgumentToStubName {
    param (
        [type]
        $GenericArgument
    )

    "Of" + (ConvertTypeToStubName $GenericArgument)
}



function ConvertParameterInfosToStubName {
    param (
        [System.Reflection.ParameterInfo[]]
        $ParameterInfos
    )

    $paramsStubName = ""
    if (0 -lt $ParameterInfos.Length) {
        $paramStubNames = New-Object "System.Collections.Generic.List[string]"
        foreach ($param in $ParameterInfos) {
            $paramStubNames.Add((ConvertParameterInfoToStubName $param))
        }
        $paramsStubName = [string]::Join('', $paramStubNames)
    }
    $paramsStubName
}



function ConvertGenericArgumentsToStubName {
    param (
        [type[]]
        $GenericArguments
    )

    $genericArgsStubName = ""
    if (0 -lt $GenericArguments.Length) {
        $genericArgStubNames = New-Object "System.Collections.Generic.List[string]"
        foreach ($genericArg in $GenericArguments) {
            $genericArgStubNames.Add((ConvertGenericArgumentToStubName $genericArg))
        }
        $genericArgsStubName = [string]::Join('', $genericArgStubNames)
    }
    $genericArgsStubName
}



function ConvertConstructorInfoToStubName {
    param (
        [System.Reflection.ConstructorInfo]
        $ConstructorInfo
    )

    $stubName = $(if ($ConstructorInfo.IsStatic) { "StaticConstructor" } else { "Constructor" })
    $paramsStubName = ConvertParameterInfosToStubName $ConstructorInfo.GetParameters() 
    $stubName + $paramsStubName
}



function ConvertMethodInfoToStubName {
    param (
        [System.Reflection.MethodInfo]
        $MethodInfo
    )

    $stubName = $MethodInfo.Name
    $stubName = $stubName -creplace '^get_(.*)', '$1Get'
    $stubName = $stubName -creplace '^set_(.*)', '$1Set'
    if ($stubName -cmatch '^op_Explicit(.*)' -or $stubName -cmatch '^op_Implicit(.*)') {
        $returnStubName = ConvertTypeToStubName $MethodInfo.ReturnType
    }
    $stubName = $stubName -creplace '^op_(.*)', '$1Op'
    $stubName = $stubName -creplace '^add_(.*)', 'Add$1'
    $stubName = $stubName -creplace '^remove_(.*)', 'Remove$1'
    if ($MethodInfo.IsGenericMethod) {
        $genericArgsStubName = ConvertGenericArgumentsToStubName $MethodInfo.GetGenericArguments()
    }

    $paramsStubName = ConvertParameterInfosToStubName $MethodInfo.GetParameters()

    $stubName + $genericArgsStubName + $(if ([string]::IsNullOrEmpty($returnStubName)) { $paramsStubName } else { $returnStubName })
}



function ConvertToIndirectionStubName {
    param (
        [System.Reflection.MethodBase]
        $MethodBase
    )

    switch ($MethodBase) {
        { $_ -is [System.Reflection.ConstructorInfo] } {  
            ConvertConstructorInfoToStubName $MethodBase
        }
        { $_ -is [System.Reflection.MethodInfo] } {  
            $result = GetExplicitlyImplementedInterface $MethodBase
            if ($null -eq $result) {
                ConvertMethodInfoToStubName $MethodBase
            } else {
                ($result.Interface.Namespace -replace '\.', '') + 
                    (ConvertTypeToStubName $result.Interface) + 
                    (ConvertMethodInfoToStubName $result.InterfaceMethod)
            }
        }
    }
}



function ConvertTypeToGenericParameterArray {
    param (
        [type]
        $Type
    )

    $typeofParams = New-Object 'System.Collections.Generic.List[string]'
    if ($Type.IsGenericType) {
        foreach ($genericArg in $Type.GetGenericArguments()) {
            if ($genericArg.IsGenericParameter) {
                $typeofParams.Add(("typeof({0})" -f $genericArg.Name))
            } else {
                $typeofParams.Add('null')
            }
        }
    }

    "new Type[] {{ {0} }}" -f ($typeofParams -join ', ')
}



function ConvertStubToGenericParameterArray {
    param (
        [Urasandesu.Prig.Framework.PilotStubberConfiguration.IndirectionStub]
        $Stub
    )

    $typeofParams = New-Object 'System.Collections.Generic.List[string]'
    if ($Stub.Target.IsGenericMethod) {
        foreach ($genericArg in $Stub.Target.GetGenericArguments()) {
            if ($genericArg.IsGenericParameter) {
                $typeofParams.Add(("typeof({0})" -f $genericArg.Name))
            } else {
                $typeofParams.Add('null')
            }
        }
    }

    "new Type[] {{ {0} }}" -f ($typeofParams -join ', ')
}



function ConvertStubToStubsXml {
    param (
        [Urasandesu.Prig.Framework.PilotStubberConfiguration.IndirectionStub]
        $Stub
    )

    @"
@"<?xml version=""1.0"" encoding=""utf-8""?>
<stubs>
  <add name=""{0}"" alias=""{1}"">
    {2}
  </add>
</stubs>"
"@ -f $Stub.Name, $Stub.Alias, ($Stub.Xml -replace '"', '""')
}



. $(Join-Path $here Chocolatey.Add-PrigAssembly.ps1)
. $(Join-Path $here Chocolatey.Remove-PrigAssembly.ps1)
. $(Join-Path $here Chocolatey.ConvertTo-PrigAssemblyName.ps1)
. $(Join-Path $here Chocolatey.ConvertTo-ProcessorArchitectureString.ps1)
. $(Join-Path $here Chocolatey.Disable-PrigTestAdapter.ps1)
. $(Join-Path $here Chocolatey.Enable-PrigTestAdapter.ps1)
. $(Join-Path $here Chocolatey.Find-IndirectionTarget.ps1)
. $(Join-Path $here Chocolatey.Get-AssemblyNameExs.ps1)
. $(Join-Path $here Chocolatey.Get-AssemblyNameExsFrom.ps1)
. $(Join-Path $here Chocolatey.Get-IndirectionStubSetting.ps1)
. $(Join-Path $here Chocolatey.Get-PackageName.ps1)
. $(Join-Path $here Chocolatey.Get-PackageToolsPath.ps1)
. $(Join-Path $here Chocolatey.New-PrigCsproj.ps1)
. $(Join-Path $here Chocolatey.New-PrigProxiesCs.ps1)
. $(Join-Path $here Chocolatey.New-PrigStubsCs.ps1)
. $(Join-Path $here Chocolatey.New-PrigTokensCs.ps1)
. $(Join-Path $here Chocolatey.Start-PrigSetup.ps1)





Export-ModuleMember -Function *-* -Alias *
tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Remove-PrigAssembly.ps1
# 
# File: Chocolatey.Remove-PrigAssembly.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#

function Remove-PrigAssembly {
<#
    .SYNOPSIS
        Removes the stub settings file for the specified assembly on the Package Manager Console or the Prig setup session.

    .DESCRIPTION
        This command removes the stub setting file that is added by `Add-PrigAssembly` from a project on the Package Manager Console or the Prig setup session.
        Target project is the value that is selected as `Default project: ` on the Package Manager Console. After the file is removed, you will get the confirmation message that the project has been modified externally, so reload the project.

    .PARAMETER  PrigAssembly
        A Prig assembly name.
        If it can't recognize uniquely, the error "Ambiguous match found" will be occurred. So, you have to specify a more detailed Prig assembly name.
        You can also refer to the PrigAssembly parameter by its built-in alias, "pa".

    .PARAMETER  Project
        A `EnvDTE.DTE` object that removes Prig assembly.
        This API supports the Prig infrastructure and is not intended to be used directly from your code.

    .EXAMPLE
        Remove-PrigAssembly -PrigAssembly mscorlib
        
        DESCRIPTION
        -----------
        This command removes the stub setting file for the assembly `mscorlib` from the target project.

    .INPUTS
        System.String

    .OUTPUTS
        None

    .NOTES
        You can also refer to the Remove-PrigAssembly command by its built-in alias, "PRemove".

    .LINK
        Add-PrigAssembly

    .LINK
        Start-PrigSetup

#>

    [CmdletBinding()]
    param (
        [Alias("pa")]
        [Parameter(Mandatory = $true)]
        [string]
        $PrigAssembly, 

        $Project
    )

    # $ProjectFullName are only enabled in Prig setup session. See also `Import-PrigSetupSession.ps1`.
    $projFullName = $ProjectFullName
    if ($null -eq $projFullName) {
        $envProj = $(if ($null -eq $Project) { (Get-Project).Object.Project } else { $Project.Object.Project })
        $projFullName = $envProj.FullName

        [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Build')
        $msbProjCollection = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection
        $allMsbProjs = $msbProjCollection.GetLoadedProjects($projFullName).GetEnumerator()
        if(!$allMsbProjs.MoveNext()) {
            throw New-Object System.InvalidOperationException ('"{0}" has not been loaded.' -f $projFullName)
        }
        $curMsbProj = $allMsbProjs.Current
    }

    $powershell = 'powershell'

    $removePrigAssembly = [System.IO.Path]::Combine((Get-PackageToolsPath), 'Remove-PrigAssembly.ps1')
    $argList = '-NonInteractive', '-NoLogo', '-NoProfile', '-File', """$removePrigAssembly""", """$projFullName""", """$PrigAssembly"""
    if ($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) {
        $argList += '-Verbose'
    }

    $tmpFileName = [System.IO.Path]::GetTempFileName()

    Start-Process $powershell $argList -Wait -RedirectStandardError $tmpFileName -NoNewWindow
    $errors = Get-Content $tmpFileName
    if (0 -lt $errors.Length) {
        $Host.UI.WriteErrorLine($errors -join "`r`n")
    }

    Remove-Item $tmpFileName -ErrorAction SilentlyContinue
}

New-Alias PRemove Remove-PrigAssembly

tools\Urasandesu.Prig\Urasandesu\Prig\Chocolatey.Start-PrigSetup.ps1
# 
# File: Chocolatey.Start-PrigSetup.ps1
# 
# Author: Akira Sugiura ([email protected])
# 
# 
# Copyright (c) 2012 Akira Sugiura
#  
#  This software is MIT License.
#  
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#  
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#



function Start-PrigSetup {
<#
    .SYNOPSIS
        Starts the Prig setup session.

    .DESCRIPTION
        The Prig setup session is a special PowerShell session to add the indirection stub settings and analyze target assemblies. In this session, you can access all information of the assemblies that are referenced from current project through the global variable `$ReferencedAssemblies`.

    .PARAMETER  NoIntro
        Omits the introduction help that is displayed when startup the session.

    .PARAMETER  AdditionalInclude
        A referenced assembly name that is used as additional `Include`.
        This API supports the Prig infrastructure and is not intended to be used directly from your code.

    .PARAMETER  EditorialInclude
        A referenced assembly name that is used as editorial `Include`.
        This API supports the Prig infrastructure and is not intended to be used directly from your code.

    .PARAMETER  DeletionalInclude
        A referenced assembly name that is used as deletional `Include`.
        This API supports the Prig infrastructure and is not intended to be used directly from your code.

    .PARAMETER  Project
        A `EnvDTE.DTE` object that adds Prig assembly.
        This API supports the Prig infrastructure and is not intended to be used directly from your code.

    .EXAMPLE
        PM> Start-PrigSetup
        
        ------- (The following commands are executed in new PowerShell window)
        Welcome to Prig setup session!!
        
        
        You can add the indirection settings from here. In this session, you can use `$ReferencedAssemblies` that contains all referenced assemblies information of current project. For example, if you want to get the indirection settings for all members of the type `Foo` that belongs to the referenced assembly `UntestableLibrary`, the following commands will achieve it:
        
        PS> $ReferencedAssemblies
        
        FullName
        --------
        mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        MyLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
        UntestableLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
        
        
        PS> padd -ra $ReferencedAssemblies[-1]
        PS> $ReferencedAssemblies[-1].GetTypes() | ? { $_.Name -eq 'Foo' } | pfind | pget | clip
        PS> exit   # Then, paste the content on the clipboard to the stub setting file(e.g. `UntestableLibrary.v4.0.30319.v1.0.0.0.prig`).
        
        
        
        See also the command's help `padd`, `pfind` and `pget`.
        
        
        
        Current Project: MyLibraryTest
        WARNING: Change the Current Project from `Default Project: ` on the Package Manager Console if it isn't what you want.
        
        


        DESCRIPTION
        -----------
        In this example, start the Prig setup session from the Package Manager Console. When the Prig setup session is started, new PowerShell window is opened with the introduction help like the above.

    .EXAMPLE
        PM> pstart -NoIntro
        
        ------- (The following commands are executed in new PowerShell window)
        Current Project: MyLibraryTest
        WARNING: Change the Current Project from `Default Project: ` on the Package Manager Console if it isn't what you want.
        
        
        PS> $ReferencedAssemblies
        
        FullName
        --------
        mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
        System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
        System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        
        
        PS> $ReferencedAssemblies | ? { $_.FullName -cmatch 'Con' }
        
        FullName
        --------
        System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
        
        
        PS> padd -ra ($ReferencedAssemblies | ? { $_.FullName -cmatch 'Con' })
        PS>


        DESCRIPTION
        -----------
        In this example, start the Prig setup session without the introduction help when opened. Then, confirm the assemblies that are referenced from current project, choose `System.Configuration` from those assemblies, and add the indirection stub setting.

    .INPUTS
        None

    .OUTPUTS
        None

    .NOTES
        You can also refer to the Start-PrigSetup command by its built-in alias, "PStart".

    .LINK
        Add-PrigAssembly

    .LINK
        Find-IndirectionTarget

    .LINK
        Get-IndirectionStubSetting

    .LINK
        Remove-PrigAssembly

#>

    [CmdletBinding()]
    param (
        [switch]
        $NoIntro, 

        [string]
        $AdditionalInclude, 

        [string]
        $EditorialInclude, 

        [string]
        $DeletionalInclude, 

        $Project
    )

    $envProj = $(if ($null -eq $Project) { (Get-Project).Object.Project } else { $Project.Object.Project })
    if (!$envProj.Saved) {
        $envProj.Save($envProj.FullName)
    }

    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Build')
    $msbProjCollection = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection
    $allMsbProjs = $msbProjCollection.GetLoadedProjects($envProj.FullName).GetEnumerator()
    if(!$allMsbProjs.MoveNext()) {
        throw New-Object System.InvalidOperationException ('"{0}" has not been loaded.' -f $envProj.FullName)
    }

    $curMsbProj = $allMsbProjs.Current
    
    $toolsPath = [IO.Path]::Combine($env:URASANDESU_PRIG_PACKAGE_FOLDER, 'tools')
    $importPrigSetupSession = [IO.Path]::Combine($toolsPath, 'Import-PrigSetupSession.ps1')

    $os = Get-WmiObject Win32_OperatingSystem
    [System.Reflection.ProcessorArchitecture]$osArch = 0
    $osArch = $(if ($os.OSArchitecture -match '64') { 'Amd64' } else { 'X86' })
    Write-Verbose ('OS Architecture: {0}' -f $osArch)

    $projPlatform = $curMsbProj.ExpandString('$(Platform)')
    if ($projPlatform -eq 'AnyCPU') {
        $projPlatform += ('|{0}' -f $curMsbProj.ExpandString('$(Prefer32Bit)'))
    }
    [System.Reflection.ProcessorArchitecture]$projArch = 0
    $projArch = ConvertTo-ProcessorArchitectureString $projPlatform
    Write-Verbose ('Project Architecture: {0}' -f $projArch)

    [System.Reflection.ProcessorArchitecture]$arch = 0
    $arch = $(if ($projArch -eq 'MSIL') { $osArch } else { $projArch })
    Write-Verbose ('Result Architecture: {0}' -f $arch)

    $powershell = $(if ($arch -eq 'Amd64') { '%windir%\SysNative\WindowsPowerShell\v1.0\powershell.exe' } else { '%windir%\system32\WindowsPowerShell\v1.0\powershell.exe' })
    $powershell = [System.Environment]::ExpandEnvironmentVariables($powershell)
    Write-Verbose ('PowerShell: {0}' -f $powershell)

    $outPath = $curMsbProj.ExpandString('$(OutputPath)')
    Write-Verbose ('OutputPath: {0}' -f $outPath)

    $refIncludes = New-Object 'System.Collections.Generic.List[string]' 
    $refHints =  New-Object 'System.Collections.Generic.List[string]'
    $refs = 
        $curMsbProj.GetItems('Reference') | 
            select @{ Name = "Include"; Expression = { $_.EvaluatedInclude } }, 
                   @{ Name = "HintPath"; Expression = { @($_.Metadata | ? { $_.Name -eq 'HintPath' })[0].EvaluatedValue }}
    foreach ($ref in $refs) {
        $refIncludes.Add($ref.Include)
        $refHints.Add($ref.HintPath)
    }
    $refInclude = $refIncludes -join ';'
    $refHint =  $refHints -join ';'
    Write-Verbose ('ReferenceInclude: {0}' -f $refInclude)
    Write-Verbose ('ReferenceHintPath: {0}' -f $refHint)

    $projRefIncludes = New-Object 'System.Collections.Generic.List[string]' 
    $projRefs = 
        $curMsbProj.GetItems('ProjectReference') | 
            select @{ Name = "Include"; Expression = { $_.EvaluatedInclude } }
    foreach ($projRef in $projRefs) {
        $projRefFullName = Resolve-Path ([System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($envProj.FullName), $projRef.Include))
        $allMsbProjs = $msbProjCollection.GetLoadedProjects($projRefFullName).GetEnumerator()
        if(!$allMsbProjs.MoveNext()) {
            throw New-Object System.InvalidOperationException ('"{0}" has not been loaded.' -f $projRefFullName)
        }

        $refMsbProj = $allMsbProjs.Current
        $projRefIncludes.Add($refMsbProj.ExpandString('$(TargetPath)'))
    }
    $projRefInclude = $projRefIncludes -join ';'
    Write-Verbose ('ProjectReferenceInclude: {0}' -f $projRefInclude)

    $targetFrmwrkVer = $curMsbProj.ExpandString('$(TargetFrameworkVersion)')
    $argList = '-NoLogo', '-File', """$importPrigSetupSession""", """$($envProj.Name)""", """$($envProj.FullName)""", """$targetFrmwrkVer""", """$outPath.""", """$refInclude""", """$refHint""", """$projRefInclude"""
    $shouldBeAutomated = ![string]::IsNullOrEmpty($AdditionalInclude) -or ![string]::IsNullOrEmpty($DeletionalInclude)
    if (!$shouldBeAutomated) {
        $argList = ,'-NoExit' + $argList
    }
    if ($targetFrmwrkVer -eq 'v3.5') {
        $argList = '-Version', '2' + $argList
    }
    if ($NoIntro) {
        $argList += '-NoIntro'
    }
    if (![string]::IsNullOrEmpty($AdditionalInclude)) {
        $argList += "-AdditionalInclude ""$AdditionalInclude"""
    }
    if (![string]::IsNullOrEmpty($EditorialInclude)) {
        $argList += "-EditorialInclude ""$EditorialInclude"""
    }
    if (![string]::IsNullOrEmpty($DeletionalInclude)) {
        $argList += "-DeletionalInclude ""$DeletionalInclude"""
    }
    if ($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) {
        $argList += '-Verbose'
    }
    Write-Verbose ('Argument List: {0}' -f ($argList -join ' '))

    $tmpFileName = [System.IO.Path]::GetTempFileName()

    Start-Process $powershell $argList -Wait -WindowStyle $(if ($shouldBeAutomated) { 'Hidden' } else { 'Normal' }) -RedirectStandardError $tmpFileName
    $errors = Get-Content $tmpFileName
    Remove-Item $tmpFileName -ErrorAction SilentlyContinue
    if (0 -lt $errors.Length) {
        $msg = $errors -join "`r`n"
        if ($shouldBeAutomated) {
            throw New-Object System.InvalidOperationException $msg
        } else {
            $Host.UI.WriteErrorLine($msg)
        }
    }
}

New-Alias PStart Start-PrigSetup
tools\x64\Urasandesu.Prig.dll
 
tools\x86\Urasandesu.Prig.dll
 

Log in or click on link to see number of positives.

In cases where actual malware is found, the packages are subject to removal. Software sometimes has false positives. Moderators do not necessarily validate the safety of the underlying software, only that a package retrieves software from the official distribution point and/or validate embedded software against official distribution point (where distribution rights allow redistribution).

Chocolatey Pro provides runtime protection from possible malware.

Version Downloads Last Updated Status
Prig - Open Source Alternative to Microsoft Fakes 2.3.1 648 Sunday, August 14, 2016 Approved
Prig - Open Source Alternative to Microsoft Fakes 2.3.0 408 Friday, April 29, 2016 Approved
Prig - Open Source Alternative to Microsoft Fakes 2.2.0 303 Sunday, February 21, 2016 Approved
Prig - Open Source Alternative to Microsoft Fakes 2.1.1 267 Saturday, January 23, 2016 Approved
Prig - Open Source Alternative to Microsoft Fakes 2.1.0 278 Sunday, December 20, 2015 Approved
Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha06 293 Friday, September 18, 2015 Exempted
Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha05 276 Saturday, August 1, 2015 Exempted
Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha04 322 Wednesday, May 27, 2015 Exempted

Version 2.0.0-alpha06

  • Fixed #45: Support Visual Studio 2015
  • Fixed #44: Namespace reference not added for parameter that is array type
    [NOTICE] This issue has already been fixed in the family of V2. We just applied the fix to the family of V1.
  • Improve installation robustness. The ExecutionPolicy of PowerShell that is invoked during build tasks was sometimes unexpected, so modify to set explicit value.
  • Enhance supported signature. The unusual types that appear on the interface of a method is almost supported. For example, T[,][](T is a generic type parameter), List&lt;DateTime[]&gt;[,], out M[][,](M is a generic method parameter) and so on.
  • Prepare to support three or more out/ref parameters. By decreasing the dependencies of an indirection stub that profiler used, performance is also improved.

Version 2.0.0-alpha05

  • Improve stability for the methods of the classes that are used on the boundary of application domains(e.g. AppDomain, BinaryReader, MemoryStream, Thread and so on).
  • Improve usability for the command to manage Prig a little(See also the Wiki).
  • Merge Infrastructure Bug Fix(See also Swathe issues #2)
  • Make the sequence that builds the indirection stub dll more efficient.

Version 2.0.0-alpha04

  • Update NUnit Test Adapter for Prig from based on 1.2.0 to based on 2.0.0.
  • [BREAKING CHANGE] To fix the following issues, alpha04 has lost compatibility with alpha03. Also, choco upgrade command cannot even work. I will publish the migration steps in this page as soon as possible.
  • Fixed #41: Error in remove prig assembly
  • Fixed #40: Test engine crashes while trying to execute a unit test without indirections context even when it doesn't use any stubs
  • Fixed #37: Suggestion add prig files as Copy If Newer to output directory
  • Fixed #33: Make framework assemblies private.
  • Implemented Experimentally #31: Issue with out parameters
  • Merge Infrastructure Enhancement(See also Swathe issues #1)
  • Fixed #36: If an assembly is added-removed multiple times there is duplicated prebuild steps
  • Fixed #35: Rebuilding after .prig file had types removed still contains removed types in prig assembly
  • Fix error when enabling Test Adapter and no vstest running
  • Fix more generation issues
  • Response to Strange Behavior. Depending on the replacing method, the static method of the infrastructure is sometimes called before initializing the field of the type. For example, you will find the behavior if you try a sample of Generics with Prig v2.0.0-alpha03 in Visual Studio integrated environment. It seems very strange behavior, but we have to consider that in this layer.

Version 2.0.0-alpha03

  • Improve stability a little. Support the test runners that have never been able to run. The test runners like NUnit(GUI)/xUnit.net/MbUnit couldn't even start up until now(They were raising ExecutionEngineException).

Version 2.0.0-alpha02

  • Fixed #29: Support Chocolatey v0.9.9.

Version 2.0.0-alpha01

  • [NOTICE] Changed the package management system to Chocolatey from NuGet.
  • [NOTICE] Supported Visual Studio integrated environment.

Version 1.1.0

  • Release 1.1.
  • Fixed #26: Prig assembly shouldn't need InternalsVisibleToAttribute.
  • Fixed #27: Test stalled if adding the indirection settings for all members of DateTime.
  • Fixed #28: The indirect tests sometimes fail.
  • Supported the feature "Prig setup session" that makes adding the indirection stub settings more easier.

Version 1.0.0

  • Release 1.
  • Fixed #25: Default parameterized method can't call indirectly.

About more previous versions, please see https://github.com/urasandesu/Prig/releases.

Discussion for the Prig: Open Source Alternative to Microsoft Fakes Package

Ground Rules:

  • This discussion is only about Prig: Open Source Alternative to Microsoft Fakes and the Prig: Open Source Alternative to Microsoft Fakes package. If you have feedback for Chocolatey, please contact the Google Group.
  • This discussion will carry over multiple versions. If you have a comment about a particular version, please note that in your comments.
  • The maintainers of this Chocolatey Package will be notified about new comments that are posted to this Disqus thread, however, it is NOT a guarantee that you will get a response. If you do not hear back from the maintainers after posting a message below, please follow up by using the link on the left side of this page or follow this link to contact maintainers. If you still hear nothing back, please follow the package triage process.
  • Tell us what you love about the package or Prig: Open Source Alternative to Microsoft Fakes, or tell us what needs improvement.
  • Share your experiences with the package, or extra configuration or gotchas that you've found.
  • If you use a url, the comment will be flagged for moderation until you've been whitelisted. Disqus moderated comments are approved on a weekly schedule if not sooner. It could take between 1-5 days for your comment to show up.
comments powered by Disqus