Unpacking Software Livestream

Join our monthly Unpacking Software livestream to hear about the latest news, chat and opinion on packaging, software deployment and lifecycle management!

Learn More

Chocolatey Product Spotlight

Join the Chocolatey Team on our regular monthly stream where we put a spotlight on the most recent Chocolatey product releases. You'll have a chance to have your questions answered in a live Ask Me Anything format.

Learn More

Chocolatey Coding Livestream

Join us for the Chocolatey Coding Livestream, where members of our team dive into the heart of open source development by coding live on various Chocolatey projects. Tune in to witness real-time coding, ask questions, and gain insights into the world of package management. Don't miss this opportunity to engage with our team and contribute to the future of Chocolatey!

Learn More

Calling All Chocolatiers! Whipping Up Windows Automation with Chocolatey Central Management

Webinar from
Wednesday, 17 January 2024

We are delighted to announce the release of Chocolatey Central Management v0.12.0, featuring seamless Deployment Plan creation, time-saving duplications, insightful Group Details, an upgraded Dashboard, bug fixes, user interface polishing, and refined documentation. As an added bonus we'll have members of our Solutions Engineering team on-hand to dive into some interesting ways you can leverage the new features available!

Watch On-Demand
Chocolatey Community Coffee Break

Join the Chocolatey Team as we discuss all things Community, what we do, how you can get involved and answer your Chocolatey questions.

Watch The Replays
Chocolatey and Intune Overview

Webinar Replay from
Wednesday, 30 March 2022

At Chocolatey Software we strive for simple, and teaching others. Let us teach you just how simple it could be to keep your 3rd party applications updated across your devices, all with Intune!

Watch On-Demand
Chocolatey For Business. In Azure. In One Click.

Livestream from
Thursday, 9 June 2022

Join James and Josh to show you how you can get the Chocolatey For Business recommended infrastructure and workflow, created, in Azure, in around 20 minutes.

Watch On-Demand
The Future of Chocolatey CLI

Livestream from
Thursday, 04 August 2022

Join Paul and Gary to hear more about the plans for the Chocolatey CLI in the not so distant future. We'll talk about some cool new features, long term asks from Customers and Community and how you can get involved!

Watch On-Demand
Hacktoberfest Tuesdays 2022

Livestreams from
October 2022

For Hacktoberfest, Chocolatey ran a livestream every Tuesday! Re-watch Cory, James, Gary, and Rain as they share knowledge on how to contribute to open-source projects such as Chocolatey CLI.

Watch On-Demand

Downloads:

6,995

Downloads of v 2.0.0-alpha01:

449

Last Update:

01 Mar 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.

  • 1
  • 2
  • 3

2.0.0-alpha01 | Updated: 01 Mar 2015

Downloads:

6,995

Downloads of v 2.0.0-alpha01:

449

Maintainer(s):

Software Author(s):

  • Akira Sugiura

Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha01

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

  • 1
  • 2
  • 3

Some Checks Have Failed or Are Not Yet Complete

Not All Tests Have Passed


Validation Testing Unknown


Verification Testing Unknown


Scan Testing Successful:

No detections found in any package files

Details
Learn More

Deployment Method: Individual Install, Upgrade, & Uninstall

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:

>

Deployment Method:

NOTE

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

1. Enter Your Internal Repository Url

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


2. Setup Your Environment

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

2. Get the package into your environment

  • 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://community.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. Copy Your Script

choco upgrade prig -y --source="'INTERNAL REPO URL'" --version="'2.0.0-alpha01'" --prerelease [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="'INTERNAL REPO URL'" --version="'2.0.0-alpha01'" --prerelease
$exitCode = $LASTEXITCODE

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

Exit $exitCode

- name: Install prig
  win_chocolatey:
    name: prig
    version: '2.0.0-alpha01'
    source: INTERNAL REPO URL
    state: present
    allow_prerelease: yes

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


chocolatey_package 'prig' do
  action    :install
  source   'INTERNAL REPO URL'
  version  '2.0.0-alpha01'
  options  '--prerelease'
end

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


cChocoPackageInstaller prig
{
    Name        = "prig"
    Version     = "2.0.0-alpha01"
    Source      = "INTERNAL REPO URL"
    chocoParams = "--prerelease"
}

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


package { 'prig':
  ensure          => '2.0.0-alpha01',
  install_options => ['--prerelease'],
  provider        => 'chocolatey',
  source          => 'INTERNAL REPO URL',
}

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


4. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

WARNING

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.


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
        Invoke-Prig

    .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.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.

    .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
        Invoke-Prig

    .LINK
        Start-PrigSetup

#>

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

    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) {
                    foreach ($indirectlyCallable in $indirectlyCallables) {
                        if ($indirectlyCallable.ToString() -match $Method) {
                            $indirectlyCallable
                        }
                    }
                } else {
                    $indirectlyCallables
                }
            }
        }
    } end {

    }
}

