- •Методические указания к выполнению лабораторных работ по дисциплине «Распределенные системы»
- •Общие положения
- •Организация занятий по курсу
- •Требования к содержанию отчетов о выполнении лабораторных работ
- •Требования к оформлению отчетной документации
- •Задания на лабораторные работы Лабораторная работа №1
- •Лабораторная работа №2
- •Лабораторная работа №3
- •Теоретические положения
- •Задание
- •Ход работы
- •Требования к содержанию отчета
- •Перечень полезных ссылок
- •Лабораторная работа №4
- •Теоретические положения
- •Задание
- •Ход работы
- •Требования к содержанию отчета
- •Удаление строки
- •Редактирование сущности
- •Требования к содержанию отчета
- •Список вспомогательных материалов
- •Лабораторная работа №6
- •Теоретические положения
- •Задание
- •Ход работы
- •Список вспомогательных материалов
- •Лабораторная работа №7
- •Теоретические положения
- •Задание
- •Ход работы
- •Список дополнительных материалов для самостоятельного изучения
- •Требования к содержанию индивидуального задания
- •Список рекомендуемой литературы
- •Приложение а – Варианты индивидуальных заданий
- •Приложение б – Полные листинги составленных программ
- •Приложение в – Пример титульного листа индивидуального задания
- •Приложение г – Пример выполнения реферата
- •43 Стр., 6 рис., 1 табл., 0 прил., 14 ист.
Приложение б – Полные листинги составленных программ
AzureTable.aspx.cs (лабораторная работа №5)
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.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using System.Data.Services.Client;
namespace WebRole1
{
public partial class StudentTable : System.Web.UI.Page
{
private CloudStorageAccount account = null;
private StudentContext context = null;
protected void Page_Load(object sender, EventArgs e)
{
account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
context = new StudentContext(account.TableEndpoint, account.Credentials);
StudentGV.DataSource = context.StudentData;
StudentGV.DataBind();
int i = 0;
foreach (TableCell cell in StudentGV.HeaderRow.Cells)
{
if (cell.Text == "PartitionKey") { Session["pkindex"] = i; }
if (cell.Text == "RowKey") { Session["rkindex"] = i; }
i++;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var statusMessage = String.Empty;
try
{
var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
var context = new StudentContext(account.TableEndpoint, account.Credentials);
context.Add(new Student
{
PartitionKey = "Students",
RowKey = this.Num.Text,
Number = Convert.ToInt32(Num.Text),
SurName = Fam.Text,
FirstName = Im.Text,
LastName = Ot.Text,
Faculty = Fak.Text,
FormEducation = Forma.Text
});
}
catch (DataServiceRequestException ex)
{
statusMessage = "Unable to connect to the table storage server. Please check that the service is running.<br>" + ex.Message;
}
Lb_Status.Text = statusMessage;
StudentGV.DataBind();
}
protected void StudentGV_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView g = (GridView)sender;
try
{
Student c = (from student in context.CreateQuery<Student>("Students")
where student.PartitionKey == g.Rows[e.RowIndex].
Cells[Convert.ToInt32(Session["pkindex"].ToString())].Text
&& student.RowKey == g.Rows[e.RowIndex].Cells[Convert.ToInt32
(Session["rkindex"].ToString())].Text
select student).FirstOrDefault();
context.Delete(c);
}
catch (DataServiceRequestException ex)
{
Lb_Status.Text = ex.Message;
}
g.DataBind();
}
protected void StudentGV_SelectedIndexChanged(object sender, EventArgs e)
{
GridView g = (GridView)sender;
int index = g.SelectedIndex;
Student c = (from student in context.CreateQuery<Student>("Students")
where student.PartitionKey == g.Rows[index].
Cells[Convert.ToInt32(Session["pkindex"].ToString())].Text
&& student.RowKey == g.Rows[index].
Cells[Convert.ToInt32(Session["rkindex"].ToString())].Text
select student).FirstOrDefault();
Num.Text = Convert.ToString(c.Number);
Fam.Text = c.SurName;
Im.Text = c.FirstName;
Ot.Text = c.LastName;
Fak.Text = c.Faculty;
Forma.Text = c.FormEducation;
Session["index"] = index;
btnChange.Visible = true;
}
protected void btnChange_Click(object sender, EventArgs e)
{
int index = Convert.ToInt32(Session["index"].ToString());
try
{
Student c = (from contact in context.CreateQuery<Student>("Students")
where contact.PartitionKey == StudentGV.Rows[index].
Cells[Convert.ToInt32(Session["pkindex"].ToString())].Text
&& contact.RowKey == StudentGV.Rows[index].
Cells[Convert.ToInt32(Session["rkindex"].ToString())].Text
select contact).FirstOrDefault();
c.Number = Convert.ToInt32(Num.Text);
c.SurName = Fam.Text;
c.FirstName = Im.Text;
c.LastName = Ot.Text;
c.Faculty = Fak.Text;
c.FormEducation = Forma.Text;
context.Update(c);
}
catch (DataServiceRequestException a)
{
Lb_Status.Text = a.Message;
}
StudentGV.DataBind();
}
}
}
AzureBlobSample.aspx (лабораторная работа №6)
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="AzureBlobSample.aspx.cs" Inherits="WebRole1.AzureBlobSample" %>
<!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 id="Head1" runat="server">
<title></title>
<style type="text/css">
.style1
{
height: 25px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="X-Large"
Text="My Image Gallery - Azure Blob Example"></asp:Label>
<br />
<br />
<table style="width:100%;">
<tr>
<td>
<asp:Label ID="lb_name" runat="server" Text="Название"></asp:Label>
</td>
<td>
<asp:TextBox ID="tb_name" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lb_desc" runat="server" Text="Описание"></asp:Label>
</td>
<td>
<asp:TextBox ID="tb_desc" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="lb_file" runat="server" Text="Файл"></asp:Label>
</td>
<td class="style1">
<asp:FileUpload ID="fu_upload" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btn_upload" runat="server" onclick="btn_upload_Click"
Text="Загрузить" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Label ID="lb_status" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:ListView ID="lv_images" runat="server"
onitemdatabound="lv_images_ItemDataBound">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</LayoutTemplate>
<EmptyDataTemplate>
<h2>No Data Available</h2>
</EmptyDataTemplate>
<ItemTemplate>
<div class="item">
<ul style="width:40em;float:left;clear:left" >
<asp:Repeater ID="blobMetadata" runat="server">
<ItemTemplate>
<li><%# Eval("Name") %><span><%# Eval("Value") %></span></li>
</ItemTemplate>
</asp:Repeater>
<li>
<asp:LinkButton ID="deleteBlob"
OnClientClick="return confirm('Delete image?');"
CommandName="Delete"
CommandArgument='<%# Eval("Uri")%>'
runat="server" Text="Удалить" oncommand="OnDeleteImage" />
<asp:LinkButton ID="CopyBlob"
OnClientClick="return confirm('Copy image?');"
CommandName="Copy"
CommandArgument='<%# Eval("Uri")%>'
runat="server" Text="Копировать" oncommand="OnCopyImage" />
</li>
</ul>
<img src="<%# Eval("Uri") %>" alt="<%# Eval("Uri") %>" style="float:left"/>
</div>
</ItemTemplate>
</asp:ListView>
</td>
</tr>
<tr>
<td>
<br />
</td>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
AzureBlobSample.aspx.cs (лабораторная работа №6)
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.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using System.Configuration;
using System.Collections.Specialized;
namespace WebRole1
{
public partial class AzureBlobSample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
this.EnsureContainerExists();
}
this.RefreshGallery();
}
catch (System.Net.WebException we)
{
lb_status.Text = "Network error: " + we.Message;
if (we.Status == System.Net.WebExceptionStatus.ConnectFailure)
{
lb_status.Text += "<br />Please check if the blob service is running at " +
ConfigurationManager.AppSettings["storageEndpoint"];
}
}
catch (StorageException se)
{
Console.WriteLine("Storage service error: " + se.Message);
}
}
private void RefreshGallery()
{
lv_images.DataSource =
this.GetContainer().ListBlobs(new BlobRequestOptions()
{
UseFlatBlobListing = true,
BlobListingDetails = BlobListingDetails.All
});
lv_images.DataBind();
}
private CloudBlobContainer GetContainer()
{
CloudStorageAccount.SetConfigurationSettingPublisher(
(configName, configSettingPublisher) =>
{
var connectionString =
RoleEnvironment.GetConfigurationSettingValue(configName);
configSettingPublisher(connectionString);
}
);
var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
var client = account.CreateCloudBlobClient();
return client.GetContainerReference(RoleEnvironment.GetConfigurationSettingValue("ContainerName"));
}
private void EnsureContainerExists()
{
var container = GetContainer();
container.CreateIfNotExist();
var permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
}
private void SaveImage(string id, string name, string description, string fileName, string contentType, byte[] data)
{
var blob = this.GetContainer().GetBlobReference(name);
blob.Properties.ContentType = contentType;
try
{
blob.UploadFromStream(fu_upload.FileContent);
blob.Metadata["Id"] = id;
blob.Metadata["Filename"] = fileName;
blob.Metadata["ImageName"] = String.IsNullOrEmpty(name) ? "unknown" : name;
blob.Metadata["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
blob.SetMetadata();
lv_images.DataBind();
}
catch (Exception ex)
{ lb_status.Text = ex.Message; }
}
protected void btn_upload_Click(object sender, EventArgs e)
{
if (fu_upload.HasFile)
{
lb_status.Text = "Inserted [" + fu_upload.FileName + "] - Content Type [" +
fu_upload.PostedFile.ContentType + "] - Length [" + fu_upload.PostedFile.ContentLength + "]";
this.SaveImage(Guid.NewGuid().ToString(),
tb_name.Text,
tb_desc.Text,
fu_upload.FileName,
fu_upload.PostedFile.ContentType,
fu_upload.FileBytes
);
RefreshGallery();
}
else
lb_status.Text = "No image file";
}
protected void lv_images_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var metadataRepeater = e.Item.FindControl("blobMetadata") as Repeater;
var blob = ((ListViewDataItem)(e.Item)).DataItem as CloudBlob;
if (blob != null)
{
if (blob.SnapshotTime.HasValue)
{
var delBtn = e.Item.FindControl("deleteBlob") as LinkButton;
if (delBtn != null) delBtn.Text = "Delete Snapshot";
var snapshotBtn = e.Item.FindControl("SnapshotBlob") as LinkButton;
if (snapshotBtn != null) snapshotBtn.Visible = false;
}
if (metadataRepeater != null)
{
metadataRepeater.DataSource = from key in blob.Metadata.AllKeys
select new
{
Name = key,
Value = blob.Metadata[key]
};
metadataRepeater.DataBind();
}
}
}
}
protected void OnDeleteImage(object sender, CommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
var blobUri = (string)e.CommandArgument;
var blob = this.GetContainer().GetBlobReference(blobUri);
blob.DeleteIfExists();
}
}
catch (StorageClientException se)
{
lb_status.Text = "Storage client error: " + se.Message;
}
catch (Exception) { }
RefreshGallery();
}
protected void OnCopyImage(object sender, CommandEventArgs e)
{
if (e.CommandName == "Copy")
{
// Prepare an Id for the copied blob
var newId = Guid.NewGuid();
// получение исходного объекта
var blobUri = (string)e.CommandArgument;
var srcBlob = this.GetContainer().GetBlobReference(blobUri);
// создание нового бинарного объекта
var newBlob = this.GetContainer().GetBlobReference(newId.ToString());
// копирование содержимого исходного объекта
newBlob.CopyFromBlob(srcBlob);
// получаем метаданные для нового объекта
newBlob.FetchAttributes(new BlobRequestOptions { BlobListingDetails = BlobListingDetails.Metadata });
// изменение метаданных нового объекта, чтобы показать, что это копия
newBlob.Metadata["ImageName"] = "Copy of \"" +
newBlob.Metadata["ImageName"] + "\"";
newBlob.Metadata["Id"] = newId.ToString();
newBlob.SetMetadata();
RefreshGallery();
}
}
}
}
AzureQueueSample.aspx.cs (лабораторная работа №7)
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();
//создаем сообщение, источник - текстовое поле tb_message
var msg = new CloudQueueMessage(tb_message.Text);
//добавляем сообщение в очередь
queue.AddMessage(msg);
tb_message.Text = string.Empty;
}
}
}
Global.aspx.cs (лабораторная работа №7)
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.StorageClient;
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)
{
// Код, выполняемый при запуске приложения.
// Примечание: Событие Session_End вызывается только в том случае, если для режима sessionstate
// задано значение InProc в файле Web.config. Если для режима сеанса задано значение StateServer
// или SQLServer, событие не порождается.
}
}
}
WorkerRole.cs (лабораторная работа №7)
using System;
using System.Collections.Generic;
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");
// получение сообщение и передача его в лог эмулятора 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);
}
}
}
}
public override bool OnStart()
{
ServicePointManager.DefaultConnectionLimit = 12;
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
{
configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
});
return base.OnStart();
}
}
}
AzureQueueSample2.aspx.cs (лабораторная работа №7)
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();
}
protected void bnt_addmessage_Click(object sender, EventArgs e)
{
CloudQueueMessage msg = new CloudQueueMessage(this.tb_insert.Text);
this.cloudQueue.AddMessage(msg);
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 btn_addbinary_Click(object sender, EventArgs e)
{
// файл не должен превышать размер - лимит сообщения - 8Кб
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();
}
}
}