# PowerShell: Automate Windows Azure Service Bus queue creation

One of the core services provided by the Windows Azure “cloud computing” platform is the ability to create first-in, first-out messaging queues. These queues are considered to be part of the Service Bus feature in Windows Azure. In some cases, it may be desirable to automate the creation of these queues, especially if there are a lot of them to create. By automating this process, rather than performing it manually, you can ensure consistency, repeatability, and speed.

Starting out with Windows Azure automation might lead you to download the official Microsoft Windows Azure cmdlets, or even the third-party Cerebrata Windows Azure module for Windows PowerShell. The latter module appears to have cmdlets that support queue creation, however the former (Microsoft) module does not. If you’d rather not spend the money on the Cerebrata module, can’t get your company to buy it for you, or you’d rather just stick to native Microsoft stuff, you’re still in luck. The Windows Azure .NET SDK 1.6 allows C# developers, and PowerShell script writers, to create queues using the provided .NET types!

In the interest of making Azure Service Bus Queue creation easier, I’ve written a PowerShell v2 advanced function / cmdlet, which allows you to specify all of the parameters related to Service Bus Queues. I wanted to keep the function somewhat generic, so I did not have it directly read from any configuration files. For my purposes though, I’m writing some code around this function, which will allow me to create Service Bus Queues by defining them in a XML configuration file, and then have the script automatically create them. Since that part is a bit less generic, I won’t be sharing it in this post, but might write about it separately later on.

[cc lang=”powershell”]
<# .Synopsis Creates a new Windows Azure Service Bus Queue .Description The New-AzureServiceBusQueue cmdlet creates a new Windows Azure Service Bus Queue with the specified parameters. .Parameter Certificate The Certificate parameter is a required parameter that allows you to specify the Windows Azure management certificate that will be used to manage the specified Azure subscription ID. .Parameter SubscriptionId The SubscriptionId parameter is a required parameter that allows you to specify the Windows Azure subscription ID that you would like to manage. .Parameter Namespace The Namespace parameter is a required parameter that allows you to specify the Windows Azure Service Namespace in which you would like to create a new Service Bus queue. .Parameter DefaultIssuer The DefaultIssuer parameter is a required parameter that allows you to specify the name of the Default Issuer, which is used to create an authentication token. .Parameter DefaultKey The DefaultKey parameter is a required parameter that allows you to specify the Default Key, which is used in conjunction with the Default Issuer to create an authentication token. .Parameter DefaultMessageTimeToLive The DefaultMessageTimeToLive parameter allows you to specify a message TTL for the Windows Azure Service Bus queue. .Parameter DuplicateDetectionHistoryTimeWindow The DuplicateDetectionHistoryTimeWindow parameter allows you to specify the period (in minutes) that the queue looks for duplicate messages. .Parameter EnableBatchedOperations The EnableBatchedOperations parameter allows to specify whether or not server-side batched operations will be enabled for the queue. .Parameter DeadLettering The DeadLettering parameter allows you to specify whether or not DeadLettering is enabled for the queue. #>
function New-AzureServiceBusQueue {
[CmdletBinding()]
param (
# Windows Azure related parameters
[Parameter(Mandatory = $true)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
, [Parameter(Mandatory = $true)] [string]$SubscriptionId
, [Parameter(Mandatory = $true)] [string]$Namespace

# Windows Azure Service Bus parameters
# (used in addition to SubscriptionId and Certificate)
, [Parameter(Mandatory = $true)] [string]$DefaultIssuer
, [Parameter(Mandatory = $true)] [string]$DefaultKey

# Windows Azure Service Bus Queue related parameters
, [ValidatePattern(‘[a-zA-Z0-9\._]+’)]
[Parameter(Mandatory = $true)] [string]$Name
, [int]
$DefaultMessageTimeToLive = 922337203685 , [int]$DuplicateDetectionHistoryTimeWindow = 10
, [Boolean]
$EnableBatchedOperations =$true
, [Boolean]
$DeadLettering =$true
, [ValidateRange(0, 300)]
[int] $LockDuration , [int]$MaxSizeInMegabytes = 1024
, [int]
$MaxDeliveryCount = 10 , [Boolean]$RequiresDuplicateDetection = $false , [Boolean]$RequiresSession = $false ) # Load the Windows Azure Service Bus assembly #$FunctionPath = Split-Path -Parent -Path (Get-Variable -Name MyInvocation -Scope 1).Value.MyCommand.Definition;
# . “$FunctionPath\Test-AzureSDK.ps1”; Load-AzureServiceBusAssembly; # Convert integer parameters to TimeSpan objects where appropriate [TimeSpan]$LockDurationTimeSpan = [TimeSpan]::FromSeconds($LockDuration); [TimeSpan]$DefaultMessageTimeToLiveTimeSpan = [TimeSpan]::FromSeconds($DefaultMessageTimeToLive); [TimeSpan]$DuplicateDetectionHistoryTimeWindowTimeSpan = [TimeSpan]::FromMinutes($DuplicateDetectionHistoryTimeWindow); # Create the TokenProvider, Uri, and NamespaceManager objects$TokenProvider = [Microsoft.ServiceBus.TokenProvider]::CreateSharedSecretTokenProvider($DefaultIssuer,$DefaultKey);
$ServiceUri = [Microsoft.ServiceBus.ServiceBusEnvironment]::CreateServiceUri(‘sb’,$Namespace, [String]::Empty);
$NamespaceManager = New-Object -TypeName Microsoft.ServiceBus.NamespaceManager -ArgumentList$ServiceUri, $TokenProvider; # Create the new queue and define all properties$QueueDescription = New-Object -TypeName Microsoft.ServiceBus.Messaging.QueueDescription -ArgumentList $Name;$QueueDescription.DefaultMessageTimeToLive = $DefaultMessageTimeToLiveTimeSpan;$QueueDescription.DuplicateDetectionHistoryTimeWindow = $DuplicateDetectionHistoryTimeWindowTimeSpan;$QueueDescription.EnableBatchedOperations = $EnableBatchedOperations;$QueueDescription.EnableDeadLetteringOnMessageExpiration = $DeadLettering;$QueueDescription.LockDuration = $LockDurationTimeSpan;$QueueDescription.MaxDeliveryCount = $MaxDeliveryCount;$QueueDescription.MaxSizeInMegabytes = $MaxSizeInMegabytes;$QueueDescription.RequiresDuplicateDetection = $RequiresDuplicateDetection;$QueueDescription.RequiresSession = $RequiresSession; # Create the queue from the in-memory QueueDescription object try {$NamespaceManager.CreateQueue($QueueDescription); } # Catch exception if the entity already exists. catch [Microsoft.ServiceBus.Messaging.MessagingEntityAlreadyExistsException] { Write-Warning -Message (‘The queue {0} already exists in namespace {1}’ -f$Name, $Namespace ); } } [/cc] This function also depends on a separate script file that I created, which helps to ensure that the Windows Azure SDK 1.6 is installed, and that the Azure Service Bus .NET assembly is loaded into the current .NET AppDomain. Although I originally developed this as part of a PowerShell module, to use these functions together, you can simply put them all in the same script file. [cc lang=”powershell”] <# .Synopsis This function simply checks to ensure that the Microsoft Windows Azure SDK version 1.6 is installed on the local system. #> function Test-AzureSdk { [CmdletBinding()] param ( ) # Get the registry path that represents the Windows Azure .NET Libraries version 1.6.$SDKReg = Get-Item -Path ‘HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\{6E390D29-6990-4819-9629-CBF1AA964422}’;

if (!$SDKReg) { throw (‘Please ensure that the Windows Azure .NET SDK 1.6 is installed! Could not locate {0} in path {1}.’ -f$ServiceBusAssemblyName, $ServiceBusAssemblyPath); } else { Write-Output -InputObject$SDKReg;
}
}

<# .Synopsis This function loads the Microsoft.ServiceBus.dll from the Windows Azure .NET SDK v1.6. #>
[CmdletBinding()]
param (
)

# Ensure that the Windows Azure .NET SDK 1.6 is installed.
if (Test-AzureSdk)
{
# Load the Windows Azure ServiceBus assembly
$AzureSdkPath = ‘C:\Program Files\Windows Azure SDK\v1.6\ServiceBus\ref\’;$ServiceBusAssemblyName = ‘Microsoft.ServiceBus.dll’;
$ServiceBusAssemblyPathList = @($AzureSdkPath + $ServiceBusAssemblyName ); foreach ($AssemblyPath in $ServiceBusAssemblyPathList) { if (Test-Path -Path$AssemblyPath) {
Write-Debug -Message (‘Loaded assembly {0}’ -f $AssemblyPath); [Void] [Reflection.Assembly]::LoadFile($AssemblyPath);
}
}
}
}