New-Alias PFind Find-IndirectionTarget
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.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()
        }
    }

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

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

    [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
    $targetDir = $curMsbProj.ExpandString('$(TargetDir)')

    [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.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.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.psd1
 
tools\Urasandesu.Prig\format.ps1xml
 
tools\Urasandesu.Prig.snk
 
tools\Prig.vsix
 
tools\prig.exe
 
tools\Prig.2.0.0-alpha01.nupkg.zip
 
tools\PilotStubber.prig
 
tools\NUnitTestAdapterForPrig.1.2.nupkg.zip
 
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, 
    
    [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 ('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)

$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
}
 
$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
}

$workDir = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($Settings), (ConvertTo-PrigAssemblyName $asmInfo))
if (![string]::IsNullOrEmpty($workDir) -and ![IO.Directory]::Exists($workDir)) {
    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\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
)

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)

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($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\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.
#


'  Uninstalling Prig.vsix...'
cmd /c '" "%VS120COMNTOOLS%VsDevCmd.bat" & vsixinstaller /q /u:0a06101d-8de3-40c4-b083-c5c16ca227ae "'


$asms = 'Urasandesu.NAnonym, Version=0.2.0.0, Culture=neutral, PublicKeyToken=ce9e95b04334d5fb, processorArchitecture=MSIL', 
        'Urasandesu.Prig.Framework, Version=0.1.0.0, Culture=neutral, PublicKeyToken=acabb3ef0ebf69ce, processorArchitecture=MSIL'
foreach ($asm in $asms) {
    "  Unregistering the assembly '$asm' from GAC..."
    cmd /c ('" "%VS120COMNTOOLS%VsDevCmd.bat" & gacutil /nologo /u "{0}" "' -f $asm)
}


$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'..."
$nuget = [IO.Path]::Combine($env:ChocolateyInstall, 'chocolateyinstall\NuGet.exe')
if (0 -lt @(& $nuget sources list | ? { $_ -match 'Prig Source' }).Length) {
    & $nuget sources remove -name $name
}
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.
#


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


$srcList = Resolve-Path ($toolsPath + '\*.zip')
foreach ($src in $srcList) {
    $dst = $src -replace '\.zip$', ''
    "  Renaming '$src' to '$dst'..."
    Move-Item $src $dst -Force
}


$name = "Prig Source"
$source = $env:chocolateyPackageFolder
"  Registering the nuget source '$source' as '$name'..."
$nuget = [IO.Path]::Combine($env:ChocolateyInstall, 'chocolateyinstall\NuGet.exe')
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
}


$asms = [System.IO.Path]::Combine($env:chocolateyPackageFolder, 'lib\net35\Urasandesu.NAnonym.dll'), 
        [System.IO.Path]::Combine($env:chocolateyPackageFolder, 'lib\net35\Urasandesu.Prig.Framework.dll'), 
        [System.IO.Path]::Combine($env:chocolateyPackageFolder, 'lib\net40\Urasandesu.NAnonym.dll'), 
        [System.IO.Path]::Combine($env:chocolateyPackageFolder, 'lib\net40\Urasandesu.Prig.Framework.dll')
foreach ($asm in $asms) {
    "  Registering the assembly '$asm' to GAC..."
    cmd /c ('" "%VS120COMNTOOLS%VsDevCmd.bat" & gacutil /f /nologo /i "{0}" "' -f $asm)
}


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

