- load i18n

.page-title: .tabs
    h2(style='color:#393630; display: inline-block') {% trans title %}
    span.spacer
    if tab == 'calendar'
        div(style='font-size: 1.6em; margin-top: 0.3em')
            if prev_month
                a(href='{% url "contest_calendar" prev_month.year prev_month.month %}') « {% trans "Prev" %}
            = ' '
            if next_month
                a(href='{% url "contest_calendar" next_month.year next_month.month %}') {% trans "Next" %} »
        span.spacer
    ul
        li(class=('active' if tab == 'list' else '')): a(href='{% url "contest_list" %}') {% trans "List" %}
        li(class=('active' if tab == 'calendar' else '')): a(href='{% url "contest_calendar" now.year now.month %}') {% trans "Calendar" %}
        if perms.judge.change_contest
            li: a(href='{% url "admin:judge_contest_changelist" %}') {% trans "Admin" %}

Add icons to contest list tabs

- load i18n

.page-title: .tabs
    h2(style='color:#393630; display: inline-block') {% trans title %}
    span.spacer
    if tab == 'calendar'
        div(style='font-size: 1.6em; margin-top: 0.3em')
            if prev_month
                a(href='{% url "contest_calendar" prev_month.year prev_month.month %}') « {% trans "Prev" %}
            = ' '
            if next_month
                a(href='{% url "contest_calendar" next_month.year next_month.month %}') {% trans "Next" %} »
        span.spacer
    ul
        li.tab(class=('active' if tab == 'list' else '')): a(href='{% url "contest_list" %}') #[i.tab-icon.fa.fa-list] {% trans "List" %}
        li.tab(class=('active' if tab == 'calendar' else '')): a(href='{% url "contest_calendar" now.year now.month %}') #[i.tab-icon.fa.fa-calendar] {% trans "Calendar" %}
        if perms.judge.change_contest
            li.tab: a(href='{% url "admin:judge_contest_changelist" %}') #[i.tab-icon.fa.fa-edit] {% trans "Admin" %}


extends ./shared/layout.jade

block title
    title Log in

block content
    h1 Log in

    form(action='/login', method='post')
        div
            label(for='email') Email
            input#email(type='text', name='email', value='user@example.com')
        div
            label(for='password') Password
            input#password(type='password', name='password', value='pass')
        button(type='submit') Log In
    div
        a(href='/forgotpassword') Forgot Password?
    div
        a(href='/register') Register

Make register link more obvious in sample app

extends ./shared/layout.jade

block title
    title Log in

block content
    h1 Register
    div
        a(href='/register') Register

    h1 Log in
    form(action='/login', method='post')
        div
            label(for='email') Email
            input#email(type='text', name='email', value='user@example.com')
        div
            label(for='password') Password
            input#password(type='password', name='password', value='pass')
        button(type='submit') Log In
    div
        br
        a(href='/forgotpassword') Forgot Password?


extends ../layouts/main.jade

block content
  .row
    .columns
      #event
        h1= event.title
        p= moment(event.start).format('LLL')
          if event.end
            |  –
            = moment(event.end).format('LLL')
        p= event.location
        p= event.tags
        p!= marked(event.mdtext)


doctype 5
html(lang="en")
  head
    include incl/copyright.html
    block mv-title
      title Mailvelope
      meta(name="description", content="Browser extension that allows to exchange encrypted emails following the OpenPGP encryption standard")
    meta(name="viewport", content="width=device-width, initial-scale=1.0")
    meta(name="author", content="Thomas Oberndörfer")
    // Le styles
    link(href='http://fonts.googleapis.com/css?family=Courgette', rel='stylesheet', type='text/css')
    link(href="css/bootstrap.css", rel="stylesheet")
    link(href="css/bootstrap-responsive.css", rel="stylesheet")
    link(href="css/mvelo.css", rel="stylesheet")
    // Le HTML5 shim, for IE6-8 support of HTML5 elements
    //if lt IE 9
      script(src="http://html5shim.googlecode.com/svn/trunk/html5.js")
    // Le fav and touch icons
    link(rel="shortcut icon", href="img/favicon.png")
    link(rel="apple-touch-icon-precomposed", sizes="132x132", href="img/mvelo_icon_132.png")
    block mv-header
  block mv-body
    body
      block mv-navbar
      .container
          block mv-content
          hr
          footer © 2012-2013 the Mailvelope Project
      include incl/scripts

Fix doctype after Jade update

doctype html
html(lang="en")
  head
    include incl/copyright.html
    block mv-title
      title Mailvelope
      meta(name="description", content="Browser extension that allows to exchange encrypted emails following the OpenPGP encryption standard")
    meta(name="viewport", content="width=device-width, initial-scale=1.0")
    meta(name="author", content="Thomas Oberndörfer")
    // Le styles
    link(href='http://fonts.googleapis.com/css?family=Courgette', rel='stylesheet', type='text/css')
    link(href="css/bootstrap.css", rel="stylesheet")
    link(href="css/bootstrap-responsive.css", rel="stylesheet")
    link(href="css/mvelo.css", rel="stylesheet")
    // Le HTML5 shim, for IE6-8 support of HTML5 elements
    //if lt IE 9
      script(src="http://html5shim.googlecode.com/svn/trunk/html5.js")
    // Le fav and touch icons
    link(rel="shortcut icon", href="img/favicon.png")
    link(rel="apple-touch-icon-precomposed", sizes="132x132", href="img/mvelo_icon_132.png")
    block mv-header
  block mv-body
    body
      block mv-navbar
      .container
          block mv-content
          hr
          footer © 2012-2013 the Mailvelope Project
      include incl/scripts


---
template: post
title:  "Change Magento's contacts page url"
url: "/blog/2014/11/03/change-magentos-contacts-page-url"
author: "Roman Piták"
last_modified_at: 2014-11-03 15:17
perex: |
    In my Magento development workflow I strive to avoid any non-code changes and settings when creating the e-shop (and yes - it is possible).
    That' why I wrote an alternative to creating an unnecessary redirect for customizing the contact page url