function Test-AzureModule {
$AzureModule = Get-Module -Name WAPPSCmdlets; if (!$AzureModule) {
$ExceptionMessage = @” Azure module is not loaded. Please follow these steps: 1. Install the Windows Azure PowerShell Module from http://wappowershell.codeplex.com 2. Set the Windows PowerShell execution policy to unrestricted (Set-ExecutionPolicy -ExecutionPolicy Unrestricted) “@ throw$ExceptionMessage;
}
}[/cc]

In order to use the New-AzureServiceBusQueue function, see the following example. You will need:

• Windows Azure management certificate thumbprint (imported into current user’s certificate store)
• Your Windows Azure subscription ID
• Name of the Windows Azure Service Namespace you want to create the queue in
• Windows Azure Service Namespace Default Issuer (get this from the Azure management interface)
• Windows Azure Service Namespace Default Key (get this from the Azure management interface)
• Name of the Service Bus queue you want to create

[cc lang=”powershell”]
#################################
# Change these variable values
#################################
# Your Windows Azure management certificate thumbprint
$AzureCertThumbprint = ‘2F2D399F0EA8844859FE5514B304733B’; # Your Windows Azure subscription ID$SubscriptionId = ‘0d599f0ec05c3bda8c3b8a68c32a1b47’;
# The service namespace you want to create the queue in
$ServiceNamespace = ‘testnamespace’; # The Default Issuer & Default Key of the service namespace$DefaultIssuer = ‘owner’;
$DefaultKey = ‘e6798d8f97ce05c8f3457677e7cda411’; # The name of the queue you want to create$QueueName = ‘powershelltest’;

#################################

# Get a reference to the Windows Azure management certificate
$AzureCert = Get-Item -Path cert:\CurrentUser\My\$AzureCertThumbprint;

# Create the new Windows Azure Service Bus queue
New-AzureServiceBusQueue 
-Name $QueueName  -SubscriptionId$SubscriptionId 
-Certificate $AzureCert  -Namespace$ServiceNamespace 
-DefaultIssuer $DefaultIssuer  -DefaultKey$DefaultKey;
[/cc]

## Conclusion

In this article, we have discussed creation of Windows Azure Service Bus queues using Windows PowerShell automation.