Install-ChocolateyVsixPackage $packageName $vsixUrl
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.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.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 = IndirectionDelegates.CreateDelegateOfDefaultBehavior$(ConvertTypeToClassName $stub.IndirectionDelegate)(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 = IndirectionDelegates.CreateDelegateOfDefaultBehaviorUntyped(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.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 holder = LooseCrossDomainAccessor.GetOrRegister<IndirectionHolder<$(ConvertTypeToClassName $stub.IndirectionDelegate)>>();
                    return holder.GetOrDefault(Info);
                }
                set
                {
                    var holder = LooseCrossDomainAccessor.GetOrRegister<IndirectionHolder<$(ConvertTypeToClassName $stub.IndirectionDelegate)>>();
                    if (value == null)
                    {
                        holder.Remove(Info);
                    }
                    else
                    {
                        holder.AddOrUpdate(Info, value);
                        RuntimeHelpers.PrepareDelegate(Body);
                    }
                }
            }

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

            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 ? IndirectionDelegates.CreateDelegateOfDefaultBehavior$(ConvertTypeToClassName $stub.IndirectionDelegate)(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 = IndirectionDelegates.CreateDelegateExecutingDefaultOr$(ConvertTypeToClassName $stub.IndirectionDelegate)(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 holder = LooseCrossDomainAccessorUntyped.GetOrRegister(Stub.Target, Stub.IndirectionDelegate, $(ConvertTypeToGenericParameterArray $declTypeGrouped.Key), $(ConvertStubToGenericParameterArray $stub));
                    return holder.GetOrDefault(Info);
                }
                set
                {
                    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 = IndirectionDelegates.CreateDelegateOfDefaultBehaviorUntyped(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 ? IndirectionDelegates.CreateDelegateOfDefaultBehaviorUntyped(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 = IndirectionDelegates.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.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.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.

    .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".

    .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
        If you added the stub setting files once, it can only remove manually. Let's say you mistake the project that should be selected as `Default project: `. In this case, you have to remove the tags `Reference`, `None`, `PreBuildEvent` that are matched the regular expression `\.prig"`.

        Also, you can't set up the stub settings for multiple assemblies to one file. If you set up such setting, you will get the build error.
        
        You can also refer to the Add-PrigAssembly command by its built-in alias, "PAdd".

    .LINK
        Find-IndirectionTarget

    .LINK
        Get-IndirectionStubSetting

    .LINK
        Invoke-Prig

    .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
    if (0 -lt $errors.Length) {
        $Host.UI.WriteErrorLine($errors -join "`r`n")
    }

    Remove-Item $tmpFileName -ErrorAction SilentlyContinue
}

New-Alias PAdd Add-PrigAssembly

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.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
    )
    
    $defName = $Type.FullName
    
    if (!$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) {
        $defName = $Type.Name
    } elseif ($Type.IsGenericParameter) {
        $defName = $Type.Name
    }

    if ($Type.IsGenericType) {
        $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 ', ') + ">")
        }
    }

    $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 GetExplicitlyImplementedInterface {
    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
        }

        $name = ""
        if ($mapping.InterfaceMethods[$index] -ne $null) {
            $interfaceMethod = $mapping.InterfaceMethods[$index]
            $name = $interfaceMethod.Name
            if (!$MethodInfo.Name.Equals($name, [System.StringComparison]::Ordinal)) {
                return New-Object psobject | 
                            Add-Member NoteProperty 'Interface' $interface -PassThru | 
                            Add-Member NoteProperty 'InterfaceMethod' $interfaceMethod -PassThru
            }
        }
    }

    $null
}



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()) {
            $typeofParams.Add(("typeof({0})" -f $genericArg.Name))
        }
    }

    "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()) {
            $typeofParams.Add(("typeof({0})" -f $genericArg.Name))
        }
    }

    "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.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.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.

    .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
        Invoke-Prig