---
:markdown
    Magento does not provide a proper built in way to change the url of the default
    contacts page. Some recommend creating a redirect in "Catalog" >> "URL Rewrite
    Management", but I find it unnecessary and counterproductive. In my Magento
    development workflow I strive to avoid any non-code changes and settings when
    creating the e-shop (and yes - it is possible).

    Changing the url of Magento's contacts page can be as easy as creating 2 files.

    `/app/etc/Zzz_ContactsPageUrl.xml`

        <?xml version="1.0" encoding="UTF-8"?>
        <config>
            <modules>
                <Zzz_ContactsPageUrl>
                    <active>true</active>
                    <codePool>local</codePool>
                </Zzz_ContactsPageUrl>
            </modules>
        </config>

    and `/app/code/local/Zzz/ContactsPageUrl/etc/config.xml`

        <?xml version="1.0"?>
        <config>
            <frontend>
                <routers>
                    <contacts>
                        <args>
                            <frontName>contact-us.html</frontName>
                        </args>
                    </contacts>
                </routers>
            </frontend>
        </config>

    The vital part here is the "vendor name", `Zzz`. Since Magento loads the
    modules alphabetically, modules from the Zzz vendor will be loaded last. This
    allows them to overwrite any previously defined settings.

    Although this might be considered a dirty hack by some, I believe it to be the
    most elegant solution since it does not create extra database overhead and can
    be easily stored in the VCS.

    [All source codes from this article are available for download on Github](https://github.com/romanpitak/Magento-contacts-page-url).


doctype html
html
  head
    title Pulsar
    style.
      * { margin: 0; padding: 0; box-sizing: border-box; }

      body { overflow: hidden; }

    script.
      var pulsarInitConfig = !{config};

    script(src='pulsar.js')

  body


!!!

//if lte IE 9
  html.ie
//[if gt IE 9]><!
html
  //<![endif]
html
  head
    title Sumaato
    meta(charset='UTF-8')
    meta(content='', name='description')
    meta(content='', name='author')
    meta(content='3 days', name='revisit-after')

    // build:css /styles/main.css
    link(href='/styles/main.css', rel='stylesheet')
    // endbuild

    //if lt IE 9
      script(src='//html5shiv.googlecode.com/svn/trunk/html5.js')

Change header title to projectName

!!!

//if lte IE 9
  html.ie
//[if gt IE 9]><!
html
  //<![endif]
html
  head
    title <%= _.slugify(projectName) %>
    meta(charset='UTF-8')
    meta(content='', name='description')
    meta(content='', name='author')
    meta(content='3 days', name='revisit-after')

    // build:css /styles/main.css
    link(href='/styles/main.css', rel='stylesheet')
    // endbuild

    //if lt IE 9
      script(src='//html5shiv.googlecode.com/svn/trunk/html5.js')


Add about dialog; Always call /Frames.json instead of /Frames

#aboutDialog.modal.fade(tabindex='-1', role='dialog', aria-labelledby='aboutDialogLabel', aria-hidden='true')
  .modal-dialog
    .modal-content
      .modal-header
        button.close(type='button', data-dismiss='modal')
          span(aria-hidden='true') ×
          span.sr-only Close
        h4#aboutDialogLabel.modal-title Flow v0.2.19
      .modal-body

      .modal-footer
        button.btn.btn-default(type='button', data-dismiss='modal') Close


doctype html
html
  head
    title Dancer Optical Flow Tracker
    meta(http-equiv="content-type", content="text/html; charset=utf-8")
    meta(name="viewport", content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0")
    meta(name="apple-mobile-web-app-capable", content="yes")
    meta(name="mobile-web-app-capable", content="yes")
    meta(name="apple-mobile-web-app-status-bar-style", content="black")

    link(rel="stylesheet", href="/stylesheets/dancer.css")

    script(src="/socket.io/socket.io.js")
    script(src="/bower_components/jquery/jquery.min.js")
    script(src="/javascript/oflow.js")

  body
    h1 Connecting...

    script(src="javascript/optiflow/optiflow.js")
    script.
      $(document).on('touchmove', function(e) {
        e.preventDefault();
      });


!!! 5
//if lt IE 7
  html.no-js.ie6(lang='en')
//if IE 7
  html.no-js.ie7(lang='en')
//if IE 8
  html.no-js.ie8(lang='en')
// [if gt IE 8] <!
html.no-js(lang='de')
  // <![endif]
  head
    include partials/_html-header

  body
    include partials/_nav
    block content
    include partials/_footer

Remove double html and head tags


- load i18n

h3 {% trans "Statistics" %}
.sidebox-content.sidebox-table: table.table
    each key, cls, count in results
        tr(class=cls)
            td(style='font-weight:bold;text-align:left')= key
            td(style='color:black')= count

Add an icon to stats table header

- load i18n

h3 {% trans "Statistics" %} #[i.fa.fa-pie-chart]
.sidebox-content.sidebox-table: table.table
    each key, cls, count in results
        tr(class=cls)
            td(style='font-weight:bold;text-align:left')= key
            td(style='color:black')= count


extends layout

block append vars
  - bodyclass = 'article-detail'

block prepend title
  | #{ page.title + ' - '}

block header
  include author
  h1= page.title
  p.author
    | #{ 'Written by ' }
    mixin author(page.metadata.author)

block content
  article.article
    section.content!= typogr(page.html).typogrify()
  a(href="http://creativecommons.org/licenses/by-sa/4.0/", rel="license")
    img(alt="Licencia Creative Commons", style="border-width:0", src="https://i.creativecommons.org/l/by-sa/4.0/80x15.png")
  br
  p(class="creativecommons")="Esta obra de "
    a(xmlns:cc="http://creativecommons.org/ns#", href=locals.url, property="cc:attributionName", rel="cc:attributionURL")=page.metadata.author
    =" está bajo una "
    a(rel="license", href="http://creativecommons.org/licenses/by-sa/4.0/")="Licencia Creative Commons Atribución-CompartirIgual 4.0 Internacional"

block prepend footer
  div.nav
    a(href=contents.index.url) « Full blog


- load i18n

.page-title: .tabs
    h2 {% trans title %}
    span.spacer
    ul
        li(class=('active' if tab == 'list' else ''))
            a(href='{% url "user_list" %}') {% trans "Leaderboard" %}
        li(class=('active' if tab == 'organizations' else ''))
            a(href='{% url "organization_list" %}') {% trans "Organizations" %}

Add icons for user list tabs

- load i18n

.page-title: .tabs
    h2 {% trans title %}
    span.spacer
    ul
        li(class=('active' if tab == 'list' else ''))
            a(href='{% url "user_list" %}') #[i.tab-icon.fa.fa-users] {% trans "Leaderboard" %}
        li(class=('active' if tab == 'organizations' else ''))
            a(href='{% url "organization_list" %}') #[i.tab-icon.fa.fa-university] {% trans "Organizations" %}


section

  section.sec-slide(data-background="#F44336")
    h1.white.upper Aviso
    h3.white.upper.fragment Essa talk é sobre experiências!

  section.sec-slide(data-background="#795548")
    h1.white.upper Quem aqui...?

  section.sec-slide(data-background="#4CAF50")
    h1.white.upper Essa talk é pra vocês!


.comment-submit
    form#comment-edit(action='{{ request.get_full_path }}', method='post')
        span.comment-id(style='display: none')= comment.id
        span.read-back(style='display: none') {% url "comment_content" comment.id %}
        - csrf_token
        .form-errors.
            | #{form.non_field_errors}
            | #{form.parent.errors}
            | #{form.parent}
        .comment-post-wrapper
            #comment-form-body #{form.body}
        hr
        input.button(style='float: right', type='submit', value='Post!')

Fix ugly comment edit form.

.comment-submit
    form#comment-edit(action='{{ request.get_full_path }}', method='post')
        span.comment-id(style='display: none')= comment.id
        span.read-back(style='display: none') {% url "comment_content" comment.id %}
        - csrf_token
        .form-errors
            | #{form.non_field_errors}
            | #{form.parent.errors}
            | #{form.parent}
        .comment-post-wrapper
            #comment-form-body #{form.body}
        hr
        input.button(style='float: right', type='submit', value='Post!')


a.division(href="#")
  .district
    = uppercase_first(t('district.' + type))
  .name
    if name
     = name
  if unit
    .title
      = t_attr(unit.name)


extends base

block body
    p You have successfully been registered. An email has been sent to confirm your registration.

Clarify *which* email we sent your registration email to

extends base

block body
    p You have successfully been registered. An email has been sent to the email address you provided to confirm your registration.


// The overlay selection radio button controls.
div(ng-show="overlayModelingNames.length > 1")
  h4 Modeling Result
  .btn-group
    div(ng-repeat="modelingName in overlayModelingNames")
      button.btn.btn-primary.qi-btn-select(
        ng-model='modelSelect' btn-radio="modelingName"
        ng-click="selectModelingResult(modelingName)"
      ) {{ modelingName }}


extends /src/layouts/post

block exports
  -exports.type = "post"
  -exports.comments = true
  -exports.authors = ["neemzy"]
  -exports.title = "L'injection de dépendances en PHP"
  -exports.tags = ["php", "php-di"]
  -exports.date = "2014-10-31"

block main
  +Post(exports.title)
    include:md index.md

Update date for php injection post

extends /src/layouts/post

block exports
  -exports.type = "post"
  -exports.comments = true
  -exports.authors = ["neemzy"]
  -exports.title = "L'injection de dépendances en PHP"
  -exports.tags = ["php", "php-di"]
  -exports.date = "2014-11-05"

block main
  +Post(exports.title)
    include:md index.md


Invoke-WebRequest -useb 'https://dot.net/v1/dotnet-install.ps1' -OutFile .\build\dotnet-install.ps1
.\build\dotnet-install.ps1 -channel Current -version 2.1.3 -InstallDir dotnetsdk
dotnet --version
dotnet pack Blazor.sln --configuration Release
cmd /c "C:\Program Files (x86)\Microsoft Visual Studio\aspnetci\Enterprise\MSBuild\15.0\Bin\MSBuild.exe" BlazorTooling.sln /t:Restore
cmd /c "C:\Program Files (x86)\Microsoft Visual Studio\aspnetci\Enterprise\MSBuild\15.0\Bin\MSBuild.exe" BlazorTooling.sln /p:DeployExtension=false

Add /p:TargetVSIXContainer to tools build script

Invoke-WebRequest -useb 'https://dot.net/v1/dotnet-install.ps1' -OutFile .\build\dotnet-install.ps1
.\build\dotnet-install.ps1 -channel Current -version 2.1.3 -InstallDir dotnetsdk
dotnet --version
dotnet pack Blazor.sln --configuration Release
cmd /c "C:\Program Files (x86)\Microsoft Visual Studio\aspnetci\Enterprise\MSBuild\15.0\Bin\MSBuild.exe" BlazorTooling.sln /t:Restore
cmd /c "C:\Program Files (x86)\Microsoft Visual Studio\aspnetci\Enterprise\MSBuild\15.0\Bin\MSBuild.exe" BlazorTooling.sln /p:DeployExtension=false /p:TargetVSIXContainer=..\..\artifacts\build\Microsoft.VisualStudio.BlazorExtension.vsix


# creates a .zip file with the file structure to run UVa-ITS-gopherbot

$version = "" + (Select-String -Path .\bot\bot.go -pattern "var Version = ")

$Start = $version.IndexOf('"')
$end = $version.LastIndexOf('"')

$version = $version.Substring($start + 1, $end - $start - 1)

Write-Output "Building for Windows 64bit"
go build

$fileName = "gopherbot-" + $version + "-windows-amd64.zip"

$list = "gopherbot.exe", "LICENSE", "README.md", ".\brain", ".\conf", ".\doc", ".\example.gopherbot", ".\lib", ".\licenses", ".\misc", ".\plugins"

Write-Output "Creating archive $filename"
Compress-Archive -path $list -DestinationPath $fileName -force

Check for clean tree and add commit for Windows

# creates a .zip file with the file structure to run UVa-ITS-gopherbot

[String]$clean = git status | select-string -pattern "nothing to commit, working tree clean"
if ( $clean -eq "" ) {
  write-output "Your working tree isn't clean, aborting build"
  exit 1
}

$version = "" + (Select-String -Path .\bot\bot.go -pattern "var Version = ")

$Start = $version.IndexOf('"')
$end = $version.LastIndexOf('"')

$version = $version.Substring($start + 1, $end - $start - 1)
[String]$commit = git log -1 | select-string -pattern "commit "
$commit = $commit.split(" ")[1]
$gofile = @"
package bot

func init(){
	commit="$commit"
}
"@

Write-Output "Building for Windows 64bit"
go build

$fileName = "gopherbot-" + $version + "-windows-amd64.zip"

$list = "gopherbot.exe", "LICENSE", "README.md", ".\brain", ".\conf", ".\doc", ".\example.gopherbot", ".\lib", ".\licenses", ".\misc", ".\plugins"

Write-Output "Creating archive $filename"
Compress-Archive -path $list -DestinationPath $fileName -force


# Powershell script to pull the VM files from GitHub into the current folder.
# Edit the following to match the version of the VM that is compatible with this image

param
(
    [string]$VMversion="v7.0.27"
)

Try
{
	$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path;
	Write-Host "Fetching DolphinVM.zip" $VMversion
	$source = "https://github.com/dolphinsmalltalk/DolphinVM/releases/download/$VMversion/DolphinVM.zip";
	$zipFile = $scriptDir+"\DolphinVM.zip";
	Invoke-WebRequest $source -OutFile $zipFile;
}
Catch
{
	Write-Host "Unable to fetch DolphinVM.zip" $VMversion;
	Break;
}

$shell = new-object -com shell.application;
$zip = $shell.NameSpace($zipFile);
foreach($item in $zip.items())
{
	Write-Host "..unpack" $item.Name
	$shell.Namespace($scriptDir).copyhere($item, 0x14);
}
Write-Host "Removing Zip"
Remove-Item $zipFile
Write-Host "Done fetching DolphinVM.zip" $VMversion

Upgrade to Dolphin VM 7.0.28

# Powershell script to pull the VM files from GitHub into the current folder.
# Edit the following to match the version of the VM that is compatible with this image

param
(
    [string]$VMversion="v7.0.28"
)

Try
{
	$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path;
	Write-Host "Fetching DolphinVM.zip" $VMversion
	$source = "https://github.com/dolphinsmalltalk/DolphinVM/releases/download/$VMversion/DolphinVM.zip";
	$zipFile = $scriptDir+"\DolphinVM.zip";
	Invoke-WebRequest $source -OutFile $zipFile;
}
Catch
{
	Write-Host "Unable to fetch DolphinVM.zip" $VMversion;
	Break;
}

$shell = new-object -com shell.application;
$zip = $shell.NameSpace($zipFile);
foreach($item in $zip.items())
{
	Write-Host "..unpack" $item.Name
	$shell.Namespace($scriptDir).copyhere($item, 0x14);
}
Write-Host "Removing Zip"
Remove-Item $zipFile
Write-Host "Done fetching DolphinVM.zip" $VMversion


$codeFormatterDownloadUri = "https://github.com/dotnet/codeformatter/releases/download/v1.0.0-alpha6/CodeFormatter.zip"
$codeFormatterDownloadLocation = "$env:TEMP\code-formatter.zip"
$codeFormatterExtractLocation = "$env:TEMP\code-formatter\"

# Check that there are no outstanding changes as we will use git status to test if CodeFormatter applied any changes
Write-Host "Checking for changes..."
$gitOutput = $(git status)
$gitHasChanges = ($gitOutput | ?{ $_.Contains("nothing to commit") } | measure).Count -eq 0 # counts lines with "nothing to commit" message
if($gitHasChanges)
{
    Write-Error "Outstanding changes to workspace (before code formatting) - aborting!"
    git status
    exit 10
}
Write-Host "No changes, downloading CodeFormatter..."

# Download CodeFormatter
(New-Object Net.WebClient).DownloadFile($codeFormatterDownloadUri, $codeFormatterDownloadLocation)
Expand-Archive -Path $codeFormatterDownloadLocation -DestinationPath $codeFormatterExtractLocation -Force

# Run CodeFormatter
Write-Host "Running CodeFormatter..."
&"$codeFormatterExtractLocation\CodeFormatter\CodeFormatter.exe" code-formatter.csproj /copyright:code-formatter.license.txt

# Check for changes, i.e. did CodeFormatter make changes?
Write-Host "Checking for changes..."
git add -A | out-null # add all files as this avoids changes due to CRLF/LF issues (providing we're set up to normalize to LF)
$gitOutput = $(git status)
$gitHasChanges = ($gitOutput | ?{ $_.Contains("nothing to commit") } | measure).Count -eq 0 # counts lines with "nothing to commit" message
if($gitHasChanges)
{
    Write-Error "Outstanding changes to workspace - aborting!"
    Write-Error "Run CodeFormatter and resubmit the pull request"
    git status
    git diff
    exit 20
}


$client = New-Object System.Net.WebClient

# Install PHP
$phpUrl = "http://windows.php.net/downloads/releases/$env:PHP.zip"
Write-Output "Downloading $phpUrl"
$client.DownloadFile($phpUrl, (Join-Path $PWD 'php.zip'))
7z e php.zip -ophp
Rename-Item .\php\php.ini-development php.ini
$env:PATH += ';' + (Join-Path $PWD 'php')

# Install XDebug
$xdebugUrl = "https://xdebug.org/files/$env:XDEBUG.dll"
Write-Output "Downloading $xdebugUrl"
$xdebugPath = Join-Path $PWD 'php\ext\xdebug.dll'
$client.DownloadFile($xdebugUrl, $xdebugPath)
Add-Content .\php\php.ini @"
extension_dir=ext
zend_extension=$xdebugPath
xdebug.remote_enable=1
xdebug.remote_autostart=1
"@

# Install Node
Write-Output 'Installing Node'
Install-Product node 4.1.1 x64
npm config -g set progress=false
npm config -g set unicode=false
npm install -g typings

# Install dependencies
Write-Output 'Installing dependencies'
npm install
typings install

Change AppVeyor Node version to 5.10.0

$client = New-Object System.Net.WebClient

# Install PHP
$phpUrl = "http://windows.php.net/downloads/releases/$env:PHP.zip"
Write-Output "Downloading $phpUrl"
$client.DownloadFile($phpUrl, (Join-Path $PWD 'php.zip'))
7z e php.zip -ophp
Rename-Item .\php\php.ini-development php.ini
$env:PATH += ';' + (Join-Path $PWD 'php')

# Install XDebug
$xdebugUrl = "https://xdebug.org/files/$env:XDEBUG.dll"
Write-Output "Downloading $xdebugUrl"
$xdebugPath = Join-Path $PWD 'php\ext\xdebug.dll'
$client.DownloadFile($xdebugUrl, $xdebugPath)
Add-Content .\php\php.ini @"
extension_dir=ext
zend_extension=$xdebugPath
xdebug.remote_enable=1
xdebug.remote_autostart=1
"@

# Install Node
Write-Output 'Installing Node'
Install-Product node 5.10.0 x64
npm config -g set progress=false
npm config -g set unicode=false
npm install -g typings

# Install dependencies
Write-Output 'Installing dependencies'
npm install
typings install


"PR: '$env:APPVEYOR_PULL_REQUEST_NUMBER'"
if($env:APPVEYOR_PULL_REQUEST_NUMBER -eq $null) {
    OpenCover.Console.exe -register:user -filter:"+[ScriptCs.ComponentModel.Composition]*" -excludebyattribute:*.ExcludeFromCodeCoverage* -target:"$env:xunit20\xunit.console.x86" -targetargs:""src\ScriptCs.ComponentModel.Composition.Test\bin\Release\ScriptCs.ComponentModel.Composition.Test.dll" -noshadow -appveyor" -output:coverage.xml -returntargetcode
    coveralls.net --opencover coverage.xml
}
else
{
    & "$env:xunit20\xunit.console.x86" "src\ScriptCs.ComponentModel.Composition.Test\bin\Release\ScriptCs.ComponentModel.Composition.Test.dll" -noshadow -appveyor
}

Fix xunit path in opencover args

if($env:APPVEYOR_PULL_REQUEST_NUMBER -eq $null) {
    OpenCover.Console.exe -register:user -filter:"+[ScriptCs.ComponentModel.Composition]*" -excludebyattribute:*.ExcludeFromCodeCoverage* -target:"$env:xunit20\xunit.console.x86.exe" -targetargs:""src\ScriptCs.ComponentModel.Composition.Test\bin\Release\ScriptCs.ComponentModel.Composition.Test.dll" -noshadow -appveyor" -output:coverage.xml -returntargetcode
    coveralls.net --opencover coverage.xml
}
else
{
    & "$env:xunit20\xunit.console.x86" "src\ScriptCs.ComponentModel.Composition.Test\bin\Release\ScriptCs.ComponentModel.Composition.Test.dll" -noshadow -appveyor
}


param($newVersion)
#
# We expect to be run from a root directory! And "$newVersion" is "v5.30.01" or
# similar.
#

#
# Get a list of all packages.config files.
#

$allConfigfiles = Get-ChildItem -Recurse packages.config

if (-not $allConfigfiles)
{
    Write-Host "No packages.config files found!"
}

#
# Find all the ROOT version numbers that are in those files.
# We will replace all of them and update them to the version that
# was passed in on the command line.
#

$oldVersions = $allConfigfiles | Get-Content | ? {$_ -match "-(v[\.0-9]+)\.win32"} | % {$Matches[1]} | Sort-Object -Unique

#
# We have to do this replacement in the project files as well as the
# nuget files.
#

$projectFiles = Get-ChildItem -Recurse *.csproj,*.vcxproj
$allfiles = $allConfigfiles + $projectFiles

#
# For each old version, update the file! :-)
#

foreach ($oldV in $oldVersions)
{
    foreach ($f in $allfiles)
    {
        $newFile = Get-Content $f | % {$_ -replace $oldV, $newVersion}
        Write-Host "Updating $f"
        $newFile | Set-Content $f
    }
}

Fix a small bug, and add some code to help debug another odd problem.

param($newVersion)
#
# We expect to be run from a root directory! And "$newVersion" is "v5.30.01" or
# similar.
#

#
# Get a list of all packages.config files.
#

$allConfigfiles = Get-ChildItem -Recurse packages.config

ls
if (-not $allConfigfiles)
{
    Write-Host "No packages.config files found!"
    return
}

#
# Find all the ROOT version numbers that are in those files.
# We will replace all of them and update them to the version that
# was passed in on the command line.
#

$oldVersions = $allConfigfiles | Get-Content | ? {$_ -match "-(v[\.0-9]+)\.win32"} | % {$Matches[1]} | Sort-Object -Unique

#
# We have to do this replacement in the project files as well as the
# nuget files.
#

$projectFiles = Get-ChildItem -Recurse *.csproj,*.vcxproj
$allfiles = $allConfigfiles + $projectFiles

#
# For each old version, update the file! :-)
#

foreach ($oldV in $oldVersions)
{
    foreach ($f in $allfiles)
    {
        $newFile = Get-Content $f | % {$_ -replace $oldV, $newVersion}
        Write-Host "Updating $f"
        $newFile | Set-Content $f
    }
}


# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

# Add the relevant binary module
try
{
    $null = [Microsoft.PowerShell.CrossCompatibility.Commands.NewPSCompatibilityProfileCommand]
    $compatibilityLoaded = $true
}
catch
{
    $compatibilityLoaded = $false
}
if (-not $compatibilityLoaded)
{
    if ($PSVersionTable.PSVersion.Major -ge 6)
    {
        Import-Module ([System.IO.Path]::Combine($PSScriptRoot, 'netstandard2.0', 'Microsoft.PowerShell.CrossCompatibility.dll'))
    }
    else
    {
        Import-Module ([System.IO.Path]::Combine($PSScriptRoot, 'net452', 'Microsoft.PowerShell.CrossCompatibility.dll'))
    }
}

Fix module reloading where cmdlets are unloaded but types not

# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

# Add the relevant binary module
if ($PSVersionTable.PSVersion.Major -ge 6)
{
    Import-Module ([System.IO.Path]::Combine($PSScriptRoot, 'netstandard2.0', 'Microsoft.PowerShell.CrossCompatibility.dll'))
}
else
{
    Import-Module ([System.IO.Path]::Combine($PSScriptRoot, 'net452', 'Microsoft.PowerShell.CrossCompatibility.dll'))
}


# The names of the user are language dependent!
$objSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-1-0")
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])

