AzureServiceBusManagement.psm1

# This is a locally sourced Imports file for local development.
# It can be imported by the psm1 in local development to add script level variables.
# It will merged in the build process. This is for local development only.

# region script variables
# $script:resourcePath = "$PSScriptRoot\Resources"


Function Get-SbApiToken {
    <#
.SYNOPSIS
    This cmdlet returns an Azure API access token for the Azure Service Bus Resource Provider
.OUTPUTS
    API Token Object
.NOTES
    This can technically also be used for other services.
#>


    [CmdletBinding()]
    param (
        #Your Azure Context. This will be discovered automatically if you have already logged in with Connect-AzAccount
        [Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext]
        $Context = (Get-AzContext | Select-Object -First 1),

        #The application resource principal you wish to request a token for. Defaults to the Undocumented Azure Portal API
        #Common Examples: https://management.core.windows.net/ https://graph.windows.net/
        $Resource = 'https://servicebus.azure.net'
    )

    if (-not $Context) {
        Connect-AzAccount -ErrorAction Stop
        $Context = (Get-AzContext | Select-Object -First 1)
    }

    return (Get-AzAccessToken -ResourceUrl $Resource).Token
}

<#
.EXTERNALHELP AzureServiceBusManagement-help.xml
#>

function Receive-SbMessage {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true,
            HelpMessage = 'The name of the Service Bus Namespace')]
        [ValidateNotNullOrEmpty()]
        [string]$NameSpace,
        [Parameter(Mandatory = $true,
            HelpMessage = 'The name of the Service Bus Namespace Topic')]
        [ValidateNotNullOrEmpty()]
        [string]$TopicName,
        [Parameter(Mandatory = $true,
            HelpMessage = 'The name of the Service Bus Topic Subscription')]
        [ValidateNotNullOrEmpty()]
        [string]$SubscriptionName,
        [Parameter(HelpMessage = 'How many messages should we receive / delete? Understand this as a batch size.')]
        [int]$BatchSize=1
    )

    $token = Get-SbApiToken
    $headers = @{
        'Authorization' = 'Bearer ' + $token
    }

    $stopWatch = [system.diagnostics.stopwatch]::startNew()

    $Scriptblock = {
        param($NameSpace, $TopicName, $SubscriptionName, $headers)
        Invoke-RestMethod -Uri "https://$($NameSpace).servicebus.windows.net//$($TopicName)/subscriptions/$($SubscriptionName)/messages/head?api-version=2015-01" -Method Delete -Headers $headers
    }

    $MaxThreads = 5
    $RunspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxThreads)
    $RunspacePool.Open()
    $Jobs = @()

    Write-Verbose "Calling the Azure Service Bus API endpoint for Service Bus Namespace $($NameSpace), Topic $($TopicName) and Subscription $($SubscriptionName)."

    1..$BatchSize | ForEach-Object {
        $PowerShell = [powershell]::Create().AddScript($ScriptBlock).AddParameter('NameSpace', $NameSpace).AddParameter('TopicName', $TopicName).AddParameter('SubscriptionName', $SubscriptionName).AddParameter('headers', $headers)
        $PowerShell.RunspacePool = $RunspacePool
        $Jobs += $PowerShell.BeginInvoke()
    }

    while ($Jobs.IsCompleted -contains $false) {
        Start-Sleep 1
    }

    $stopWatch.Stop()
    return $stopWatch.Elapsed

} #Receive-SbMessage



<#
.EXTERNALHELP AzureServiceBusManagement-help.xml
#>

function Send-SbTestMessage {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true,
            HelpMessage = 'The name of the Service Bus Namespace')]
        [ValidateNotNullOrEmpty()]
        [string]$NameSpace,
        [Parameter(Mandatory = $true,
            HelpMessage = 'The name of the Service Bus Namespace Topic')]
        [ValidateNotNullOrEmpty()]
        [string]$TopicName,
        [Parameter(HelpMessage = 'Message that should be put onto the Service Bus Topic.')]
        [ValidateNotNullOrEmpty()]
        [string]$message,
        [Parameter(HelpMessage = 'How many messages should we send? Understand this as a batch size.')]
        [int]$BatchSize = 1
    )

    $token = Get-SbApiToken
    $headers = @{
        'Authorization'    = 'Bearer ' + $token
        'Content-Type'     = 'application/atom+xml;type=entry;charset=utf-8'
        'BrokerProperties' = '{"Label":"M1","State":"Active","TimeToLive":10}'
    }

    $stopWatch = [system.diagnostics.stopwatch]::startNew()

    $Scriptblock = {
        param($NameSpace, $TopicName, $message, $headers)
        Invoke-RestMethod -Uri "https://$($NameSpace).servicebus.windows.net//$($TopicName)/messages/?api-version=2015-01" -Body $message -Method Post -Headers $headers
    }

    $MaxThreads = 10
    $RunspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxThreads)
    $RunspacePool.Open()
    $Jobs = @()

    Write-Verbose "Calling the Azure Service Bus API endpoint for Service Bus Namespace $($NameSpace), Topic $($TopicName) and sending the following $($message)."

    1..$BatchSize | ForEach-Object {
        $PowerShell = [powershell]::Create().AddScript($ScriptBlock).AddParameter('NameSpace', $NameSpace).AddParameter('TopicName', $TopicName).AddParameter('message', $message).AddParameter('headers', $headers)
        $PowerShell.RunspacePool = $RunspacePool
        $Jobs += $PowerShell.BeginInvoke()
    }

    while ($Jobs.IsCompleted -contains $false) {
        Start-Sleep 1
    }

    $stopWatch.Stop()
    return $stopWatch.Elapsed

}