Введение в облачные решения Microsoft

Работа с Windows AzureQueue

Разбить на страницы
Показывать лекцию целиком

Создайте проект облачной службы и добавьте веб - роль и рабочую роль в решение.

В свойствах ролей определим строку подключения к эмулятору хранилища Azure .

(рис 22.1)

Задание 1

Отправка сообщения в очередь

Создадим веб - форму AzureQueueSample со элементами управления - текстовое поле и кнопка:

(рис 22.2)

asp - код веб формы:

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="AzureQueueSample.aspx.cs" Inherits="WebRole1.AzureQueueSample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 197px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="X-Large" 
            Text="Windows Azure Queue Example"></asp:Label>
        <br />
        <br />
        <table style="width:100%;">
            <tr>
                <td class="style1">
                    <asp:TextBox ID="tb_message" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Button ID="btn_send" runat="server" onclick="btn_send_Click" 
                        Text="Отправить" />
                </td>
            </tr>
            </table>
        <br />
    
    </div>
    </form>
</body>
</html>

Добавим следующие ссылки в AzureQueueSample.aspx.cs :

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;

Создадим метод, обрабатывающие событие нажатия на кнопку btn_send :

protected void btn_send_Click(object sender, EventArgs e)
        {
//определяем параметры учетной записи и клиента для создания очереди и сообщения
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            var queueClient = storageAccount.CreateCloudQueueClient();
            var queue = queueClient.GetQueueReference("messagequeue");
//создаем очередь
            queue.CreateIfNotExist();
//создаем сообщение, источник - текстовое поле tb_message
            var msg = new CloudQueueMessage(tb_message.Text);
//добавляем сообщение в очередь
            queue.AddMessage(msg);
            tb_message.Text = string.Empty;
        }

На этом работа с формой закончена.

Извлечение сообщения из очереди

Перейдите с помощью обозревателя решений к файлу Global.asax.cs и добать следующий код в метод ApplicationStart :

void Application_Start(object sender, EventArgs e)
        {
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
            });

        }

Затем перейдите к файлу WorkerRole.cs нашей рабочей роли. Добавьте следующие ссылки:

using System.Diagnostics;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient

Измените метод OnStart в соответствие со следующим кодом:

public override bool OnStart()
        {
            ServicePointManager.DefaultConnectionLimit = 12;

            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                {
                      configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                });

        return base.OnStart();


        }

Затем приведите метод Run в соответствие с:

public override void Run()
        {

            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            // получение ссылок на сообщения очереди
            var queueClient = storageAccount.CreateCloudQueueClient();
            var queue = queueClient.GetQueueReference("messagequeue");

            // получение сообщение и передача его в лог эмулятора Compute Emulator
            while (true)
            {
                Thread.Sleep(10000);
                if (queue.Exists())
                {
                    var msg = queue.GetMessage();
                    if (msg != null)
                    {
                        Trace.TraceInformation(string.Format("Сообщение '{0}' обработано.", msg.AsString));
                        queue.DeleteMessage(msg);
                    }
                }
            }
        }

Запустите приложение, заполните текстовое поле и нажмите кнопку "Отправить" :

(рис 22.3)

Затем, откройте интерфейс Compute Emulator :

(рис 22.4)

И откройте лог рабочей роли, чтобы убедиться в работоспособности приложения:

(рис 22.5)

Задание 2

Для следующего задания можно "усовершенствовать" предыдущую веб - форму, но мы предпочли создать новую - AzureQueueSample2.aspx :

(рис 22.6)