$grant = "$objUser,Full"

for ($i=0; $i -le $args.length; $i = $i + 3) {
    $path = $args[$i]
    $share_name = $args[$i+1]
    $share_id = $args[$i+2]

    if ($path -eq $null) {
        Write-Warning "empty path argument encountered - complete"
        exit 0
    }

    if ($share_name -eq $null) {
        Write-Output "share path: ${path}"
        Write-Error "error - no share name provided"
        exit 1
    }

    if ($share_id -eq $null) {
        Write-Output "share path: ${path}"
        Write-Error "error - no share ID provided"
        exit 1
    }

    $result = net share $share_name=$path /unlimited /GRANT:$grant /REMARK:"${share_id}"
    if ($LastExitCode -ne 0) {
        $host.ui.WriteLine("share path: ${path}")
        $host.ui.WriteErrorLine("error ${result}")
        exit 1
    }
}
exit 0

Swap usage of share name and id for consistent behavior

# The names of the user are language dependent!
$objSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-1-0")
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])

$grant = "$objUser,Full"

for ($i=0; $i -le $args.length; $i = $i + 3) {
    $path = $args[$i]
    $share_name = $args[$i+1]
    $share_id = $args[$i+2]

    if ($path -eq $null) {
        Write-Warning "empty path argument encountered - complete"
        exit 0
    }

    if ($share_name -eq $null) {
        Write-Output "share path: ${path}"
        Write-Error "error - no share name provided"
        exit 1
    }

    if ($share_id -eq $null) {
        Write-Output "share path: ${path}"
        Write-Error "error - no share ID provided"
        exit 1
    }

    $result = net share $share_id=$path /unlimited /GRANT:$grant /REMARK:"${share_name}"
    if ($LastExitCode -ne 0) {
        $host.ui.WriteLine("share path: ${path}")
        $host.ui.WriteErrorLine("error ${result}")
        exit 1
    }
}
exit 0


function prompt {
    $location = ([string]$(get-location)).Replace($HOME, '~')
   "$location |-/ "
}

Set-Alias g git

function e {
    emacsclient --alternate-editor="" $Args
}

$local = "$PSScriptRoot/profile_local.ps1"
(Test-Path $local) -And (. $local) > $null

Set PSReadLine edit mode to Emacs

if (Get-Module PSReadLine) {
    Set-PSReadLineOption -EditMode Emacs
}

function prompt {
    $location = ([string]$(get-location)).Replace($HOME, '~')
   "$location |-/ "
}

Set-Alias g git

function e {
    emacsclient --alternate-editor="" $Args
}

$local = "$PSScriptRoot/profile_local.ps1"
(Test-Path $local) -And (. $local) > $null


# Powershell script to pull the VM files from GitHub into the current folder.
# Edit the following to match the version of the VM that is compatible with this image

param
(
    [string]$VMversion="v7.0.42"
)

Try
{
	$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path;
	Write-Host "Fetching DolphinVM.zip" $VMversion
	$source = "https://github.com/dolphinsmalltalk/DolphinVM/releases/download/$VMversion/DolphinVM.zip";
	$zipFile = $scriptDir+"\DolphinVM.zip";
	Invoke-WebRequest $source -OutFile $zipFile;
}
Catch
{
	Write-Host "Unable to fetch DolphinVM.zip" $VMversion;
	Break;
}

$shell = new-object -com shell.application;
$zip = $shell.NameSpace($zipFile);
foreach($item in $zip.items())
{
	Write-Host "..unpack" $item.Name
	$shell.Namespace($scriptDir).copyhere($item, 0x14);
}
Write-Host "Removing Zip"
Remove-Item $zipFile
Write-Host "Done fetching DolphinVM.zip" $VMversion

Upgrade to 7.0.43 VM build for new stubs without insecure CRT exports

# Powershell script to pull the VM files from GitHub into the current folder.
# Edit the following to match the version of the VM that is compatible with this image

param
(
    [string]$VMversion="v7.0.43"
)

Try
{
	$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path;
	Write-Host "Fetching DolphinVM.zip" $VMversion
	$source = "https://github.com/dolphinsmalltalk/DolphinVM/releases/download/$VMversion/DolphinVM.zip";
	$zipFile = $scriptDir+"\DolphinVM.zip";
	Invoke-WebRequest $source -OutFile $zipFile;
}
Catch
{
	Write-Host "Unable to fetch DolphinVM.zip" $VMversion;
	Break;
}

$shell = new-object -com shell.application;
$zip = $shell.NameSpace($zipFile);
foreach($item in $zip.items())
{
	Write-Host "..unpack" $item.Name
	$shell.Namespace($scriptDir).copyhere($item, 0x14);
}
Write-Host "Removing Zip"
Remove-Item $zipFile
Write-Host "Done fetching DolphinVM.zip" $VMversion


param(
  [string]$name
)

if (! $name) {
  $name = "dev"
}

# create a virtual switch
New-VMSwitch -NetAdapterInterfaceDescription "vmxnet3 Ethernet Adapter" -Name "docker"

# create a Hyper-V Linux docker machine
docker-machine -D create -d hyperv --hyperv-virtual-switch "docker" $name

# known issues
# https://github.com/docker/machine/issues/2267
# https://github.com/docker/machine/issues/2362
# workaround: https://github.com/docker/machine/issues/2267#issuecomment-156426874
docker-machine start $name
docker-machine regenerate-certs -f $name

# windows docker client has different API version
# workaround: update the docker engine in the Hyper-V Linux docker machine
docker-machine ssh $name sudo /etc/init.d/docker stop
docker-machine ssh $name sudo curl -o /usr/local/bin/docker https://master.dockerproject.org/linux/amd64/docker
docker-machine ssh $name sudo /etc/init.d/docker start

Improve script to create linux machine

param(
  [string]$name
)

if (! $name) {
  $name = "dev"
}

# ensure that we are running as administrator
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {#
  Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -Name $name" -Verb RunAs; exit
}

# create a virtual switch
if (((Get-VMSwitch).name | grep docker) -ne "docker") {
  $description=(Get-NetAdapter).InterfaceDescription | grep -v Hyper-V
  New-VMSwitch -NetAdapterInterfaceDescription $description -Name "docker"

  Write-Host "Waiting for internet connectivity"
  Sleep 15
}

# create a Hyper-V Linux docker machine
docker-machine create -d hyperv --hyperv-virtual-switch "docker" $name

# known issues
# https://github.com/docker/machine/issues/2267
# https://github.com/docker/machine/issues/2362
# workaround: https://github.com/docker/machine/issues/2267#issuecomment-156426874
docker-machine start $name
docker-machine regenerate-certs -f $name

# windows docker client has different API version
# workaround: update the docker engine in the Hyper-V Linux docker machine
docker-machine ssh $name sudo /etc/init.d/docker stop
docker-machine ssh $name sudo curl -o /usr/local/bin/docker https://master.dockerproject.org/linux/amd64/docker
docker-machine ssh $name sudo /etc/init.d/docker start


sal gh help

function prompt {
	$Host.UI.RawUI.WindowTitle = "PS $($ExecutionContext.SessionState.Path.CurrentLocation)$('>' * ($NestedPromptLevel + 1))"
	return 'PS> '
}

Add sl functions as aliases

sal gh help
function sl.. { sl .. }
function sl~ { sl ~ }

function prompt {
	$Host.UI.RawUI.WindowTitle = "PS $($ExecutionContext.SessionState.Path.CurrentLocation)$('>' * ($NestedPromptLevel + 1))"
	return 'PS> '
}


$OutputEncoding = [Text.Encoding]::UTF8

$client = New-Object System.Net.WebClient

# Install PHP
$phpUrl = "http://windows.php.net/downloads/releases/$env:PHP.zip"
Write-Output "Downloading $phpUrl"
$client.DownloadFile($phpUrl, (Join-Path $PWD 'php.zip'))
7z e php.zip -ophp
Rename-Item .\php\php.ini-development php.ini
$env:PATH += ';' + (Join-Path $PWD 'php')

# Install XDebug
$xdebugUrl = "https://xdebug.org/files/$env:XDEBUG.dll"
Write-Output "Downloading $xdebugUrl"
$xdebugPath = Join-Path $PWD 'php\ext\xdebug.dll'
$client.DownloadFile($xdebugUrl, $xdebugPath)
Add-Content .\php\php.ini @"
extension_dir=ext
zend_extension=$xdebugPath
xdebug.remote_enable=1
xdebug.remote_autostart=1
"@

# Install Node
Write-Output 'Installing Node'
Install-Product node 4.1.1 x64
npm install -g typings --no-progress

# Install dependencies
Write-Output 'Installing dependencies'
npm install --no-progress
typings install

Disable Unicode for NPM in AppVeyor

$client = New-Object System.Net.WebClient

