Geeks With Blogs

News
CloudCasts Blog Webcasts in the Cloud
When creating applications that use AppFabric messaging it makes sense to have a separate application or console to manage the messaging artifacts rather than creating them in the applications that send and receive messages. At the time of writing there is no such functionality in the AppFabric management portal so it is helpful to have this functionality in an on-premise application.
This section will take a walk through the creation of a simple console application to manage queues in an AppFabric service bus namespace. This application is a help when creating basic messaging applications but it does not provide support for setting properties on queues, or managing topics and subscriptions. The Service Bus Explorer application is a ready built Windows application developed by the AppFabric Customer Advisory Team (CAT) that provides full support managing queues, topics and subscriptions. The use of this tool is described in the next section.
Creating the Solution
The solution is created as a C# console application named SimpleQueueManagementConsole. The target framework of the project is changed from .NET Framework 4 Client Profile to .NET Framework 4 and references to the following assemblies added.
·         Microsoft.ServiceBus
·         System.Configuration
·         System.Runtime.Serialization
Adding Configuration Settings
The management console must connect to a service bus namespace using a set of credentials. To prompting the user for credentials they will be placed in the app.config file.

 

<?xmlversion="1.0"?>
<configuration>
 <startup>
    <supportedRuntimeversion="v4.0"sku=".NETFramework,Version=v4.0"/>
 </startup>
 
 <appSettings>
    <addkey="NameSpace"value="(enter value)"/>
    <addkey="CredentialName"value="(enter value)"/>
    <addkey="CredentialKey"value="(enter value)"/>
  </appSettings>
 
</configuration>
 
You will have to set the appropriate values for your AppFabirc service bus account. Be aware that storing these credentials in a configuration file is a potential security risk.
Adding a ManagementHelper Class
The next step is to add a helper class named ManagementHelper that will initialize a ServiceBusNamespaceClient member variable with the appropriate settings in the constructor.

 

 
namespace SimpleQueueManagementConsole
{
    class ManagementHelper
    {
        private NamespaceManager m_NamespaceManager;
 