asp - код веб формы для второго задания:

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="AzureQueueSample2.aspx.cs" Inherits="WebRole1.AzureQueueSample2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 268px;
        }
        .style2
        {
            width: 247px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label4" runat="server" Font-Bold="True" Font-Size="X-Large" 
                Text="Windows Azure Queue - Second Example"></asp:Label>
            <br />
            <table style="width:100%;">
                <tr>
                    <td class="style1">
            <asp:Label id="lb_inert" Text="Добавить в очередь сообщение:" runat="server" />
                    </td>
                    <td class="style2">
            <asp:TextBox id="tb_insert" runat="server" />
                    </td>
                    <td>
            <asp:Button ID="bnt_addmessage" Text="Добавить сообщение" runat="server" 
                            onclick="bnt_addmessage_Click" Width="231px" />
                    </td>
                </tr>
                <tr>
                    <td class="style1">
            <asp:Label id="lb_binarydata" Text="Добавить, как двойчный объект:" runat="server" />
                    </td>
                    <td class="style2">
            <asp:FileUpload ID="fu_insertbinary" runat="server" />
                    </td>
                    <td>
            <asp:Button ID="btn_addbinary" Text="Добавить двоичные данные" runat="server" 
                            onclick="btn_addbinary_Click" />
                    </td>
                </tr>
                <tr>
                    <td class="style1">
            <asp:Button ID="btn_getmessage" Text="Получить сообщение" runat="server" 
                            onclick="btn_getmessage_Click" />
                    </td>
                    <td class="style2">
            <asp:Label id="lb_retrievedmessage" runat="server" />
                    </td>
                    <td>
                         </td>
                </tr>
            </table>
            <br />
            <asp:Repeater id="Repeater1" runat="server">
                <HeaderTemplate>
                    <table border="1">
                        <tr><td><b>Queue Messages</b></td></tr>
                </HeaderTemplate>
                <ItemTemplate>
                    <tr>
                      <td> <asp:Label ID="Label1" runat="server" 
                      Text="<%# Container.DataItem %>" /> </td>
                    </tr>
                </ItemTemplate>
                <FooterTemplate>
                    </table>
                </FooterTemplate>
            </asp:Repeater>
        </div>
    </form>

</body>
</html>

Наша задача состоит в следующем:

  • Реализовать функционал создания очереди
  • Добавить сообщение в очередь
  • Добавить в очередь файл, в виде двойного объекта
  • Отобразить сообщения очереди
  • Получить сообщение из очереди
  • Добавьте следующие ссылки в AzureQueueSample2.aspx.cs :

    using System.IO;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;
    using Microsoft.WindowsAzure.ServiceRuntime;

    Также определим переменные учетной записи, очереди и клиента до метода PageLoad :

    CloudStorageAccount storageAccount = null;
    CloudQueue cloudQueue = null;
    CloudQueueClient queueClient = null;

    Для выполнения первого пункта, добавим следующий код в метод PageLoad :

    // определение контекста
                this.storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                this.queueClient = storageAccount.CreateCloudQueueClient();
    
                // создание очереди
                this.cloudQueue = this.queueClient.GetQueueReference("myqueue");
                this.cloudQueue.CreateIfNotExist();
    
                this.DisplayMesssages();

    Для добавления сообщения в очередь, создадим метод, обрабатывающий событие нажатия кнопки btn_addmessage :

    protected void bnt_addmessage_Click(object sender, EventArgs e)
            {
                CloudQueueMessage msg = new CloudQueueMessage(this.tb_insert.Text);
                this.cloudQueue.AddMessage(msg);
    
                this.DisplayMesssages();
            }

    Для отображения содержимого очереди, создадим метод DisplayMessages :

    private void DisplayMesssages()
            {
                // получение первых пяти сообщений, без удаления их из очереди
                var msgs = this.cloudQueue.PeekMessages(5);
                var cloudList = new List<string>();
    
                foreach (var msg in msgs)
                {
                    cloudList.Add("Message ID: " + msg.Id + "; Message: " + msg.AsString + 
                    "; Message insertion time: " + msg.InsertionTime);
                }
    
                // привязка к источнику данных
                this.Repeater1.DataSource = cloudList;
                this.Repeater1.DataBind();
            }

    Для добавления очередь файла, создадим метод обрабатывающий нажатие кнопки btn_addbinary:

    protected void btn_addbinary_Click(object sender, EventArgs e)
            {
                // файл не должен превышать размер - лимит сообщения - 8Кб
    CloudQueueMessage msg = new CloudQueueMessage(File.ReadAllBytes(fu_insertbinary.FileName));
                this.cloudQueue.AddMessage(msg);
    
                this.DisplayMesssages();
            }

    Осталось только написать метод, для получения сообщения из очереди, обратите внимание, что при этом сообщение из очереди удаляется, а получить можно только первое сообщение из очереди (подробнее об очередях смотри лекции № 15- 16):

    protected void Page_Load(object sender, EventArgs e)
            {
                this.storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                this.queueClient = storageAccount.CreateCloudQueueClient();
                this.cloudQueue = this.queueClient.GetQueueReference("myqueue");
                this.cloudQueue.CreateIfNotExist();
                this.DisplayMesssages();
            }

    Теперь запустим приложение и протестируем функционал.

    (рис 22.7)

    Обратим ваше внимание на то, что файл, который можно добавить в очередь должен соответствовать следующим условиям:

  • размер файла не должен превышать 8Кб
  • файл должен находиться: [путь к проекту AzureQueueExample]\bin\Debug\CloudService1.csx\roles\WebRole1
  • В случае, если выполнение задания вызвало сложности и затруднения, в приложениях к данной практической работе вы найдете итоговый программный код в том виде, в котором он необходим для последнего задания.

    Список вспомогательных материалов

    Работа с Windows Azure Queue

  • http://msdn.microsoft.com/en-us/wazplatformtrainingcourse_exploringwindowsazurestoragevs2010_topic4
  • http://dotnetbyexample.blogspot.com/2009/07/storing-objects-as-compressed-messages.html
  • http://soumya.wordpress.com/2010/05/20/azure-simplified-part-4-using-azure-queue-storage/
  • http://www.dotnetconsult.co.uk/weblog2/PermaLink,guid,c24f8177-f6bf-479b-bd5c-d532e0e40272.aspx
  • Приложение А AzureQueueSample.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;
    using Microsoft.WindowsAzure.ServiceRuntime;
    
    
    namespace WebRole1
    {
        public partial class AzureQueueSample : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            protected void btn_send_Click(object sender, EventArgs e)
            {
                var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                var queueClient = storageAccount.CreateCloudQueueClient();
                var queue = queueClient.GetQueueReference("messagequeue");
                queue.CreateIfNotExist();
                var msg = new CloudQueueMessage(tb_message.Text);
                queue.AddMessage(msg);
                tb_message.Text = string.Empty;
            }
    
    
        }
    }

    Приложение Б Global.asax.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.SessionState;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.ServiceRuntime;
    
    namespace WebRole1
    {
        public class Global : System.Web.HttpApplication
        {
    
            void Application_Start(object sender, EventArgs e)
            {
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                {
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                });
    
            }
    
            void Application_End(object sender, EventArgs e)
            {
    
            }
    
            void Application_Error(object sender, EventArgs e)
            {
    
            }
    
            void Session_Start(object sender, EventArgs e)
            {
    
            }
    
            void Session_End(object sender, EventArgs e)
            {
    
            }
    
        }
    }

    Приложение В Worker.cs

    using System.Diagnostics;
    using System.Linq;
    using System.Net;
    using System.Threading;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Diagnostics;
    using Microsoft.WindowsAzure.ServiceRuntime;
    using Microsoft.WindowsAzure.StorageClient;
    
    
    namespace WorkerRole1
    {
        public class WorkerRole : RoleEntryPoint
        {
            public override void Run()
            {
    
                var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                var queueClient = storageAccount.CreateCloudQueueClient();
                var queue = queueClient.GetQueueReference("messagequeue");
                while (true)
                {
                    Thread.Sleep(10000);
                    if (queue.Exists())
                    {
                        var msg = queue.GetMessage();
                        if (msg != null)
                        {
                            Trace.TraceInformation(string.Format("Сообщение '{0}' обработано.", msg.AsString));
                            queue.DeleteMessage(msg);
                        }
                    }
                }
            }
            public override bool OnStart()
            {
                ServicePointManager.DefaultConnectionLimit = 12;
    
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                    {
                          configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                    });
    
            return base.OnStart();
    
            }
        }
    }

    Приложение Г AzureQueueSample2.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;
    using Microsoft.WindowsAzure.ServiceRuntime;
    
    namespace WebRole1
    {
        public partial class AzureQueueSample2 : System.Web.UI.Page
        {
    
            CloudStorageAccount storageAccount = null;
            CloudQueue cloudQueue = null;
            CloudQueueClient queueClient = null;
    
            protected void Page_Load(object sender, EventArgs e)
            {
                this.storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                this.queueClient = storageAccount.CreateCloudQueueClient();
                this.cloudQueue = this.queueClient.GetQueueReference("myqueue");
                this.cloudQueue.CreateIfNotExist();
                this.DisplayMesssages();
            }
    
    
            private void DisplayMesssages()
            {
                var msgs = this.cloudQueue.PeekMessages(5);
                var cloudList = new List<string>();
    
                foreach (var msg in msgs)
                {
                    cloudList.Add("Message ID: " + msg.Id + "; Message: " + msg.AsString + 
                     "; Message insertion time: " + msg.InsertionTime);
                }
    
                this.Repeater1.DataSource = cloudList;
                this.Repeater1.DataBind();
            }
    
            protected void bnt_addmessage_Click(object sender, EventArgs e)
            {
                CloudQueueMessage msg = new CloudQueueMessage(this.tb_insert.Text);
                this.cloudQueue.AddMessage(msg);
    
                this.DisplayMesssages();
            }
    
            protected void btn_addbinary_Click(object sender, EventArgs e)
            {
                CloudQueueMessage msg = new CloudQueueMessage(File.ReadAllBytes(fu_insertbinary.FileName));
                this.cloudQueue.AddMessage(msg);
    
                this.DisplayMesssages();
            }
    
            protected void btn_getmessage_Click(object sender, EventArgs e)
            {
    
                CloudQueueMessage msg = this.cloudQueue.GetMessage();
                this.lb_retrievedmessage.Text = "Retrieved message: " + msg.AsString;
                this.cloudQueue.DeleteMessage(msg);
    
                this.DisplayMesssages();
            }
    
        }
    }
    Страницы:

    Создайте проект облачной службы и добавьте веб - роль и рабочую роль в решение.

    В свойствах ролей определим строку подключения к эмулятору хранилища Azure .

    (рис 22.1)

    Задание 1

    Отправка сообщения в очередь

    Создадим веб - форму AzureQueueSample со элементами управления - текстовое поле и кнопка:

    (рис 22.2)

    asp - код веб формы:

    <%@ Page Language="C#" AutoEventWireup="true" 
    CodeBehind="AzureQueueSample.aspx.cs" Inherits="WebRole1.AzureQueueSample" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style type="text/css">
            .style1
            {
                width: 197px;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
            <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="X-Large" 
                Text="Windows Azure Queue Example"></asp:Label>
            <br />
            <br />
            <table style="width:100%;">
                <tr>
                    <td class="style1">
                        <asp:TextBox ID="tb_message" runat="server"></asp:TextBox>
                    </td>
                    <td>
                        <asp:Button ID="btn_send" runat="server" onclick="btn_send_Click" 
                            Text="Отправить" />
                    </td>
                </tr>
                </table>
            <br />
        
        </div>
        </form>
    </body>
    </html>

    Добавим следующие ссылки в AzureQueueSample.aspx.cs :

    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;
    using Microsoft.WindowsAzure.ServiceRuntime;

    Создадим метод, обрабатывающие событие нажатия на кнопку btn_send :

    protected void btn_send_Click(object sender, EventArgs e)
            {
    //определяем параметры учетной записи и клиента для создания очереди и сообщения
                var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                var queueClient = storageAccount.CreateCloudQueueClient();
                var queue = queueClient.GetQueueReference("messagequeue");
    //создаем очередь
                queue.CreateIfNotExist();
    //создаем сообщение, источник - текстовое поле tb_message
                var msg = new CloudQueueMessage(tb_message.Text);
    //добавляем сообщение в очередь
                queue.AddMessage(msg);
                tb_message.Text = string.Empty;
            }

    На этом работа с формой закончена.

    Извлечение сообщения из очереди

    Перейдите с помощью обозревателя решений к файлу Global.asax.cs и добать следующий код в метод ApplicationStart :

    void Application_Start(object sender, EventArgs e)
            {
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                {
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                });
    
            }

    Затем перейдите к файлу WorkerRole.cs нашей рабочей роли. Добавьте следующие ссылки:

    using System.Diagnostics;
    using System.Threading;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Diagnostics;
    using Microsoft.WindowsAzure.ServiceRuntime;
    using Microsoft.WindowsAzure.StorageClient

    Измените метод OnStart в соответствие со следующим кодом:

    public override bool OnStart()
            {
                ServicePointManager.DefaultConnectionLimit = 12;
    
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                    {
                          configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                    });
    
            return base.OnStart();
    
    
            }

    Затем приведите метод Run в соответствие с:

    public override void Run()
            {
    
                var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                // получение ссылок на сообщения очереди
                var queueClient = storageAccount.CreateCloudQueueClient();
                var queue = queueClient.GetQueueReference("messagequeue");
    
                // получение сообщение и передача его в лог эмулятора Compute Emulator
                while (true)
                {
                    Thread.Sleep(10000);
                    if (queue.Exists())
                    {
                        var msg = queue.GetMessage();
                        if (msg != null)
                        {
                            Trace.TraceInformation(string.Format("Сообщение '{0}' обработано.", msg.AsString));
                            queue.DeleteMessage(msg);
                        }
                    }
                }
            }

    Запустите приложение, заполните текстовое поле и нажмите кнопку "Отправить" :

    (рис 22.3)

    Затем, откройте интерфейс Compute Emulator :

    (рис 22.4)

    И откройте лог рабочей роли, чтобы убедиться в работоспособности приложения:

    (рис 22.5)

    Задание 2

    Для следующего задания можно "усовершенствовать" предыдущую веб - форму, но мы предпочли создать новую - AzureQueueSample2.aspx :

    (рис 22.6)

    asp - код веб формы для второго задания:

    <%@ Page Language="C#" AutoEventWireup="true" 
    CodeBehind="AzureQueueSample2.aspx.cs" Inherits="WebRole1.AzureQueueSample2" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style type="text/css">
            .style1
            {
                width: 268px;
            }
            .style2
            {
                width: 247px;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Label ID="Label4" runat="server" Font-Bold="True" Font-Size="X-Large" 
                    Text="Windows Azure Queue - Second Example"></asp:Label>
                <br />
                <table style="width:100%;">
                    <tr>
                        <td class="style1">
                <asp:Label id="lb_inert" Text="Добавить в очередь сообщение:" runat="server" />
                        </td>
                        <td class="style2">
                <asp:TextBox id="tb_insert" runat="server" />
                        </td>
                        <td>
                <asp:Button ID="bnt_addmessage" Text="Добавить сообщение" runat="server" 
                                onclick="bnt_addmessage_Click" Width="231px" />
                        </td>
                    </tr>
                    <tr>
                        <td class="style1">
                <asp:Label id="lb_binarydata" Text="Добавить, как двойчный объект:" runat="server" />
                        </td>
                        <td class="style2">
                <asp:FileUpload ID="fu_insertbinary" runat="server" />
                        </td>
                        <td>
                <asp:Button ID="btn_addbinary" Text="Добавить двоичные данные" runat="server" 
                                onclick="btn_addbinary_Click" />
                        </td>
                    </tr>
                    <tr>
                        <td class="style1">
                <asp:Button ID="btn_getmessage" Text="Получить сообщение" runat="server" 
                                onclick="btn_getmessage_Click" />
                        </td>
                        <td class="style2">
                <asp:Label id="lb_retrievedmessage" runat="server" />
                        </td>
                        <td>
                             </td>
                    </tr>
                </table>
                <br />
                <asp:Repeater id="Repeater1" runat="server">
                    <HeaderTemplate>
                        <table border="1">
                            <tr><td><b>Queue Messages</b></td></tr>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <tr>
                          <td> <asp:Label ID="Label1" runat="server" 
                          Text="<%# Container.DataItem %>" /> </td>
                        </tr>
                    </ItemTemplate>
                    <FooterTemplate>
                        </table>
                    </FooterTemplate>
                </asp:Repeater>
            </div>
        </form>
    
    </body>
    </html>

    Наша задача состоит в следующем:

  • Реализовать функционал создания очереди
  • Добавить сообщение в очередь
  • Добавить в очередь файл, в виде двойного объекта
  • Отобразить сообщения очереди
  • Получить сообщение из очереди
  • Добавьте следующие ссылки в AzureQueueSample2.aspx.cs :

    using System.IO;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;
    using Microsoft.WindowsAzure.ServiceRuntime;

    Также определим переменные учетной записи, очереди и клиента до метода PageLoad :

    CloudStorageAccount storageAccount = null;
    CloudQueue cloudQueue = null;
    CloudQueueClient queueClient = null;

    Для выполнения первого пункта, добавим следующий код в метод PageLoad :

    // определение контекста
                this.storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                this.queueClient = storageAccount.CreateCloudQueueClient();
    
                // создание очереди
                this.cloudQueue = this.queueClient.GetQueueReference("myqueue");
                this.cloudQueue.CreateIfNotExist();
    
                this.DisplayMesssages();

    Для добавления сообщения в очередь, создадим метод, обрабатывающий событие нажатия кнопки btn_addmessage :

    protected void bnt_addmessage_Click(object sender, EventArgs e)
            {
                CloudQueueMessage msg = new CloudQueueMessage(this.tb_insert.Text);
                this.cloudQueue.AddMessage(msg);
    
                this.DisplayMesssages();
            }

    Для отображения содержимого очереди, создадим метод DisplayMessages :

    private void DisplayMesssages()
            {
                // получение первых пяти сообщений, без удаления их из очереди
                var msgs = this.cloudQueue.PeekMessages(5);
                var cloudList = new List<string>();
    
                foreach (var msg in msgs)
                {
                    cloudList.Add("Message ID: " + msg.Id + "; Message: " + msg.AsString + 
                    "; Message insertion time: " + msg.InsertionTime);
                }
    
                // привязка к источнику данных
                this.Repeater1.DataSource = cloudList;
                this.Repeater1.DataBind();
            }

    Для добавления очередь файла, создадим метод обрабатывающий нажатие кнопки btn_addbinary:

    protected void btn_addbinary_Click(object sender, EventArgs e)
            {
                // файл не должен превышать размер - лимит сообщения - 8Кб
    CloudQueueMessage msg = new CloudQueueMessage(File.ReadAllBytes(fu_insertbinary.FileName));
                this.cloudQueue.AddMessage(msg);
    
                this.DisplayMesssages();
            }

    Осталось только написать метод, для получения сообщения из очереди, обратите внимание, что при этом сообщение из очереди удаляется, а получить можно только первое сообщение из очереди (подробнее об очередях смотри лекции № 15- 16):

    protected void Page_Load(object sender, EventArgs e)
            {
                this.storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                this.queueClient = storageAccount.CreateCloudQueueClient();
                this.cloudQueue = this.queueClient.GetQueueReference("myqueue");
                this.cloudQueue.CreateIfNotExist();
                this.DisplayMesssages();
            }

    Теперь запустим приложение и протестируем функционал.

    (рис 22.7)

    Обратим ваше внимание на то, что файл, который можно добавить в очередь должен соответствовать следующим условиям:

  • размер файла не должен превышать 8Кб
  • файл должен находиться: [путь к проекту AzureQueueExample]\bin\Debug\CloudService1.csx\roles\WebRole1
  • В случае, если выполнение задания вызвало сложности и затруднения, в приложениях к данной практической работе вы найдете итоговый программный код в том виде, в котором он необходим для последнего задания.

    Список вспомогательных материалов

    Работа с Windows Azure Queue

  • http://msdn.microsoft.com/en-us/wazplatformtrainingcourse_exploringwindowsazurestoragevs2010_topic4
  • http://dotnetbyexample.blogspot.com/2009/07/storing-objects-as-compressed-messages.html
  • http://soumya.wordpress.com/2010/05/20/azure-simplified-part-4-using-azure-queue-storage/
  • http://www.dotnetconsult.co.uk/weblog2/PermaLink,guid,c24f8177-f6bf-479b-bd5c-d532e0e40272.aspx
  • Приложение А AzureQueueSample.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;
    using Microsoft.WindowsAzure.ServiceRuntime;
    
    
    namespace WebRole1
    {
        public partial class AzureQueueSample : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            protected void btn_send_Click(object sender, EventArgs e)
            {
                var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                var queueClient = storageAccount.CreateCloudQueueClient();
                var queue = queueClient.GetQueueReference("messagequeue");
                queue.CreateIfNotExist();
                var msg = new CloudQueueMessage(tb_message.Text);
                queue.AddMessage(msg);
                tb_message.Text = string.Empty;
            }
    
    
        }
    }

    Приложение Б Global.asax.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.SessionState;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.ServiceRuntime;
    
    namespace WebRole1
    {
        public class Global : System.Web.HttpApplication
        {
    
            void Application_Start(object sender, EventArgs e)
            {
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                {
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                });
    
            }
    
            void Application_End(object sender, EventArgs e)
            {
    
            }
    
            void Application_Error(object sender, EventArgs e)
            {
    
            }
    
            void Session_Start(object sender, EventArgs e)
            {
    
            }
    
            void Session_End(object sender, EventArgs e)
            {
    
            }
    
        }
    }

    Приложение В Worker.cs

    using System.Diagnostics;
    using System.Linq;
    using System.Net;
    using System.Threading;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Diagnostics;
    using Microsoft.WindowsAzure.ServiceRuntime;
    using Microsoft.WindowsAzure.StorageClient;
    
    
    namespace WorkerRole1
    {
        public class WorkerRole : RoleEntryPoint
        {
            public override void Run()
            {
    
                var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                var queueClient = storageAccount.CreateCloudQueueClient();
                var queue = queueClient.GetQueueReference("messagequeue");
                while (true)
                {
                    Thread.Sleep(10000);
                    if (queue.Exists())
                    {
                        var msg = queue.GetMessage();
                        if (msg != null)
                        {
                            Trace.TraceInformation(string.Format("Сообщение '{0}' обработано.", msg.AsString));
                            queue.DeleteMessage(msg);
                        }
                    }
                }
            }
            public override bool OnStart()
            {
                ServicePointManager.DefaultConnectionLimit = 12;
    
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                    {
                          configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                    });
    
            return base.OnStart();
    
            }
        }
    }

    Приложение Г AzureQueueSample2.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;
    using Microsoft.WindowsAzure.ServiceRuntime;
    
    namespace WebRole1
    {
        public partial class AzureQueueSample2 : System.Web.UI.Page
        {
    
            CloudStorageAccount storageAccount = null;
            CloudQueue cloudQueue = null;
            CloudQueueClient queueClient = null;
    
            protected void Page_Load(object sender, EventArgs e)
            {
                this.storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                this.queueClient = storageAccount.CreateCloudQueueClient();
                this.cloudQueue = this.queueClient.GetQueueReference("myqueue");
                this.cloudQueue.CreateIfNotExist();
                this.DisplayMesssages();
            }
    
    
            private void DisplayMesssages()
            {
                var msgs = this.cloudQueue.PeekMessages(5);
                var cloudList = new List<string>();
    
                foreach (var msg in msgs)
                {
                    cloudList.Add("Message ID: " + msg.Id + "; Message: " + msg.AsString + 
                     "; Message insertion time: " + msg.InsertionTime);
                }
    
                this.Repeater1.DataSource = cloudList;
                this.Repeater1.DataBind();
            }
    
            protected void bnt_addmessage_Click(object sender, EventArgs e)
            {
                CloudQueueMessage msg = new CloudQueueMessage(this.tb_insert.Text);
                this.cloudQueue.AddMessage(msg);
    
                this.DisplayMesssages();
            }
    
            protected void btn_addbinary_Click(object sender, EventArgs e)
            {
                CloudQueueMessage msg = new CloudQueueMessage(File.ReadAllBytes(fu_insertbinary.FileName));
                this.cloudQueue.AddMessage(msg);
    
                this.DisplayMesssages();
            }
    
            protected void btn_getmessage_Click(object sender, EventArgs e)
            {
    
                CloudQueueMessage msg = this.cloudQueue.GetMessage();
                this.lb_retrievedmessage.Text = "Retrieved message: " + msg.AsString;
                this.cloudQueue.DeleteMessage(msg);
    
                this.DisplayMesssages();
            }
    
        }
    }
    Вернуться к учебному плану