# Install PHP
$phpUrl = "http://windows.php.net/downloads/releases/$env:PHP.zip"
Write-Output "Downloading $phpUrl"
$client.DownloadFile($phpUrl, (Join-Path $PWD 'php.zip'))
7z e php.zip -ophp
Rename-Item .\php\php.ini-development php.ini
$env:PATH += ';' + (Join-Path $PWD 'php')

# Install XDebug
$xdebugUrl = "https://xdebug.org/files/$env:XDEBUG.dll"
Write-Output "Downloading $xdebugUrl"
$xdebugPath = Join-Path $PWD 'php\ext\xdebug.dll'
$client.DownloadFile($xdebugUrl, $xdebugPath)
Add-Content .\php\php.ini @"
extension_dir=ext
zend_extension=$xdebugPath
xdebug.remote_enable=1
xdebug.remote_autostart=1
"@

# Install Node
Write-Output 'Installing Node'
Install-Product node 4.1.1 x64
npm config -g set progress=false
npm config -g set unicode=false
npm install -g typings

# Install dependencies
Write-Output 'Installing dependencies'
npm install
typings install


[cmdletbinding()]
param(
    [string]$remoteName
)

Write-Verbose "Entering script RestoreGitRemote.ps1"
Write-Verbose "Parameter Values"
foreach($key in $PSBoundParameters.Keys)
{
    Write-Verbose ($key + ' = ' + $PSBoundParameters[$key])
}

if(!$remoteName)
{
    throw ("RemoteName parameter must be set.")
}

Write-Verbose "Leaving script RestoreGitRemote.ps1"

Implement Restore Git Remote task

[cmdletbinding()]
param(
    [string]$remoteName
)

Write-Verbose "Entering script RestoreGitRemote.ps1"
Write-Verbose "Parameter Values"
foreach($key in $PSBoundParameters.Keys)
{
    Write-Verbose ($key + ' = ' + $PSBoundParameters[$key])
}

if(!$remoteName)
{
    throw ("RemoteName parameter must be set.")
}

import-module "Microsoft.TeamFoundation.DistributedTask.Task.Common"

# Get the original remote URL from the context variable.
$originalRemoteUrl = Get-TaskVariable -Context $distributedTaskContext -Name IOZ.GitTools.OriginalRemote.$remoteName -Global $FALSE

if ([string]::IsNullOrEmpty($originalRemoteUrl) -eq $true)
{
    throw ("Could not find original URL of the remote '$remoteName'. Make sure you have called 'Enable Git Remote Access' Task for the remote '$remoteName' before the 'Restore Git Remote' task.")
}

git remote set-url $remoteName $originalRemoteUrl
Write-Verbose "Updated remote for $remoteName is $originalRemoteUrl"

Write-Verbose "Leaving script RestoreGitRemote.ps1"