        public ManagementHelper()
        {
            // Retrieve the account details from the configuration file.
            string nameSpace = ConfigurationManager.AppSettings["NameSpace"];
            string credentialName = ConfigurationManager.AppSettings["CredentialName"];
            string credentialKey = ConfigurationManager.AppSettings["CredentialKey"];
 
 
            // Create a token provider with the relevant credentials.
            TokenProvider credentials =
                TokenProvider.CreateSharedSecretTokenProvider
                (credentialName, credentialKey);
 
 
            // create a Uri for the service bus using the specified namespace
            Uri sbUri = ServiceBusEnvironment.CreateServiceUri
                ("sb", nameSpace, string.Empty);
 
            // Create a ServiceBusNamespaceClient for the specified namespace
            // using the specified credentials.
            m_NamespaceManager = new NamespaceManager (sbUri, credentials);
 
            // Set the timeout to 15 seconds.
            m_NamespaceManager.Settings.OperationTimeout = TimeSpan.FromSeconds(15);
 
            // Output the client address.
            Console.WriteLine("Service bus address {0}", m_NamespaceManager.Address);
        }
 
 
Once this is done methods can be added to create, delete, get and list queues.

 

 
public void CreateQueue(string queuePath)
{
    Console.Write("Creating queue {0}...", queuePath);
    m_NamespaceManager.CreateQueue(queuePath);           
    Console.WriteLine("Done!");
}
 
public void DeleteQueue(string queuePath)
{
    Console.Write("Deleting queue {0}...", queuePath);
    m_NamespaceManager.DeleteQueue(queuePath);
    Console.WriteLine("Done!");
}
 
public void GetQueue(string queuePath)
{
    QueueDescription queueDescription = m_NamespaceManager.GetQueue(queuePath);
           
    Console.WriteLine("Queue Path:                                   {0}",
        queueDescription.Path);
    Console.WriteLine("Queue MessageCount:                           {0}",
        queueDescription.MessageCount);
    Console.WriteLine("Queue SizeInBytes:                            {0}",
        queueDescription.SizeInBytes);
    Console.WriteLine("Queue RequiresSession:                        {0}",
        queueDescription.RequiresSession);
    Console.WriteLine("Queue RequiresDuplicateDetection:             {0}",
        queueDescription.RequiresDuplicateDetection);
    Console.WriteLine("Queue DuplicateDetectionHistoryTimeWindow:    {0}",
        queueDescription.DuplicateDetectionHistoryTimeWindow);
    Console.WriteLine("Queue LockDuration:                           {0}",
        queueDescription.LockDuration);
    Console.WriteLine("Queue DefaultMessageTimeToLive:               {0}",
        queueDescription.DefaultMessageTimeToLive);
    Console.WriteLine("Queue EnableDeadLetteringOnMessageExpiration: {0}",
        queueDescription.EnableDeadLetteringOnMessageExpiration);
    Console.WriteLine("Queue EnableBatchedOperations:                {0}",
        queueDescription.EnableBatchedOperations);
    Console.WriteLine("Queue MaxSizeInMegabytes:                     {0}",
        queueDescription.MaxSizeInMegabytes);
    Console.WriteLine("Queue MaxDeliveryCount:                       {0}",
        queueDescription.MaxDeliveryCount);
    Console.WriteLine("Queue IsReadOnly:                             {0}",
        queueDescription.IsReadOnly);
}
 
public void ListQueues()
{
    IEnumerable<QueueDescription> queueDescriptions = m_NamespaceManager.GetQueues();
    Console.WriteLine("Lisitng queues...");
    foreach (QueueDescription queueDescription in queueDescriptions)
    {
        Console.WriteLine("\t{0}", queueDescription.Path);
    }
    Console.WriteLine("Done!");
}
 
 
Processing the Commands
The console application will process the commands that the user enters and call the appropriate methods on the helper class. The following code in the Main method will implement this.

 

 
static void Main(string[] args)
{
    ManagementHelper helper = new ManagementHelper();
 
    bool done = false;
    do
    {
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.Write(">");
        string commandLine = Console.ReadLine();
        Console.ForegroundColor = ConsoleColor.Magenta;
        string[] commands = commandLine.Split(' ');
 
        try
        {
            if (commands.Length > 0)
            {
                switch (commands[0])
                {
                    case "createqueue":
                    case "cq":
                        if (commands.Length > 1)
                        {
                            helper.CreateQueue(commands[1]);
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("Queue path not specified.");
                        }
                        break;
                    case "listqueues":
                    case "lq":
                        helper.ListQueues();
                        break;
                    case "getqueue":
                    case "gq":
                        if (commands.Length > 1)
                        {
                            helper.GetQueue(commands[1]);
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("Queue path not specified.");
                        }
                        break;
                    case "deletequeue":
                    case "dq":
                        if (commands.Length > 1)
                        {
                            helper.DeleteQueue(commands[1]);
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("Queue path not specified.");
                        }
                        break;
                    case "exit":
                        done = true;
                        break;
                    default:
                        break;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex.Message);
        }
 
    } while (!done);
 
}
 
 
Testing the Console
The queue management console can now be tested.
Code Listings
The complete listings for the two classes are provided below.
app.config

 

 
<?xmlversion="1.0"?>
<configuration>
 <startup>
    <supportedRuntimeversion="v4.0"sku=".NETFramework,Version=v4.0"/>
 </startup>
 
 <appSettings>
    <addkey="NameSpace"value=""/>
    <addkey="CredentialName"value=""/>
    <addkey="CredentialKey"value=""/>
 </appSettings>
 
</configuration>
 
 
 
ManagementHelper.cs

 

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
 
namespace SimpleQueueManagementConsole
{
    class ManagementHelper
    {
        private NamespaceManager m_NamespaceManager;
 
        public ManagementHelper()
        {
            // Retrieve the account details from the configuration file.
            string nameSpace = ConfigurationManager.AppSettings["NameSpace"];
            string credentialName = ConfigurationManager.AppSettings["CredentialName"];
            string credentialKey = ConfigurationManager.AppSettings["CredentialKey"];
 
 
            // Create a token provider with the relevant credentials.
            TokenProvider credentials =
                TokenProvider.CreateSharedSecretTokenProvider
                (credentialName, credentialKey);
 
 
            // create a Uri for the service bus using the specified namespace
            Uri sbUri = ServiceBusEnvironment.CreateServiceUri
                ("sb", nameSpace, string.Empty);
 
            // Create a ServiceBusNamespaceClient for the specified namespace
            // using the specified credentials.
            m_NamespaceManager = new NamespaceManager(sbUri, credentials);
 
            // Set the timeout to 15 seconds.
            m_NamespaceManager.Settings.OperationTimeout = TimeSpan.FromSeconds(15);
 
            // Output the client address.
            Console.WriteLine("Service bus address {0}", m_NamespaceManager.Address);
        }
 
 
 
        public void CreateQueue(string queuePath)
        {
            Console.Write("Creating queue {0}...", queuePath);
            m_NamespaceManager.CreateQueue(queuePath);
            Console.WriteLine("Done!");
        }
 
        public void DeleteQueue(string queuePath)
        {
            Console.Write("Deleting queue {0}...", queuePath);
            m_NamespaceManager.DeleteQueue(queuePath);
            Console.WriteLine("Done!");
        }
 
        public void GetQueue(string queuePath)
        {
            QueueDescription queueDescription = m_NamespaceManager.GetQueue(queuePath);
 
            Console.WriteLine("Queue Path:                                   {0}",
                queueDescription.Path);
            Console.WriteLine("Queue MessageCount:                           {0}",
                queueDescription.MessageCount);
            Console.WriteLine("Queue SizeInBytes:                            {0}",
                queueDescription.SizeInBytes);
            Console.WriteLine("Queue RequiresSession:                        {0}",
                queueDescription.RequiresSession);
            Console.WriteLine("Queue RequiresDuplicateDetection:             {0}",
                queueDescription.RequiresDuplicateDetection);
            Console.WriteLine("Queue DuplicateDetectionHistoryTimeWindow:    {0}",
                queueDescription.DuplicateDetectionHistoryTimeWindow);
            Console.WriteLine("Queue LockDuration:                           {0}",
                queueDescription.LockDuration);
            Console.WriteLine("Queue DefaultMessageTimeToLive:               {0}",
                queueDescription.DefaultMessageTimeToLive);
            Console.WriteLine("Queue EnableDeadLetteringOnMessageExpiration: {0}",
                queueDescription.EnableDeadLetteringOnMessageExpiration);
            Console.WriteLine("Queue EnableBatchedOperations:                {0}",
                queueDescription.EnableBatchedOperations);
            Console.WriteLine("Queue MaxSizeInMegabytes:                     {0}",
                queueDescription.MaxSizeInMegabytes);
            Console.WriteLine("Queue MaxDeliveryCount:                       {0}",
                queueDescription.MaxDeliveryCount);
            Console.WriteLine("Queue IsReadOnly:                             {0}",
                queueDescription.IsReadOnly);
        }
 
        public void ListQueues()
        {
            IEnumerable<QueueDescription> queueDescriptions = m_NamespaceManager.GetQueues();
            Console.WriteLine("Lisitng queues...");
            foreach (QueueDescription queueDescription in queueDescriptions)
            {
                Console.WriteLine("\t{0}", queueDescription.Path);
            }
            Console.WriteLine("Done!");
        }
 
 
 
 
    }
 
}
 
 
 
Program.cs

 

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SimpleQueueManagementConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            ManagementHelper helper = new ManagementHelper();
 
            bool done = false;
            do
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write(">");
                string commandLine = Console.ReadLine();
                Console.ForegroundColor = ConsoleColor.Magenta;
                string[] commands = commandLine.Split(' ');
 
                try
                {
                    if (commands.Length > 0)
                    {
                        switch (commands[0])
                        {
                            case "createqueue":
                            case "cq":
                                if (commands.Length > 1)
                                {
                                    helper.CreateQueue(commands[1]);
                                }
                                else
                                {
                                    Console.ForegroundColor = ConsoleColor.Yellow;
                                    Console.WriteLine("Queue path not specified.");
                                }
                                break;
                            case "listqueues":
                            case "lq":
                                helper.ListQueues();
                                break;
                            case "getqueue":
                            case "gq":
                                if (commands.Length > 1)
                                {
                                    helper.GetQueue(commands[1]);
                                }
                                else
                                {
                                    Console.ForegroundColor = ConsoleColor.Yellow;
                                    Console.WriteLine("Queue path not specified.");
                                }
                                break;
                            case "deletequeue":
                            case "dq":
                                if (commands.Length > 1)
                                {
                                    helper.DeleteQueue(commands[1]);
                                }
                                else
                                {
                                    Console.ForegroundColor = ConsoleColor.Yellow;
                                    Console.WriteLine("Queue path not specified.");
                                }
                                break;
                            case "exit":
                                done = true;
                                break;
                            default:
                                break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex.Message);
                }
 
            } while (!done);
 
        }
    }
}
 
 
 
 
Posted on Monday, September 19, 2011 9:44 AM | Back to top


Comments on this post: AppFabric Walkthrough: Creating a Simple Queue Management Tool

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Alan Smith | Powered by: GeeksWithBlogs.net