#>

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

        [string]
        $AdditionalInclude, 

        [string]
        $EditorialInclude, 

        $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"""
    if ([string]::IsNullOrEmpty($AdditionalInclude)) {
        $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 ($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) {
        $argList += '-Verbose'
    }
    Write-Verbose ('Argument List: {0}' -f ($argList -join ' '))

    Start-Process $powershell $argList -Wait -WindowStyle $(if (![string]::IsNullOrEmpty($AdditionalInclude)) { 'Hidden' } else { 'Normal' })
}

New-Alias PStart Start-PrigSetup
tools\x64\Urasandesu.Prig.dll
 
tools\x86\Urasandesu.Prig.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' } else { '%windir%\system32\WindowsPowerShell\v1.0\powershell.exe' })
    $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'
        $argReferenceFrom = '-ReferenceFrom "@(''{0}\net35\Urasandesu.NAnonym.dll'',''{0}\net35\Urasandesu.Prig.Framework.dll'')"' -f $libPath
    } else {
        $argOther = '-NoLogo -NoProfile'
        $argReferenceFrom = '-ReferenceFrom "@(''{0}\net40\Urasandesu.NAnonym.dll'',''{0}\net40\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
    $cmd = 'cmd /c " "%VS120COMNTOOLS%VsDevCmd.bat" & {0} {1} {2} {3} {4} {5} {6} {7} {8} "' -f 
                $powershell, 
                $argOther, 
                $argFile, 
                $argReferenceFrom, 
                $argAssembly, 
                $argTargetFrameworkVersion, 
                $argKeyFile, 
                $argOutputPath, 
                $argSettings
        

    if ($Platform -match 'AnyCPU') {
        $condition = "'`$(Platform)|`$(Prefer32Bit)' == '$Platform'"
    } else {
        $condition = "'`$(Platform)' == '$Platform'"
    }
    
    $preBuildEvents = 
        $MSBuildProject.Xml.Properties | 
            Where-Object { $_.Name -eq 'PreBuildEvent' } | 
            Where-Object { $_.Value -cmatch '\bPrig\b' } | 
            Where-Object { $_.Parent.Condition -eq $condition }
    
    if (0 -lt $preBuildEvents.Length) {
        $preBuildEvents[0].Value += "`r`n$cmd"
    } else {
        $propGroup = $MSBuildProject.Xml.CreatePropertyGroupElement()
        $MSBuildProject.Xml.InsertAfterChild($propGroup, @($MSBuildProject.Xml.Imports)[-1])
        $propGroup.Condition = $condition
        [void]$propGroup.AddProperty('PreBuildEvent', $cmd)
    }
}



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
    }
}



$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
    }
        
    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()
lib\net40\Urasandesu.Prig.Framework.dll
 
lib\net40\Urasandesu.NAnonym.dll
 
lib\net35\Urasandesu.Prig.Framework.dll
 
lib\net35\Urasandesu.NAnonym.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.

Add to Builder Version Downloads Last Updated Status
Prig - Open Source Alternative to Microsoft Fakes 2.3.1 779 Sunday, August 14, 2016 Approved
Prig - Open Source Alternative to Microsoft Fakes 2.3.0 568 Friday, April 29, 2016 Approved
Prig - Open Source Alternative to Microsoft Fakes 2.2.0 454 Sunday, February 21, 2016 Approved
Prig - Open Source Alternative to Microsoft Fakes 2.1.1 394 Saturday, January 23, 2016 Approved
Prig - Open Source Alternative to Microsoft Fakes 2.1.0 425 Sunday, December 20, 2015 Approved
Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha06 472 Friday, September 18, 2015 Exempted
Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha05 432 Saturday, August 1, 2015 Exempted
Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha04 470 Wednesday, May 27, 2015 Exempted
Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha03 510 Monday, March 16, 2015 Exempted
Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha02 466 Sunday, March 8, 2015 Exempted
Prig: Open Source Alternative to Microsoft Fakes 2.0.0-alpha01 449 Sunday, March 1, 2015 Exempted

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.

Version 0.0.0-alpha10

  • Pre-release 10.
  • Fixed #23: Can't be replaced the method that exposes the type of GAC unregistered assembly.
  • Fixed #24: Add Comment-Based Help.
  • Supported the feature that be able to replace any methods that have some non-public type in its signature.
  • [NOTICE] Changed the generated stub's API. It became that the indirection stubs and proxies are generated ALWAYS(overwrite). Until now, it no longer generates stubs and proxies after it generated them once.

Version 0.0.0-alpha9

  • Pre-release 9.
  • Fixed #16: Nested Type can't be resolved in its indirection stub.
  • Fixed #17: Prig can't uninstall correctly against the solution that contains multiple test projects.
  • Fixed #18: Get-IndirectionStubSetting generates invalid alias against explict implemented interface.
  • Fixed #19: Find-IndirectionTarget should filter the members that can't call indirectly by default.
  • Fixed #20: Indirection stub settings for the instance method of an internal class generates build errors.

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


This package has no dependencies.

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