$deployToolsDir = Split-Path ((Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path)

if (Test-Path variable:\OctopusParameters)
{
    foreach($kp in $OctopusParameters.GetEnumerator())
    {
        Set-Content ("env:\" + $kp.Key) ($kp.Value) -Force
    }
}

if(!(Test-Path "env:\ConfigOnly"))
{
    Set-Content "env:\ConfigOnly" $false
}

function ensconce
{
    if (@($input).Count -ne 0)
    {
        $input.Reset()
        $results = $input | & "$deployToolsDir\ensconce.exe" $args 2>&1
    }
    else {
        $results = & "$deployToolsDir\ensconce.exe" $args 2>&1
    }
    if ($LASTEXITCODE -ne 0)
    {
	    Write-Host "##teamcity[buildStatus status='FAILURE' text='{build.status.text}; Ensconce failure']"
	    $results
	    exit $LASTEXITCODE
    }
    $results
}

function EnsurePath([string]$name)
{
	$path = $name | ensconce -i

	if ((Test-Path $path) -eq $False)
	{
		md $path
	}
}

function is64bit() {
  return ( (Get-WmiObject Win32_OperatingSystem).OSArchitecture -eq "64-bit")
}

Remove Octopus error hack now that it breaks Octopus.

$deployToolsDir = Split-Path ((Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path)

if (Test-Path variable:\OctopusParameters)
{
    foreach($kp in $OctopusParameters.GetEnumerator())
    {
        Set-Content ("env:\" + $kp.Key) ($kp.Value) -Force
    }
}

if(!(Test-Path "env:\ConfigOnly"))
{
    Set-Content "env:\ConfigOnly" $false
}

function ensconce
{
    if (@($input).Count -ne 0)
    {
        $input.Reset()
        $results = $input | & "$deployToolsDir\ensconce.exe" $args
    }
    else {
        $results = & "$deployToolsDir\ensconce.exe" $args
    }
    if ($LASTEXITCODE -ne 0)
    {
        Write-Host "##teamcity[buildStatus status='FAILURE' text='{build.status.text}; Ensconce failure']"
        $results
        exit $LASTEXITCODE
    }
    $results
}

function EnsurePath([string]$name)
{
    $path = $name | ensconce -i

    if ((Test-Path $path) -eq $False)
    {
        md $path
    }
}

function is64bit() {
  return ( (Get-WmiObject Win32_OperatingSystem).OSArchitecture -eq "64-bit")
}


Add script for generation of Coverity Scan upload package

# Move to the project root folder (parent from current script folder)

function Get-ScriptDirectory
{
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value
    Split-Path $Invocation.MyCommand.Path
}

$rootFolder = (Get-Item (Get-ScriptDirectory)).Parent.FullName
Set-Location $rootFolder

# --- Initialization ---

# Check NuGet is installed and updated

If (!(Test-Path .\.nuget\nuget.exe))
{
    New-Item .\.nuget -type directory -Force | Out-Null
    Invoke-WebRequest 'https://www.nuget.org/nuget.exe' -OutFile '.\.nuget\nuget.exe'
}

.\.nuget\NuGet.exe update -self

# Install required NuGet packages

.\.nuget\NuGet.exe install DotNetZip -OutputDirectory .\packages -Version 1.9.3

# --- Functions ---

function Write-Zip( $sourcefiles, $zipPath )
{
    $item = New-Item .\artifacts\ziptemp -type directory
    Copy-item $sourcefiles .\artifacts\ziptemp -Recurse

    $zipFullPath = Join-Path (pwd) $zipPath

    Add-Type -Path ".\packages\DotNetZip.1.9.3\lib\net20\Ionic.zip.dll"

    $zip = new-object Ionic.Zip.ZipFile
    $zip.AddDirectory($item.FullName)
    $zip.Save($zipFullPath)
    $zip.Dispose()

    Remove-Item .\artifacts\ziptemp -Recurse -Force
    return $zipPath
}

# --- Script ---

# Clean the solution

./scripts/Clean.ps1

# Run the Coverity Build tool

& "C:\Program Files\cov-analysis-win64-7.5.0\bin\cov-build" --dir artifacts\cov-int powershell ./scripts/BuildRelease.ps1

# Zip the resulting files

Write-Zip .\artifacts\cov-int .\artifacts\Okra.Data-cov-int.zip


Add TEPP for MailAccount Originally named just Account

#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"]) {
	[Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )

    $start = Get-Date
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts["mailaccount"].LastExecution = $start

	$server = $fakeBoundParameter['SqlInstance']

	if (-not $server) {
		$server = $fakeBoundParameter['Source']
	}

	if (-not $server) {
		$server = $fakeBoundParameter['ComputerName']
	}

	if (-not $server) { return }

    try
    {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    }
    catch
    {
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts["mailaccount"].LastDuration = (Get-Date) - $start
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"][$parServer.FullSmoName.ToLower()])
    {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*"))
        {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts["mailaccount"].LastDuration = (Get-Date) - $start
        return
    }

    try
    {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*"))
        {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts["mailaccount"].LastDuration = (Get-Date) - $start
        return
    }
    catch
    {
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts["mailaccount"].LastDuration = (Get-Date) - $start
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name MailAccount
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

	[Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["mailaccount"][$FullSmoName] = $server.Mail.Accounts.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache


$currentScriptDirectory = Get-Location
[System.IO.Directory]::SetCurrentDirectory($currentScriptDirectory.Path)

Set-Location -Path ${PSScriptRoot}
$solutiondir = Resolve-Path -Path "$currentScriptDirectory"

Write-Host "Solution dir is " $solutiondir

$path = "$solutiondir\ReactiveDomain\ReactiveDomain.nuspec"
Write-Host "NuSpec File is" $path

$dll = "$solutiondir\ReactiveDomain\bin\x64\Debug\ReactiveDomain.dll"
Write-Host "Loading dll: " $dll

$Assembly = [Reflection.Assembly]::Loadfile($dll)
$AssemblyName = $Assembly.GetName()
$Assemblyversion = $AssemblyName.version.ToString()

Write-Host "Assembly version is" $Assemblyversion

#Modify the nuspec file to get the assembly version of this build
$xml = [xml](Get-Content $path)
$node = $xml.package.metadata
$node.version = $Assemblyversion
$xml.Save($path)

Fix path to updatenuget script

$currentScriptDirectory = Get-Location
[System.IO.Directory]::SetCurrentDirectory($currentScriptDirectory.Path)

Set-Location -Path ${PSScriptRoot}
$solutiondir = Resolve-Path -Path "$currentScriptDirectory\src\ReactiveDomain"

Write-Host "Solution dir is " $solutiondir

$path = "$solutiondir\ReactiveDomain\ReactiveDomain.nuspec"
Write-Host "NuSpec File is" $path

$dll = "$solutiondir\ReactiveDomain\bin\x64\Debug\ReactiveDomain.dll"
Write-Host "Loading dll: " $dll

$Assembly = [Reflection.Assembly]::Loadfile($dll)
$AssemblyName = $Assembly.GetName()
$Assemblyversion = $AssemblyName.version.ToString()

Write-Host "Assembly version is" $Assemblyversion

#Modify the nuspec file to get the assembly version of this build
$xml = [xml](Get-Content $path)
$node = $xml.package.metadata
$node.version = $Assemblyversion
$xml.Save($path)


#Script based on https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/visual-studio-dev-vm-chocolatey/scripts/SetupChocolatey.ps1
param([Parameter(Mandatory=$true)][string]$chocoPackages)

Write-Host "File packages URL: $linktopackages"

#Changing ExecutionPolicy
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force

#Change securoty protocol
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072

# Install Choco
$sb = { iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) }
Invoke-Command -ScriptBlock $sb

$sb = { Set-ItemProperty -path HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System -name EnableLua -value 0 }
Invoke-Command -ScriptBlock $sb

#Install Chocolatey Packages
$chocoPackages.Split(";") | ForEach {
    choco install $_ -y -force
}

Write-Host "Packages from choco.org were installes"

Fix typo: installes -> installed

#Script based on https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/visual-studio-dev-vm-chocolatey/scripts/SetupChocolatey.ps1
param([Parameter(Mandatory=$true)][string]$chocoPackages)

Write-Host "File packages URL: $linktopackages"

#Changing ExecutionPolicy
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force

#Change securoty protocol
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072

# Install Choco
$sb = { iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) }
Invoke-Command -ScriptBlock $sb

$sb = { Set-ItemProperty -path HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System -name EnableLua -value 0 }
Invoke-Command -ScriptBlock $sb

#Install Chocolatey Packages
$chocoPackages.Split(";") | ForEach {
    choco install $_ -y -force
}

Write-Host "Packages from choco.org were installed"


param($installPath, $toolsPath, $package, $project)

$obj = $project.Object
$getRefsMethod = [Microsoft.VisualStudio.Project.VisualC.VCProjectEngine.VCProjectShim].GetMethod("get_References")
$refs = $getRefsMethod.Invoke($obj, $null)
$assemblyRef = $refs.Find("RestSharp.Portable.Encodings")
if ($assemblyRef -ne $NULL) {
	$assemblyRef.Remove();
}

Fix for C++/CLI to ensure that the assembly gets removed

param($installPath, $toolsPath, $package, $project)

$obj = $project.Object
$getRefsMethod = [Microsoft.VisualStudio.Project.VisualC.VCProjectEngine.VCProjectShim].GetMethod("get_References")
$refs = $getRefsMethod.Invoke($obj, $null)
$assemblyRef = $refs.Find("RestSharp.Portable")
if ($assemblyRef -ne $NULL) {
	$assemblyRef.Remove();
}


$ErrorActionPreference = "Stop"

$env:DOTNET_CLI_TELEMETRY_OPTOUT=1
dotnet build --configuration Release PSFzf.sln
$dllPaths = Get-ChildItem PSFzf.dll -Recurse
if ($null -eq $dllPaths) {
    throw 'Unable to find PSFzf.dll'
}
Copy-Item $dllPaths[0].FullName . -Force -Verbose

& (Join-Path $PSScriptRoot 'helpers' 'Join-ModuleFiles.ps1')

Remove build step to generate .psm1


param (
    [string] $yarn = 'yarn',
    [string] $RepoPath = "$PSScriptRoot/../ForneverMind/wwwroot/talks"
)

$ErrorActionPreference = 'Stop'

function log($text, $header) {
    if (-not $header) {
        $header = 'Prepare-Talks'
    }
    Write-Output "[$header] $text"
}

function exec($command) {
    log "$command $args" 'Prepare-Talks.exec'
    & $command $args
    if (!$?) {
        throw "[build error] $command $args = $LASTEXITCODE"
    }
}

function execIgnoreStdErr($command) {
    log "$command $args" 'Prepare-Talks.execIgnoreStdErr'
    cmd /c "$command $args 2>&1"
    if (!$?) {
        throw "[build error] $command $args = $LASTEXITCODE"
    }
}

function yarnInstall($name, $flags) {
    $output = "$RepoPath/$name"
    Push-Location $output
    try {
        log "Installing $name"
        exec $yarn install $flags
    } finally {
        Pop-Location
    }
}

function npmInstall($name) {
    $output = "$RepoPath/$name"
    Push-Location $output
    try {
        log "Installing $name"
        execIgnoreStdErr npm install
    } finally {
        Pop-Location
    }
}

yarnInstall modern-programming --ignore-engines
yarnInstall net-core-slides
yarnInstall git-basics
npmInstall talk-javascriptservices

Update error handling in the talk preparation script

param (
    [string] $yarn = 'yarn',
    [string] $RepoPath = "$PSScriptRoot/../ForneverMind/wwwroot/talks"
)

$ErrorActionPreference = 'Stop'

function log($text, $header) {
    if (-not $header) {
        $header = 'Prepare-Talks'
    }
    Write-Output "[$header] $text"
}

function exec($command) {
    log "$command $args" 'Prepare-Talks.exec'
    & $command $args
    if ($LASTEXITCODE -ne 0) {
        throw "[build error] $command $args = $LASTEXITCODE"
    }
}

function yarnInstall($name, $flags) {
    $output = "$RepoPath/$name"
    Push-Location $output
    try {
        log "Installing $name"
        exec $yarn install $flags
    } finally {
        Pop-Location
    }
}

function npmInstall($name) {
    $output = "$RepoPath/$name"
    Push-Location $output
    try {
        log "Installing $name"
        exec npm install
    } finally {
        Pop-Location
    }
}

yarnInstall modern-programming --ignore-engines
yarnInstall net-core-slides
yarnInstall git-basics
npmInstall talk-javascriptservices


# Extract the latest version of Turbo repository
#
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0

function Get-LatestHubVersion
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [string] $imageToCheck,

        [Parameter(Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [string] $versionToCheck
    )
    process
    {
        $hubResponse = turbo releases $imageToCheck

        if($versionToCheck) {
            return ([string]$hubResponse) -match $versionToCheck
        }
        else {
            return $hubResponse[2]
        }
    }
}

Check version without turbo client

# Extract the latest version of Turbo repository
#
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0

function Get-LatestHubVersion
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [string] $imageToCheck,

        [Parameter(Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [string] $versionToCheck
    )
    process
    {
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        $hubResponse = Invoke-WebRequest -Uri "https://turbo.net/io/_hub/repo/$imageToCheck"
        $tags = $hubResponse | ConvertFrom-Json | Select -expand tags

        if($versionToCheck) {
            return ([string]$tags[0]) -match $versionToCheck
        }
        else {
            return $tags[0]
        }
    }
}


Add scan option to monitor file share permissions

$all_shares = Get-WmiObject win32_LogicalShareSecuritySetting
$shares = @()
if($all_shares){
    foreach($s in $all_shares){
        $obj = New-Object –TypeName PSObject
        $obj | Add-Member -MemberType NoteProperty –Name Name –Value $s.name
        $ACLS = $s.GetSecurityDescriptor().Descriptor.DACL
        $permissions = @{}
        foreach($ACL in $ACLS){
            $User = $ACL.Trustee.Name
            if(!($user)){$user = $ACL.Trustee.SID}
            $Domain = $ACL.Trustee.Domain
            switch($ACL.AccessMask)
            {
                2032127 {$Perm = "Full Control"}
                1245631 {$Perm = "Change"}
                1179817 {$Perm = "Read"}
            }
            # Write-Host "$($s.Name)   $Domain\$user  $Perm"
            if($Domain){
                $permissions.Add("$($Domain)\\$($user)", $Perm)
            }else{
                $permissions.Add($user, $Perm)
            }
        }
        $obj | Add-Member -MemberType NoteProperty -Name Permissions -Value $permissions
        $shares += $obj
    }
}
$shares


$publishVersion = $Env:GitVersion_MajorMinorPatch

# Regular expression pattern to find the version in the build number
# and then apply it to the assemblies
$versionRegex = "\d+\.\d+\.\d+\.\d+"

$vsixManifestSearchPattern = "./source.extension.vsixmanifest"
$vsixManifestCollection = (Get-ChildItem $vsixManifestSearchPattern -Recurse)

foreach($file in $vsixManifestCollection)
{
    $filecontent = Get-Content($file)
    attrib $file -r
    $filecontent -replace $versionRegex, $publishVersion | Out-File $file -Encoding utf8
    "Update version in VSIX manifest to $publishVersion"| Write-Host -ForegroundColor White
}

Update script to get proper incremental versions in develop branch

$publishVersion = $Env:GitVersion_MajorMinorPatch+"."+$Env:GitVersion_PreReleaseNumber

# Regular expression pattern to find the version in the build number
# and then apply it to the assemblies
$versionRegex = "\d+\.\d+\.\d+\.\d+"

$vsixManifestSearchPattern = "./source.extension.vsixmanifest"
$vsixManifestCollection = (Get-ChildItem $vsixManifestSearchPattern -Recurse)

foreach($file in $vsixManifestCollection)
{
    $filecontent = Get-Content($file)
    attrib $file -r
    $filecontent -replace $versionRegex, $publishVersion | Out-File $file -Encoding utf8
    "Update version in VSIX manifest to $publishVersion"| Write-Host -ForegroundColor White
}


# Global modules directory
$global:PsGetDestinationModulePath = $PSScriptRoot + "\..\vendor\psmodules"

# Push to modules location
Push-Location -Path ($PsGetDestinationModulePath)

# Load modules from current directory
Import-Module .\PsGet\PsGet
Get-ChildItem -Exclude "PsGet" -Directory -Name | Foreach-Object {
    Import-Module .\$_\$_
}

# Come back to PWD
Pop-Location

# Set up a Cmder prompt, adding the git prompt parts inside git repos
function global:prompt {
    $realLASTEXITCODE = $LASTEXITCODE
    $Host.UI.RawUI.ForegroundColor = "White"
    Write-Host("`n" + $pwd.ProviderPath) -NoNewLine -ForegroundColor Green
    if (Get-Module posh-git) {
        Write-VcsStatus
    }
    $global:LASTEXITCODE = $realLASTEXITCODE
    Write-Host "`nλ" -NoNewLine -ForegroundColor "DarkGray"
    return " "
}

# Load special features come from posh-git
if (Get-Module posh-git) {
    Enable-GitColors
    Start-SshAgent -Quiet
}

# Move to the wanted location
if (Test-Path Env:\CMDER_START) {
    Set-Location -Path $Env:CMDER_START
} elseif ($Env:CMDER_ROOT -and $Env:CMDER_ROOT.StartsWith($pwd)) {
    Set-Location -Path $Env:USERPROFILE
}

Leverage the Module Autoload path and save doing it ourselves.

# Add Cmder modules directory to the autoload path.
$CmderModulePath = Join-path $PSScriptRoot "psmodules/"

if( -not $env:PSModulePath.Contains($CmderModulePath) ){
    $env:PSModulePath = $env:PSModulePath.Insert(0, "$CmderModulePath;")
}

# Set up a Cmder prompt, adding the git prompt parts inside git repos
function global:prompt {
    $realLASTEXITCODE = $LASTEXITCODE
    $Host.UI.RawUI.ForegroundColor = "White"
    Write-Host("`n" + $pwd.ProviderPath) -NoNewLine -ForegroundColor Green
    if (Get-Module posh-git) {
        Write-VcsStatus
    }
    $global:LASTEXITCODE = $realLASTEXITCODE
    Write-Host "`nλ" -NoNewLine -ForegroundColor "DarkGray"
    return " "
}

# Load special features come from posh-git
if (Get-Module posh-git) {
    Enable-GitColors
    Start-SshAgent -Quiet
}

# Move to the wanted location
if (Test-Path Env:\CMDER_START) {
    Set-Location -Path $Env:CMDER_START
} elseif ($Env:CMDER_ROOT -and $Env:CMDER_ROOT.StartsWith($pwd)) {
    Set-Location -Path $Env:USERPROFILE
}


# install docker tools
choco install -y docker-machine -version 0.5.6
choco install -y docker-compose -version 1.5.2

Update docker-compose 1.6.0, docker-machine 0.6.0

# install docker tools
choco install -y docker-machine -version 0.6.0
choco install -y docker-compose -version 1.6.0


pushd

$steamData = "C:/Steam/DataMP/"
$steamCMDPath = "C:/Steam/steamcmd/"
$steamCMDZip = "C:/Steam/steamcmd.zip"

Add-Type -AssemblyName System.IO.Compression.FileSystem

if (!(Test-Path $steamData)) {
	mkdir "$steamData"
}
if (!(Test-Path $steamCMDPath)) {
	if (!(Test-Path $steamCMDZip)) {
		(New-Object System.Net.WebClient).DownloadFile("https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip", "$steamCMDZip");
	}
	[System.IO.Compression.ZipFile]::ExtractToDirectory($steamCMDZip, $steamCMDPath)
}

cd "$steamData"
& "$steamCMDPath/steamcmd.exe" "+login anonymous" "+force_install_dir $steamData" "+app_update 298740 -beta mptest -betapassword nt7WuDw9kdvB" "+quit"

popd

Revert "I don't even know anymore"

pushd

$steamData = "C:/Steam/Data/"
$steamCMDPath = "C:/Steam/steamcmd/"
$steamCMDZip = "C:/Steam/steamcmd.zip"

Add-Type -AssemblyName System.IO.Compression.FileSystem

if (!(Test-Path $steamData)) {
	mkdir "$steamData"
}
if (!(Test-Path $steamCMDPath)) {
	if (!(Test-Path $steamCMDZip)) {
		(New-Object System.Net.WebClient).DownloadFile("https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip", "$steamCMDZip");
	}
	[System.IO.Compression.ZipFile]::ExtractToDirectory($steamCMDZip, $steamCMDPath)
}

cd "$steamData"
& "$steamCMDPath/steamcmd.exe" "+login anonymous" "+force_install_dir $steamData" "+app_update 298740 +beta mptest +betapassword nt7WuDw9kdvB" "+quit"

popd


function GoodFunc
{
    param(
        [parmaeter(mandatory=$false)]
        [string]$Param1=$null
    )
    $Param1
}

Correct PSProvideDefaultParameterValue NoViolations test script

function GoodFunc
{
    param(
        [Parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Param1=$null
    )
    $Param1
}


#Requires -Modules VagrantMessages, VagrantVM

param(
    [parameter (Mandatory=$true)]
    [string] $Path
)

$check = Check-VagrantHyperVAccess -Path $Path
$result = @{
    root_dir = ($Path -split '\\')[0,2] -join '\';
    result = $check
}

Write-OutputMessage $(ConvertTo-Json $result)

Fix root directory generation on failed access

#Requires -Modules VagrantMessages, VagrantVM

param(
    [parameter (Mandatory=$true)]
    [string] $Path
)

$check = Check-VagrantHyperVAccess -Path $Path
$result = @{
    root_dir = ($Path -split '\\')[0,1] -join '\';
    result = $check
}

Write-OutputMessage $(ConvertTo-Json $result)


. "$PSScriptRoot/utils/WebConfig.ps1"
. "$PSScriptRoot/utils/MSBuild.ps1"
. "$PSScriptRoot/utils/MSDeploy.ps1"

$fixtures = @{
    default = @{
        Solution = "$PSScriptRoot\fixtures/default/HelixBuild.Sample.Web.sln";
        Project1 = "$PSScriptRoot\fixtures/default/Projects\HelixBuild.Sample.Web\HelixBuild.Sample.Web.csproj";
    }

}

$count = 1

Describe "CollectFilesFromHelixModules.Content" {

    Context "collecting helix modules for a project" {
        $projectPath = $fixtures.default.Project1

        $result = Invoke-MSBuildWithOutput -Project $projectPath -TargetName "CollectFilesFromHelixModulesContent" -OutputItem "FilesForPackagingFromHelixModules -> '%(DestinationRelativePath)'"

        Write-Host $result

        It "should include content from module projects" {
            $result -contains "App_Config\Include\HelixBuild.Feature1.config" | Should Be $true
        }
    }
}

Remove debug console output in test

. "$PSScriptRoot/utils/WebConfig.ps1"
. "$PSScriptRoot/utils/MSBuild.ps1"
. "$PSScriptRoot/utils/MSDeploy.ps1"

$fixtures = @{
    default = @{
        Solution = "$PSScriptRoot\fixtures/default/HelixBuild.Sample.Web.sln";
        Project1 = "$PSScriptRoot\fixtures/default/Projects\HelixBuild.Sample.Web\HelixBuild.Sample.Web.csproj";
    }

}

$count = 1

Describe "CollectFilesFromHelixModules.Content" {

    Context "collecting helix modules for a project" {
        $projectPath = $fixtures.default.Project1

        $result = Invoke-MSBuildWithOutput -Project $projectPath -TargetName "CollectFilesFromHelixModulesContent" -OutputItem "FilesForPackagingFromHelixModules -> '%(DestinationRelativePath)'"

        It "should include content from module projects" {
            $result -contains "App_Config\Include\HelixBuild.Feature1.config" | Should Be $true
        }
    }
}


### Install handy tools and apps for my dev machine
### Run this script from an administrative shell

Set-ExecutionPolicy RemoteSigned

# Install Chocolatey
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Install some software
choco install -y 7zip
choco install -y git
#choco install -y github-desktop    # Github Desktop gets updates so often that it's hard for the Chocolatey package to keep up
choco install -y gitkraken
choco install -y googlechrome
choco install -y hyper
choco install -y keepass
choco install -y linqpad
choco install -y nodejs
choco install -y notepadplusplus
choco install -y poshgit
choco install -y rdcman
choco install -y slack
choco install -y sql-server-management-studio
#choco install -y toggl             # The Toggl Desktop Chocolatey package is significantly behind as of May 2017, so I'll install it manually
#choco install -y visualstudiocode  # VS Code gets updates so often that it's hard for the Chocolatey package to keep up
RefreshEnv.cmd

Install Postman and NodeJS LTS

### Install handy tools and apps for my dev machine
### Run this script from an administrative shell

Set-ExecutionPolicy RemoteSigned

# Install Chocolatey
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Install some software
choco install -y 7zip
choco install -y git
#choco install -y github-desktop    # Github Desktop gets updates so often that it's hard for the Chocolatey package to keep up
choco install -y gitkraken
choco install -y googlechrome
choco install -y hyper
choco install -y keepass
choco install -y linqpad
choco install -y nodejs-lts
choco install -y notepadplusplus
choco install -y poshgit
choco install -y postman
choco install -y rdcman
choco install -y slack
choco install -y sql-server-management-studio
#choco install -y toggl             # The Toggl Desktop Chocolatey package is significantly behind as of May 2017, so I'll install it manually
#choco install -y visualstudiocode  # VS Code gets updates so often that it's hard for the Chocolatey package to keep up
RefreshEnv.cmd


#
# Install Powershell modules, if not already installed
#
function Test-Installed
{
  $Name = $args[0]
  Get-Module -ListAvailable -Name $Name
}
if (Test-Installed posh-git) {
  Import-Module posh-git
}
if (Test-Installed oh-my-posh) {
  Import-Module oh-my-posh
}
if (Test-Installed Get-ChildItemColor) {
  Import-Module Get-ChildItemColor
}
if (Test-Installed pwsh-handy-helpers) {
  Import-Module pwsh-handy-helpers
}
#
# Set Oh-my-posh theme
#
Set-Theme Agnoster
#
# Import Chocolatey profile
#
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path $ChocolateyProfile) {
  Import-Module "$ChocolateyProfile"
}
#
# Directory traversal shortcuts
#
for($i = 1; $i -le 5; $i++) {
  $u =  "".PadLeft($i,"u")
  $d =  $u.Replace("u","../")
  Invoke-Expression "function $u { push-location $d }"
}

Add bash-like autocomplete features using PSReadline

#
# Install Powershell modules, if not already installed
#
function Test-Installed
{
  $Name = $args[0]
  Get-Module -ListAvailable -Name $Name
}
if (Test-Installed PSReadLine) {
  Import-Module PSReadLine
  Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete
  Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
  Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward
}
if (Test-Installed posh-git) {
  Import-Module posh-git
}
if (Test-Installed oh-my-posh) {
  Import-Module oh-my-posh
}
if (Test-Installed Get-ChildItemColor) {
  Import-Module Get-ChildItemColor
}
if (Test-Installed pwsh-handy-helpers) {
  Import-Module pwsh-handy-helpers
}
#
# Set Oh-my-posh theme
#
Set-Theme Agnoster
#
# Import Chocolatey profile
#
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path $ChocolateyProfile) {
  Import-Module "$ChocolateyProfile"
}
#
# Directory traversal shortcuts
#
for($i = 1; $i -le 5; $i++) {
  $u =  "".PadLeft($i,"u")
  $d =  $u.Replace("u","../")
  Invoke-Expression "function $u { push-location $d }"
}


Describe "Basic" {
    Context "Arithmetic" {
        It "1 + 1 shoukd be 2" {
            1 + 1 | Should -Be 2
        }
    }

    Context "String" {
        It "An i letter should not be in team - like" {
            "team" | Should -Not -BeLike "*i*"
        }

        It "An i letter should not be in team - match" {
            "team" | Should -Not -Match "i"
        }
    }

    Context "AAA Aproach" {
        $stringToTest = "team"

        It "An i letter should not be in team - like" {
            $stringToTest | Should -Not -BeLike "*i*"
        }

        It "An e letter should be in team - like" {
            $stringToTest | Should -BeLike "*e*"
        }

        It "An i letter should not be in team - match" {
            $stringToTest | Should -Not -Match "i"
        }
    }
}


param([String]$Tests="Functional", [switch]$Parallel, [switch]$Build);

$paths = Get-ChildItem Tests -Directory | % { Join-Path $_.FullName -ChildPath ("bin/Debug/netcoreapp2.2/$($_.Name).dll") };
$filter = "";
$execute = "";

if ($Tests -eq "functional" -or $Tests -eq "f")
{
    $filter = "--TestCaseFilter:Category=Functional";
}
elseif ($Tests -eq "performance" -or $Tests -eq "p")
{
    $filter = "--TestCaseFilter:Category=Performance";
}

if ($Parallel)
{
    $execute = "--Parallel";
}

if ($Build)
{
    dotnet build AppBrix.sln;
}

dotnet vstest $paths $filter $execute;

Add flag for running tests in Release

param([String]$Tests="Functional", [switch]$Parallel, [switch]$Build, [switch]$Release);

$version = "netcoreapp2.2"

$configuration = "Debug";
if ($Release)
{
    $configuration = "Release";
}

if ($Build)
{
    dotnet build AppBrix.sln --configuration $($configuration);
}

$filter = "";
if ($Tests -eq "functional" -or $Tests -eq "f")
{
    $filter = "--TestCaseFilter:Category=Functional";
}
elseif ($Tests -eq "performance" -or $Tests -eq "p")
{
    $filter = "--TestCaseFilter:Category=Performance";
}

$execute = "";
if ($Parallel)
{
    $execute = "--Parallel";
}

$paths = Get-ChildItem Tests -Directory | % { Join-Path $_.FullName -ChildPath ("bin/$($configuration)/$($version)/$($_.Name).dll") };
dotnet vstest $paths $filter $execute;


$deployToolsDir = Split-Path ((Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path)

if (Test-Path variable:\OctopusParameters)
{
    foreach($kp in $OctopusParameters.GetEnumerator())
    {
        Set-Content ("env:\" + $kp.Key) ($kp.Value) -Force
    }
}

if(!(Test-Path "env:\ConfigOnly"))
{
    Set-Content "env:\ConfigOnly" $false
}

function ensconce
{
    if (@($input).Count -ne 0)
    {
        $input.Reset()
        $results = $input | & "$deployToolsDir\ensconce.exe" $args 2>&1
    }
    else {
        $results = & "$deployToolsDir\ensconce.exe" $args 2>&1
    }
    if ($LASTEXITCODE -ne 0)
    {
        if (Test-Path env:\TEAMCITY_VERSION)
        {
            Write-Host "##teamcity[buildStatus status='FAILURE' text='{build.status.text}; Ensconce failure']"
            $results
            exit $LASTEXITCODE
        }
        else {
        throw (
"Ensconce operation failed.
$results")
        }
    }
    $results
}

function EnsurePath([string]$name)
{
	$path = $name | ensconce -i

	if ((Test-Path $path) -eq $False)
	{
		md $path
	}
}

function is64bit() {
  return ([IntPtr]::Size -eq 8)
}

Update of is64bit so it's not dependent on version of Powershell being used

$deployToolsDir = Split-Path ((Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path)

if (Test-Path variable:\OctopusParameters)
{
    foreach($kp in $OctopusParameters.GetEnumerator())
    {
        Set-Content ("env:\" + $kp.Key) ($kp.Value) -Force
    }
}

if(!(Test-Path "env:\ConfigOnly"))
{
    Set-Content "env:\ConfigOnly" $false
}

function ensconce
{
    if (@($input).Count -ne 0)
    {
        $input.Reset()
        $results = $input | & "$deployToolsDir\ensconce.exe" $args 2>&1
    }
    else {
        $results = & "$deployToolsDir\ensconce.exe" $args 2>&1
    }
    if ($LASTEXITCODE -ne 0)
    {
        if (Test-Path env:\TEAMCITY_VERSION)
        {
            Write-Host "##teamcity[buildStatus status='FAILURE' text='{build.status.text}; Ensconce failure']"
            $results
            exit $LASTEXITCODE
        }
        else {
        throw (
"Ensconce operation failed.
$results")
        }
    }
    $results
}

function EnsurePath([string]$name)
{
	$path = $name | ensconce -i

	if ((Test-Path $path) -eq $False)
	{
		md $path
	}
}

function is64bit() {
  return ( (Get-WmiObject Win32_OperatingSystem).OSArchitecture -eq "64-bit")
}


<#
	My Function
#>
function Get-Function {

}

Add Write-breakline cmdlet to utils.psm1

function Write-Breakline () {
	Param(
		[string]$Title = ""
	)

	$line = "`n----------------------------------------------------------------------";
	$limit = $line.Length;
	if (-not [String]::IsNullOrEmpty($Title))
	{
		$line = $line.Insert(4, " $Title ");
		if ($line.Length -gt $limit) { $line = $line.Substring(0, $limit); }
	}

	Write-Host $line;
	Write-Host "";
}


[CmdletBinding()]
Param(
    [Parameter(Position=1)]$IARRoot = "${env:ProgramFiles(x86)}\IAR Systems\Embedded Workbench 7.3"
)

# NOTE: Also requires the "strings" tool from sysinternals on your path
# choco install -y sysinternals is an easy way to make that happen.

$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

# Build with IAR
Start-Process (Join-Path $IARRoot "common\bin\IarBuild.exe") -ArgumentList @('Project.ewp', '-build', 'Production') -WorkingDirectory $PSScriptRoot -NoNewWindow -Wait

# Generate the config file by grepping for the build string in the elf file.
# Couldn't find any better way to extract this from the object files or final elf file...
$BuildString = (strings -q (Join-Path $PSScriptRoot 'Production\Exe\Project.out') | Select-String -Pattern '\[Sensics')
Out-File (Join-Path $PSScriptRoot 'Production\Exe\Config.txt') -InputObject $BuildString

Write-Host 'Completed build identified as:'
Write-Host $BuildString
Write-Host "See the .hex and Config.txt files in $(Join-Path $PSScriptRoot 'Production\Exe')"

Fix production image build script.

[CmdletBinding()]
Param(
    [Parameter(Position=1)]$IARRoot = "${env:ProgramFiles(x86)}\IAR Systems\Embedded Workbench 7.3"
)

# NOTE: Also requires the "strings" tool from sysinternals on your path
# choco install -y sysinternals is an easy way to make that happen.

$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

# Build with IAR
Start-Process (Join-Path $IARRoot "common\bin\IarBuild.exe") -ArgumentList @('Project.ewp', '-build', 'Production') -WorkingDirectory $PSScriptRoot -NoNewWindow -Wait

# Generate the config file by grepping for the build string in the elf file.
# Couldn't find any better way to extract this from the object files or final elf file...
$BuildString = (strings (Join-Path $PSScriptRoot 'Production\Exe\Project.out') | Select-String -Pattern '\[Sensics')
Out-File (Join-Path $PSScriptRoot 'Production\Exe\Config.txt') -InputObject $BuildString

Write-Host 'Completed build identified as:'
Write-Host $BuildString
Write-Host "See the .hex and Config.txt files in $(Join-Path $PSScriptRoot 'Production\Exe')"


Write-Host "Installing chocolatey"
Set-ExecutionPolicy Unrestricted
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

((New-Object System.Net.WebClient).DownloadFile('https://github.com/ctfhacker/windows-setup/archive/master.zip', 'C:\Windows\Temp\master.zip'))

cd C:\Windows\Temp\
mkdir master
$shell = new-object -com shell.application
$zip = $shell.NameSpace("C:\Windows\Temp\master.zip")
foreach($item in $zip.items())
{
    $shell.Namespace(".\master").copyhere($item)
}

cd .\master\windows-setup-master

Get-ChildItem | ForEach-Object {
    Write-Host "Executing " + $_.FullName
    & $_.FullName
}

# Write-Host "Rebooting.."
# shutdown /r /t 0

Use native powershell for unzipping

Write-Host "Installing chocolatey"
Set-ExecutionPolicy Unrestricted
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

((New-Object System.Net.WebClient).DownloadFile('https://github.com/ctfhacker/windows-setup/archive/master.zip', 'C:\Windows\Temp\master.zip'))

cd C:\Windows\Temp\
mkdir master
$shell = new-object -com shell.application
$zip = $shell.NameSpace("C:\Windows\Temp\master.zip")
foreach($item in $zip.items())
{
    $shell.Namespace("C:\Windows\Temp\master").copyhere($item)
}

cd .\master\windows-setup-master

Get-ChildItem | ForEach-Object {
    Write-Host "Executing " + $_.FullName
    & $_.FullName
}

# Write-Host "Rebooting.."
# shutdown /r /t 0


$mgr = New-Object -ComObject Microsoft.Update.ServiceManager -Strict
$mgr.ClientApplicationID = "packer"
$mgr.RemoveService('7971f918-a847-4430-9279-4a52d1efe18d')

Use the registry to stop Windows Updates

$WindowsUpdateKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update"

$Update_Never    = 1
$Update_Check    = 2
$Update_Download = 3
$Update_Auto     = 4

Set-ItemProperty -Path $WindowsUpdateKey -Name AUOptions       -Value $Update_Never -Force -Confirm:$false
Set-ItemProperty -Path $WindowsUpdateKey -Name CachedAUOptions -Value $Update_Never -Force -Confirm:$false


# Set versions for AssemblyInfo.cs
$version = ( Get-Content .\Version.txt );
$env:AssemblyBaseVersion = $version | foreach{ if( $_ -match "^\d+\.\d+" ){ $matches[0] } }
if ( $env:APPVEYOR_REPO_TAG -ne "True" )
{
	if ( ${env:APPVEYOR_BUILD_NUMBER} -eq $null )
	{
		$now = [DateTime]::UtcNow
		$daysSpan = $now - ( New-Object DateTime( $now.Year, 1, 1 ) )
		$env:PackageVersion = "${version}-{0:yy}{1:000}" -f @( $now, $daysSpan.Days )
	}
	elseif ( ${version} -match "^[\d.]+$" )
	{
		$env:PackageVersion = "${version}-final-${env:APPVEYOR_BUILD_NUMBER}"
	}
	else
	{
		$env:PackageVersion = "${version}-${env:APPVEYOR_BUILD_NUMBER}"
	}
}
else
{
	$env:PackageVersion = $version
}

Write-Information "version:'${version}', AssemblyBaseVersion:'${AssemblyBaseVersion}', PackageVersion:'${PackageVersion}'"

Fix nightly (dev) package versioning.

# Set versions for AssemblyInfo.cs
$version = ( Get-Content .\Version.txt );
$env:AssemblyBaseVersion = $version | foreach{ if( $_ -match "^\d+\.\d+" ){ $matches[0] } }
if ( $env:APPVEYOR_REPO_TAG -ne "True" )
{
	if ( ${env:APPVEYOR_BUILD_NUMBER} -eq $null )
	{
		$now = [DateTime]::UtcNow
		$daysSpan = $now - ( New-Object DateTime( $now.Year, 1, 1 ) )
		$env:PackageVersion = "${version}-dev-{0:yy}{1:000}" -f @( $now, $daysSpan.Days )
	}
	elseif ( ${version} -match "^[\d.]+$" )
	{
		$env:PackageVersion = "${version}-final-${env:APPVEYOR_BUILD_NUMBER}"
	}
	else
	{
		$env:PackageVersion = "${version}-dev-${env:APPVEYOR_BUILD_NUMBER}"
	}
}
else
{
	$env:PackageVersion = $version
}

Write-Information "version:'${version}', AssemblyBaseVersion:'${AssemblyBaseVersion}', PackageVersion:'${PackageVersion}'"


pushd

$steamData = "C:/Steam/Data/"
$steamCMDPath = "C:/Steam/steamcmd/"
$steamCMDZip = "C:/Steam/steamcmd.zip"

Add-Type -AssemblyName System.IO.Compression.FileSystem

if (!(Test-Path $steamData)) {
	mkdir "$steamData"
}
if (!(Test-Path $steamCMDPath)) {
	if (!(Test-Path $steamCMDZip)) {
		(New-Object System.Net.WebClient).DownloadFile("https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip", "$steamCMDZip");
	}
	[System.IO.Compression.ZipFile]::ExtractToDirectory($steamCMDZip, $steamCMDPath)
}

cd "$steamData"
& "$steamCMDPath/steamcmd.exe" "+login anonymous" "+force_install_dir $steamData" "+app_update 298740" "+quit"

popd

Make Jenkins download playtest branch

pushd

$steamData = "C:/Steam/Data-playtest/"
$steamCMDPath = "C:/Steam/steamcmd/"
$steamCMDZip = "C:/Steam/steamcmd.zip"

Add-Type -AssemblyName System.IO.Compression.FileSystem

if (!(Test-Path $steamData)) {
	mkdir "$steamData"
}
if (!(Test-Path $steamCMDPath)) {
	if (!(Test-Path $steamCMDZip)) {
		(New-Object System.Net.WebClient).DownloadFile("https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip", "$steamCMDZip");
	}
	[System.IO.Compression.ZipFile]::ExtractToDirectory($steamCMDZip, $steamCMDPath)
}

cd "$steamData"
& "$steamCMDPath/steamcmd.exe" "+login anonymous" "+force_install_dir $steamData" "+app_update 298740 -beta playtest -betapassword nt7WuDw9kdvC" "+quit"

popd


param (
[string] $filePath,
[string] $major,
[string] $minor,
[string] $patch
)

# Get the task.json as a powershell object
$task = Get-Content -Raw -Path $filePath | ConvertFrom-Json

$task.version.Major = $major
$task.version.Minor = $minor
$task.version.Patch = $patch

# get this as a string again

ConvertTo-Json $task -Depth 100 | Set-Content -Path $filePath

Throw exception if script for patching TFS task version is called with invalid arguments.

param (
[string] $filePath,
[string] $major,
[string] $minor,
[string] $patch
)

if ([string]::IsNullOrWhiteSpace($filePath)) {
    throw "File path needs to be provided."
}

if ([string]::IsNullOrWhiteSpace($major)) {
    throw "Major version number needs to be provided."
}

if ([string]::IsNullOrWhiteSpace($minor)) {
    throw "Minor version number needs to be provided."
}

if ([string]::IsNullOrWhiteSpace($patch)) {
    throw "Patch level needs to be provided."
}

Write-Host "Set version in '$filePath' to $major.$minor.$patch"

# Get the task.json as a powershell object
$task = Get-Content -Raw -Path $filePath | ConvertFrom-Json

$task.version.Major = $major
$task.version.Minor = $minor
$task.version.Patch = $patch

# get this as a string again

ConvertTo-Json $task -Depth 100 | Set-Content -Path $filePath


# Stop script execution when a non-terminating error occurs
$ErrorActionPreference = "Stop"

$docker_version="20.10.9"
$docker_compose_version="1.29.2"

Write-Output "Upgrading DockerMsftProvider module"
Update-Module -Name DockerMsftProvider -Force

Write-Output "Printing available docker versions"
Find-Package -providerName DockerMsftProvider -AllVersions

Write-Output "Installing docker enterprise edition"
Stop-Service docker
Install-Package -Name docker -ProviderName DockerMsftProvider -Force -RequiredVersion $docker_version
Start-Service docker

Write-Output "Installing docker-compose"
choco install -y docker-compose --version $docker_compose_version
If ($lastexitcode -ne 0) { Exit $lastexitcode }

Write-Output "Installing jq"
choco install -y jq
If ($lastexitcode -ne 0) { Exit $lastexitcode }

Downgrade docker version for windows to 20.10.7

# Stop script execution when a non-terminating error occurs
$ErrorActionPreference = "Stop"

$docker_version="20.10.7"
$docker_compose_version="1.29.2"

Write-Output "Upgrading DockerMsftProvider module"
Update-Module -Name DockerMsftProvider -Force

Write-Output "Printing available docker versions"
Find-Package -providerName DockerMsftProvider -AllVersions

Write-Output "Installing docker enterprise edition"
Stop-Service docker
Install-Package -Name docker -ProviderName DockerMsftProvider -Force -RequiredVersion $docker_version
Start-Service docker

Write-Output "Installing docker-compose"
choco install -y docker-compose --version $docker_compose_version
If ($lastexitcode -ne 0) { Exit $lastexitcode }

Write-Output "Installing jq"
choco install -y jq
If ($lastexitcode -ne 0) { Exit $lastexitcode }


$scriptDir = Split-Path ((Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path)

if(Test-Path $DeployToolsDir)
{
    Write-Host "Removing Deploy Tools Directory Found at $DeployToolsDir"
    Remove-Item $DeployToolsDir -force
}

Write-Host "Creating Deploy Tools Directory at $DeployToolsDir"
New-Item $DeployToolsDir -Type container

Write-Host "Deploying Tools to $DeployToolsDir"
Copy-Item "$scriptDir\Content\*" $DeployToolsDir -Force -Recurse

Add a recurse to the delete

$scriptDir = Split-Path ((Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path)

if(Test-Path $DeployToolsDir)
{
    Write-Host "Removing Deploy Tools Directory Found at $DeployToolsDir"
    Remove-Item $DeployToolsDir -Force -Recurse
}

Write-Host "Creating Deploy Tools Directory at $DeployToolsDir"
New-Item $DeployToolsDir -Type container

Write-Host "Deploying Tools to $DeployToolsDir"
Copy-Item "$scriptDir\Content\*" $DeployToolsDir -Force -Recurse


Build script for CI server (properties don't work there)

Framework "4.0x86"

Task Build-Master {
	Invoke-Psake default.ps1 -properties @{autoVersion = $false}
}

Task Build-Develop {
	Invoke-Psake default.ps1
}


# Copyright 2015 Google Inc. All Rights Reserved.
# Licensed under the Apache License Version 2.0.
#
# Bootstraps the Google Cloud cmdlets into the current PowerShell session.

function Get-ScriptDirectory
{
    $invocation = (Get-Variable MyInvocation -Scope 1).Value
    return Split-Path $invocation.MyCommand.Path
}

$modulePath = Join-Path (Get-ScriptDirectory) "GoogleCloudPowerShell.psd1"
Import-Module $modulePath

$Env:UserProfile
clear

$welcomeBanner = "Google Cloud PowerShell"
Write-Output $welcomeBanner

Update text on the Bootstrapping script

# Copyright 2015 Google Inc. All Rights Reserved.
# Licensed under the Apache License Version 2.0.
#
# Bootstraps the Google Cloud cmdlets into the current PowerShell session.

function Get-ScriptDirectory
{
    $invocation = (Get-Variable MyInvocation -Scope 1).Value
    return Split-Path $invocation.MyCommand.Path
}

$modulePath = Join-Path (Get-ScriptDirectory) "GoogleCloudPowerShell.psd1"
Import-Module $modulePath

$Env:UserProfile
clear

Write-Output "Google Cloud Tools for PowerShell"


Add basic PowerShell script for building images.

Param(
    [Parameter(Mandatory=$true)]
    [string] $Repo,

    [Parameter()]
    [string] $Version = '1.0.0-dev'
)

$Components = @(
    'api',
    'sql-executor',
    'provisioning',
    'ui'
)

$docker = Get-Command docker

Write-Host 'Building images...'
ForEach ($Component in $Components) {
    & $docker build -t "${Repo}/${Component}:${Version}" -f Dockerfile.${Component} .
}

Write-Host 'Pushing images...'
ForEach ($Component in $Components) {
    & $docker push "${Repo}/${Component}:${Version}"
}


# "dot source" this file in my $PROFILE

# Define git related functions for aliases
function GitDiff { git diff }
function GitLog { git log --graph --oneline --decorate }
function GitShowBranch { git show-branch }
function GitStatus { git status -s }

# Define git related aliases. Note, "gl" is for Get-Location by default.
Set-Alias gd GitDiff
Set-Alias gb GitShowBranch
Set-Alias gs GitStatus
if ($Host.Version.Major -ge 7) {
    Set-Alias -Force gl GitLog
} else {
    Set-Alias -Force -Option AllScope gl GitLog
}

# Use Emacs keybindings
Set-PSReadLineOption -EditMode Emacs

# Use standard-ish prompt using "~" for user profile directory
function prompt {
    "PS " + "$(Get-Location)".Replace($env:USERPROFILE, "~") + "> "
}

Remove alias of curl & wget if defined

# "dot source" this file in my $PROFILE

# Define git related functions for aliases
function GitDiff { git diff }
function GitLog { git log --graph --oneline --decorate }
function GitShowBranch { git show-branch }
function GitStatus { git status -s }

# Define git related aliases. Note, "gl" is for Get-Location by default.
Set-Alias gd GitDiff
Set-Alias gb GitShowBranch
Set-Alias gs GitStatus
if ($Host.Version.Major -ge 7) {
    Set-Alias -Force gl GitLog
} else {
    Set-Alias -Force -Option AllScope gl GitLog
}

# Remove unnecessary aliases
Get-ChildItem Alias: | Where-Object -Property Name -in @("curl", "wget") | Remove-Item

# Use Emacs keybindings
Set-PSReadLineOption -EditMode Emacs

# Use standard-ish prompt using "~" for user profile directory
function prompt {
    "PS " + "$(Get-Location)".Replace($env:USERPROFILE, "~") + "> "
}


dotnet restore;
dotnet build -c Release;
dotnet pack --no-build -c Release ShopifySharp/ShopifySharp.csproj;
dotnet pack --no-build -c Release ShopifySharp.Experimental/ShopifySharp.Experimental.fsproj;

$nupkg = (Get-ChildItem "ShopifySharp/bin/Release/*.nupkg")[0];
$experimentalNupkg = (Get-ChildItem "ShopifySharp.Experimental/bin/Release/*.nupkg")[0];

# Push the nuget packages to AppVeyor's artifact list.
Push-AppveyorArtifact $nupkg.FullName -FileName $nupkg.Name -DeploymentName "ShopifySharp.nupkg";
Push-AppveyorArtifact $experimentalNupkg.FullName -FileName $experimentalNupkg.Name -DeploymentName "ShopifySharp.Experimental.nupkg";

Build all non-test projects as both release and prerelease artifacts

#! /bin/pwsh

$artifacts = "./artifacts";

dotnet restore;
dotnet build -c Release;

# Get the prerelease version suffix from AppVeyor's build revision
# Source: https://github.com/another-guy/Mirror/blob/9034cd0d6ee6ec072469f6c0f07bdb16b4b5764e/Build.ps1
$revision = @{ $true = $env:APPVEYOR_BUILD_NUMBER; $false = 1 }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL];
$revision = "b{0:D5}" -f [convert]::ToInt32($revision, 10)

# Get a list of the projects that will be built and packed (those that aren't test projects)
$projects = gci "./ShopifySharp*/*.*sproj" | where-object -filterscript { $_ -inotmatch "tests" }

# Pack the projects as both release and prerelease versions
# TODO: use the following source to create a script that knows when to pack as release or prerelease
# example script: https://github.com/another-guy/Mirror/blob/9034cd0d6ee6ec072469f6c0f07bdb16b4b5764e/Build.ps1
$projects | % { dotnet pack --no-build -c Release -o $artifacts $_ }
$projects | % { dotnet pack --no-build -c Release -o $artifacts --version-suffix $revision $_ }

# Gather all nuget packages and push them to AppVeyor artifacts
gci "./ShopifySharp*/$artifacts/*.nupkg" | % {
    Push-AppveyorArtifact $_.FullName -FileName $_.Name -DeploymentName $_.Name
}


$ErrorActionPreference = 'Stop'

$paramsFile = Join-Path $env:WORKSPACE "mesos-build-parameters.txt"
$consoleLogFile = Join-Path $env:WORKSPACE "mesos-build-${env:BRANCH}-${env:BUILD_NUMBER}.log"
$windowsBuildScript = (Resolve-Path "$PSScriptRoot\..\start-windows-build.ps1").Path
& "$windowsBuildScript" -Branch $env:BRANCH -CommitID $env:COMMIT_ID -ReviewID $env:REVIEW_ID -ParametersFile $paramsFile | Tee-Object -FilePath $consoleLogFile
$exitCode = $LASTEXITCODE
Remove-Item -Force -ErrorAction SilentlyContinue -Path $consoleLogFile
exit $exitCode

Add EnableSSL to the main Reviewbot Jenkins job script

$ErrorActionPreference = 'Stop'

$paramsFile = Join-Path $env:WORKSPACE "mesos-build-parameters.txt"
$consoleLogFile = Join-Path $env:WORKSPACE "mesos-build-${env:BRANCH}-${env:BUILD_NUMBER}.log"
$windowsBuildScript = (Resolve-Path "$PSScriptRoot\..\start-windows-build.ps1").Path
& "$windowsBuildScript" -Branch $env:BRANCH -CommitID $env:COMMIT_ID -ReviewID $env:REVIEW_ID -ParametersFile $paramsFile -EnableSSL | Tee-Object -FilePath $consoleLogFile
$exitCode = $LASTEXITCODE
Remove-Item -Force -ErrorAction SilentlyContinue -Path $consoleLogFile
exit $exitCode


# "dot source" this file in my $PROFILE

# Define git related functions for aliases
function GitDiff { git diff }
function GitLog { git log --graph --oneline --decorate }
function GitShowBranch { git show-branch }
function GitStatus { git status -s }

# Define git related aliases. Note, "gl" is for Get-Location by default.
Set-Alias gd GitDiff
Set-Alias gb GitShowBranch
Set-Alias gs GitStatus
if ($Host.Version.Major -ge 7) {
    Set-Alias -Force gl GitLog
} else {
    Set-Alias -Force -Option AllScope gl GitLog
}

# Remove unnecessary aliases
Get-ChildItem Alias: | Where-Object -Property Name -in @("curl", "wget") | Remove-Item

# Use Emacs keybindings
Set-PSReadLineOption -EditMode Emacs

# Use standard-ish prompt using "~" for user profile directory
function prompt {
    "PS " + "$(Get-Location)".Replace($env:USERPROFILE, "~") + "> "
}

Allow adding args for Git related aliases

# "dot source" this file in my $PROFILE

# Define git related functions for aliases
function GitDiff { git diff $args }
function GitLog { git log --graph --oneline --decorate $args }
function GitShowBranch { git show-branch $args }
function GitStatus { git status -s $args }

# Define git related aliases. Note, "gl" is for Get-Location by default.
Set-Alias gd GitDiff
Set-Alias gb GitShowBranch
Set-Alias gs GitStatus
if ($Host.Version.Major -ge 7) {
    Set-Alias -Force gl GitLog
} else {
    Set-Alias -Force -Option AllScope gl GitLog
}

# Remove unnecessary aliases
Get-ChildItem Alias: | Where-Object -Property Name -in @("curl", "wget") | Remove-Item

# Use Emacs keybindings
Set-PSReadLineOption -EditMode Emacs

# Use standard-ish prompt using "~" for user profile directory
function prompt {
    "PS " + "$(Get-Location)".Replace($env:USERPROFILE, "~") + "> "
}


@{

# Script module or binary module file associated with this manifest.
ModuleToProcess = 'account-monitoring-control.psm1'

# Version number of this module.
ModuleVersion = '2.0.0'

# ID used to uniquely identify this module
GUID = '2cf86856-3550-4150-8aaa-b72e83f819b0'

# Author of this module
Author = 'PoshSec'

# Copyright statement for this module
Copyright = 'BSD 3-Clause'

# Description of the functionality provided by this module
Description = 'PoshSec Account Monitoring and Control Module'

# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '2.0'

# Cmdlets to export from this module
CmdletsToExport = '*'

# Functions to export from this module
FunctionsToExport = '*'

# List of all modules packaged with this module.
ModuleList = @(@{ModuleName = 'account-monitoring-control'; ModuleVersion = '1.0.0.0'; GUID = '2cf86856-3550-4150-8aaa-b72e83f819b0'})

# List of all files packaged with this module
FileList = 'account-monitoring-control.psm1', 'account-monitoring-control.psd1', 'Get-SecAccountThatDontExpire.ps1',
     'Get-SecAccountThatExpire.ps1', 'Get-SecAllAccount.ps1', 'Get-SecDisabledAccount.ps1',
     'Get-SecLockedOutAccount.ps1', 'Get-SecPasswordOverExpireDate.ps1', 'Show-SecDisabledAccountAccess.ps1',
     'Get-SecInactiveAccount.ps1', 'Find-SecAccountNameChecker.ps1', 'Get-SecAdminAccount.ps1', 'Enable-SecVulnAccount.ps1'
}


Add simple Enable-PSBreakpoint and Disable-PSBreakpoint cmdlet tests

Describe "Enable and Disable PSBreakpoints" -Tag "CI" {
    BeforeAll {
        $path = Setup -F testbp.ps1 -content "get-command`nget-date`nget-location" -pass
        $bp = set-psbreakpoint -script $path -line 2
        disable-psbreakpoint $bp
    }
    AfterAll {
        $bp | remove-psbreakpoint
    }
    It "Enable-PSBreakpoint should enable the breakpoint" {
        $bp.Enabled | should be $false
        Enable-PSBreakpoint $bp
        $bp.Enabled | Should be $true
    }
    It "Disable-PSBreakpoint should disable the breakpoint" {
        Enable-PSBreakpoint $bp
        $bp.Enabled | Should be $true
        Disable-PSBreakpoint $bp
        $bp.Enabled | Should be $false
    }
}


Add script to source VC env into powershell

# Setups VC environment from bat.
# It runs environment in cmd and extract all variables into  temp file.
# which then is used to source environment.
function set_vc($arch) {
    $vc_env = "vcvars$arch.bat"
    if (Get-Command $vc_env -errorAction SilentlyContinue)
    {
        $tempFile = [IO.Path]::GetTempFileName()

        ## Store the output of cmd.exe. We also ask cmd.exe to output
        ## the environment table after the batch file completes
        cmd /Q /c " $vc_env  && set > $tempFile " | out-null

        ## Go through the environment variables in the temp file.
        ## For each of them, set the variable in our local environment.
        Get-Content $tempFile | Foreach-Object {
            if($_ -match "^(.*?)=(.*)$")
            {
                Set-Content "env:\$($matches[1])" $matches[2]
            }
        }

        Remove-Item $tempFile
    }
    else {
        echo "Cannot find vcvars.bat for your arch '$arch'"
    }
}


<#

.SYNOPSIS
This is a simple Powershell script to ease change of the .NET Project name

.DESCRIPTION
Changes project name to the new one by renaming all files, folders and text occurences of the default project name.

.EXAMPLE
./RenameProject.ps1 "MyNewWebSite"

#>
Param(
    [Parameter(Mandatory=$true, HelpMessage=”You must provide a project name”)]
    [String]$ProjectName
 )

 $oldProjectName = "CloudBoilerplateNet"

# Replace occurences within a files
$files = Get-ChildItem . -Recurse -File
foreach ($file in $files)
{
    (Get-Content $file.PSPath) |
        Foreach-Object { $_ -replace $oldProjectName, $NewProjectName } |
            Set-Content $file.PSPath
}

# Rename files & directories
Get-ChildItem . -Recurse -Filter *$oldProjectName* |
    Rename-Item -NewName { $_.Name -replace $oldProjectName, $NewProjectName }


Write-Verbose -Message (Get-DotFilesMessage -Message 'Configuring aliases ...')

# Some useful aliases
Set-Alias -Name cop -Value Compare-ObjectProperties
Set-Alias -Name gh -Value Get-Help
Set-Alias -Name gita -Value Invoke-GitChildDir
Set-Alias -Name rdn -Value Resolve-DnsName
Set-Alias -Name up -Value Update-Profile
Set-Alias -Name which -Value Get-Command

# Windows only
if (Test-IsWindows) {
    # Remove the curl alias if the real deal is present
    if (Get-Command -Name curl.exe -ErrorAction Ignore) {
        Remove-Item -LiteralPath Alias:\curl -ErrorAction Ignore
    }

    # Remove the sc alias in favour of the sc.exe utility
    if (Get-Command -Name sc.exe -ErrorAction Ignore) {
        Remove-Item -LiteralPath Alias:\sc -ErrorAction Ignore
    }
}

Remove PoSh wget alias if the real deal is present

Write-Verbose -Message (Get-DotFilesMessage -Message 'Configuring aliases ...')

# Some useful aliases
Set-Alias -Name cop -Value Compare-ObjectProperties
Set-Alias -Name gh -Value Get-Help
Set-Alias -Name gita -Value Invoke-GitChildDir
Set-Alias -Name rdn -Value Resolve-DnsName
Set-Alias -Name up -Value Update-Profile
Set-Alias -Name which -Value Get-Command

# Windows only
if (Test-IsWindows) {
    # Remove the curl alias if the real deal is present
    if (Get-Command -Name curl.exe -ErrorAction Ignore) {
        Remove-Item -LiteralPath Alias:\curl -ErrorAction Ignore
    }

    # Remove the sc alias in favour of the sc.exe utility
    if (Get-Command -Name sc.exe -ErrorAction Ignore) {
        Remove-Item -LiteralPath Alias:\sc -ErrorAction Ignore
    }

    # Remove the wget alias if the real deal is present
    if (Get-Command -Name wget.exe -ErrorAction Ignore) {
        Remove-Item -LiteralPath Alias:\wget -ErrorAction Ignore
    }
}


if (Get-Command -Name dotnet -ErrorAction Ignore) {
    Write-Verbose -Message '[dotfiles] Loading .NET Core settings ...'

    # Opt-out of telemetry
    Set-Item -Path Env:\DOTNET_CLI_TELEMETRY_OPTOUT -Value 'true'
} else {
    Write-Verbose -Message '[dotfiles] Skipping .NET Core settings as unable to locate dotnet.'
}

Add dotnet command completion for PowerShell

if (Get-Command -Name dotnet -ErrorAction Ignore) {
    Write-Verbose -Message '[dotfiles] Loading .NET Core settings ...'

    # Opt-out of telemetry
    Set-Item -Path Env:\DOTNET_CLI_TELEMETRY_OPTOUT -Value 'true'

    # Command completion for the dotnet CLI
    # https://docs.microsoft.com/en-us/dotnet/core/tools/enable-tab-autocomplete
    Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock {
        Param($CommandName, $WordToComplete, $CursorPosition)
        dotnet complete --position $CursorPosition, "$WordToComplete" | ForEach-Object {
            [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
        }
    }
} else {
    Write-Verbose -Message '[dotfiles] Skipping .NET Core settings as unable to locate dotnet.'
}