Pada bagian 1 kita sudah membahas apa itu Azure Table Storage dan bagaimana cara membuat Storage Account pada layanan Azure. Selanjutnya kita akan membuat ASP.NET MVC Project yang dapat terhubung dengan layanan Storage Account yang sudah kita buat, kemudian menambahkan data pada Storage Account berupa Azure Table dan Azure Blob. Azure Table digunakan untuk menyimpan data standard yang bertipe string/number (selain blob). Azure Blob digunakan untuk menyimpan data blob seperti file image, video, pdf, dan format lain yang biasanya mempunyai ukuran relatif besar.
Membuat Project ASP.NET MVC
Buka Visual Studio 2015 kemudian buat ASP.NET MVC Project baru dengan nama SampleTableStorage. Kemudian pada folder model tambahkan interface baru dengan nama ITableOperations.cs. Method pada interface ini akan diimplementasikan pada method selanjutnya.
using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using System.Collections.Generic; using System.Configuration; using System; namespace SampleTableStorage.Models { public interface ITableOperations { void CreateEntity(StorageEntity entity); List<StorageEntity> GetEntities(string filter); StorageEntity GetEntity(string partitionKey,string rowKey); } }
Masih pada folder Model, tambahkan class StorageEntity.cs. Class ini digunakan untuk mendefinisikan data model yang akan dibuat pada Azure Table. Class ini berisi definisi dari field-field yang akan dibuat pada Azure Table.
using Microsoft.WindowsAzure.Storage.Table; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace SampleTableStorage.Models { public class StorageEntity : TableEntity { public StorageEntity() { } public StorageEntity(int storageId,string city) { this.RowKey = storageId.ToString(); this.PartitionKey = city; } public string StorageId { get; set; } public string Size { get; set; } public string Environment { get; set; } public decimal PriceDay { get; set; } public decimal PriceMonth { get; set; } public string Space { get; set; } public string Access { get; set; } public string Description { get; set; } [Required(ErrorMessage = "Title Required !")] public string Title { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string ZipCode { get; set; } public string Picture { get; set; } public double Length { get; set; } public double Height { get; set; } public string Phone { get; set; } } }
Setelah membuat TableEntity, maka langkah selanjutnya adalah menambahkan operasi-operasi yang akan dilakukan di Table Storage seperti membuat dan mengambil data pada Azure Table. Pada folder Model, tambahkan class dengan nama TableOperations.cs.
Untuk bekerja dengan Storage Account yang ada di Azure anda harus menambahkan string koneksi pada project anda. Anda dapat mengambil string koneksi tersebut pada portal Azure.
kemudian tambahkan string koneksi tersebut pada file konfirgurasi di web.config
<appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add key="keepStorage" value="DefaultEndpointsProtocol=https;AccountName=keepstorage;AccountKey=<key anda>;BlobEndpoint=https://keepstorage.blob.core.windows.net/;TableEndpoint=https://keepstorage.table.core.windows.net/;QueueEndpoint=https://keepstorage.queue.core.windows.net/;FileEndpoint=https://keepstorage.file.core.windows.net/" /> </appSettings>
Setelah string koneksi ditambahkan, anda dapat menggunakan string koneksi tersebut pada aplikasi anda untuk terhubung dengan Storage Account yang ada pada layanan Azure.
using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using System.Collections.Generic; using System.Configuration; using System; using System.Linq; namespace SampleTableStorage.Models { public class TableOperations : ITableOperations { CloudStorageAccount storageAccount; CloudTableClient tableClient; public TableOperations() { storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["keepStorage"].ToString()); tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("keepstorage"); table.CreateIfNotExists(); } public void CreateEntity(StorageEntity entity) { CloudTable table = tableClient.GetTableReference("keepstorage"); TableOperation insertOperation = TableOperation.Insert(entity); table.Execute(insertOperation); } public List<StorageEntity> GetEntities(string filter) { //List<StorageEntity> storages = new List<StorageEntity>(); CloudTable table = tableClient.GetTableReference("keepstorage"); List<StorageEntity> query = (from entity in table.CreateQuery<StorageEntity>() where entity.PartitionKey == "City" select entity).ToList(); return query; } public StorageEntity GetEntity(string partitionKey, string rowKey) { StorageEntity entity = null; CloudTable table = tableClient.GetTableReference("keepstorage"); entity = (from e in table.CreateQuery<StorageEntity>() where e.PartitionKey == partitionKey && e.RowKey == rowKey select e).FirstOrDefault(); return entity; } } }
Tambahkan juga class dengan nama BlobOperations.cs. Class ini akan digunakan untuk membuat dan menambahkan file blob kedalam objek Azure Blob pada Storage Account.
using System; using System.Web; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using System.Configuration; using System.Threading.Tasks; using System.IO; namespace SampleTableStorage.Models { public class BlobOperations { private static CloudBlobContainer storageBlobContainer; public BlobOperations() { var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["keepStorage"].ToString()); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); storageBlobContainer = blobClient.GetContainerReference("blobkeepstorage"); storageBlobContainer.CreateIfNotExists(); } public CloudBlockBlob UploadBlob(HttpPostedFileBase storagePicFile) { string blobName = Guid.NewGuid().ToString() + Path.GetExtension(storagePicFile.FileName); CloudBlockBlob storageBlob = storageBlobContainer.GetBlockBlobReference(blobName); using (var fs = storagePicFile.InputStream) { storageBlob.UploadFromStream(fs); } return storageBlob; } } }
Kemudian langkah selanjutnya adalah membuat controller dengan nama StorageListController.cs. Pada controller ini kita akan menambahkan method yang digunakan untuk menambahkan data ke Azure Table dan Azure Blob.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SampleTableStorage.Models; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Blob; namespace SampleTableStorage.Controllers { public class StorageListController : Controller { BlobOperations blobOperations; TableOperations tableOperations; public StorageListController() { blobOperations = new BlobOperations(); tableOperations = new TableOperations(); } // GET: StorageList public ActionResult Index() { var storages = tableOperations.GetEntities("Spokane"); return View(storages); } public ActionResult Create() { var objStorage = new StorageEntity(); //objStorage.StorageId = Guid.NewGuid().ToString(); objStorage.City = "Spokane"; ViewBag.Environment = new SelectList(new List<string>() { "Outdoor","Indoor" }); ViewBag.Access = new SelectList(new List<string>() { "Limited","Anytime" }); return View(); } [HttpPost] public ActionResult Create(StorageEntity obj,HttpPostedFileBase Picture) { //upload file to blob CloudBlockBlob storageBlob = null; if(Picture != null && Picture.ContentLength !=0) { storageBlob = blobOperations.UploadBlob(Picture); obj.Picture = storageBlob.Uri.ToString(); } obj.City = "Spokane"; obj.RowKey = Guid.NewGuid().ToString(); obj.PartitionKey = obj.City; tableOperations.CreateEntity(obj); return RedirectToAction("Index","Home"); } } }
Setelah membuat controller maka untuk membuat form input yang akan kita gunakan untuk menambahkan data ke Azure Table anda dapat menambahkan view dengan nama Create.cshtml berikut.
@model SampleTableStorage.Models.StorageEntity @{ ViewBag.Title = "Create"; } @using (Html.BeginForm("Create","StorageList",FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken()Storage Entity
@Html.ValidationSummary(true, "", new { @class = "text-danger" })@Html.LabelFor(model => model.Size, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Size, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Size, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.Environment, htmlAttributes: new { @class = "control-label col-md-2" })@Html.DropDownListFor(model=>model.Environment, (IEnumerable)ViewBag.Environment,new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Environment, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.PriceDay, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.PriceDay, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PriceDay, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.PriceMonth, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.PriceMonth, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PriceMonth, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.Space, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Space, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Space, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.Access, htmlAttributes: new { @class = "control-label col-md-2" })@Html.DropDownListFor(model => model.Access, (IEnumerable)ViewBag.Access ,new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Access, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.State, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.ZipCode, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.ZipCode, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ZipCode, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.Picture, htmlAttributes: new { @class = "control-label col-md-2" })@Html.ValidationMessageFor(model => model.Picture, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.Length, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Length, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Length, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.Height, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Height, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Height, "", new { @class = "text-danger" })</div>@Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })</div></div> </div> }@Html.ActionLink("Back to List", "Index")Setelah itu anda dapat mencoba menjalankan aplikasi ini dan memasukan data kedalam Azure Table dan Azure Blob
Setelah berhasil anda dapat melihat isi dari Azure Table dan Azure Blob yang sudah anda buat di Visual Studio 2015 Cloud Explorer.
Azure Mobile Services–Mengupdate Data
Tutorial ini akan membahas bagaimana cara mengupdate data table pada Azure Mobile Services.
Tutorial sebelumnya: https://erickkurniawan.net/2015/12/05/azure-mobile-services-menambahkan-data-baru-pada-table/
Untuk melakukan update data anda dapat menggunakan method PUT atau PATCH. Dengan menggunakan PATCH anda cukup mengirimkan field yang akan diupdate. Sebagai contoh kita akan mengupdate field ‘Complete’ menjadi ‘true’ dari data dengan id tertentu.
Jika anda lihat record setelah data diupdate adalah sebagai berikut :
Untuk mendelete data anda dapat menggunakan method DELETE.
Maka record tersebut akan didelete sehingga kita sudah tidak mempunyai record yg tersisa.
Tambahkan beberapa record lagi sebagai data contoh karena kita akan mencoba beberapa variasi query dapat dilakukan.
Kita dapat menggunakan sintaks ODATA untuk memfilter record sesuai dengan kebutuhan. Untuk menampilkan data yg field ‘Complete’ bernilai ‘true’ tambahkan sintaks berikut pada url.
https://cloudemiaams.azure-mobile.net/Tables/Courses?$filter=Complete eq true
Hasil query dalam format JSON adalah sebagai berikut :
Untuk contoh2 query pada ODATA dapat dilihat pada alamat berikut : http://www.odata.org/documentation/odata-version-2-0/uri-conventions/
Misal untuk mengurutkan data course berdasarkan title, anda dapat menggunakan keyword $orderby sebagai berikut:
PHP & MySQL dengan Layanan Azure Web Apps
Pada tutorial kali ini kita akan mencoba untuk membuat aplikasi web dengan menggunakan PHP dan MySQL kemudian memasang aplikasi tersebut pada layanan Azure Web App.
Untuk menjalankan tutorial yang akan kita buat pada bab ini, maka anda harus menginstal beberapa aplikasi sebagai berikut.
- XAMPP Lite (jika anda ingin menjalankan aplikasi di server lokal).
- MySQL Workbench
- Visual Studio Code for Editor (atau editor lain seperti sublimetext)
- Git
- GitHub account
- GitHub desktop for Windows/Mac
Membuat Database MySQL di Azure
1. Login kedalam azure portal.
2. Pilih new icon, kemudian pilih Data + Storage, kemudian MySQL Database.
3. Buat resource group baru, sebagai contoh ‘bmis489’.
4. Pilih tombol create, dan sekarang database MySQL sudah dapat digunakan.
1. Anda dapat melihat database properties. Kita akan menggunakan property tersebut ketika akan mengakses MySQL database dari server side script.
2. Setelah database dibuat, anda dapat melakukan pengaturan database cloud tersebut pada komputer lokal. Buka tool MySQL Workbench dan masukan informasi hostname, username, dan password. Click Pilih Connection button untuk memastikan bahwa koneksi anda lancar.
3. Buka MySQL Workbench, pada jendela query tambahkan script berikut, dan kemudian jalankan script untuk membuat tabel ‘registration_tbl’.
CREATE TABLE registration_tbl(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name VARCHAR(30), email VARCHAR(30), date DATE);1. Anda dapat melihat tabel “registration_tbl” berhasil dibuat.
Membuat Aplikasi Web dengan PHP
1. Langkah selanjutnya adalah membuat aplikasi web.
2. Pilih New Icon, kemudian pilih Web + Mobile, kemudian pilih Web App.
3. Masukan nama untuk aplikasi web yang anda buat.
4. Pilih “bmis489” sebagai nama resource group.
5. Pilih tombol create.
6. Ketika aplikasi web sudah berhasil dibuat, anda akan melihat tampilan resource group. Pilih nama pada aplikasi web untuk melakukan konfigurasi.
1. Buka aplikasi GitHub Desktop pada komputer lokal.
1. Buat file PHP dengan nama “index.php” dengan editor favorit anda. Simpan pada folder “PHPOnAzure”.
2. Buka file “index.php” dan tambahkan script berikut untuk terbuhung dengan MySQL database pada layanan Azure, menampilkan data peserta, dan menambahkan peserta pada sistem.
<html>
<head>
<Title>Registration Form</Title>
<style type="text/css">
body { background-color: #fff; border-top: solid 10px #000;
color: #333; font-size: .85em; margin: 20; padding: 20;
font-family: "Segoe UI", Verdana, Helvetica, Sans-Serif;
}
h1, h2, h3,{ color: #000; margin-bottom: 0; padding-bottom: 0; }
h1 { font-size: 2em; }
h2 { font-size: 1.75em; }
h3 { font-size: 1.2em; }
table { margin-top: 0.75em; }
th { font-size: 1.2em; text-align: left; border: none; padding-left: 0; }
td { padding: 0.25em 2em 0.25em 0em; border: 0 none; }
</style>
</head>
<body>
<h1>Register here!</h1>
<p>Fill in your name and email address, then click <strong>Submit</strong> to register.</p>
<form method="post" action="index.php">
Name <input type="text" name="name" id="name"/></br>
Email <input type="text" name="email" id="email"/></br>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
// DB connection info
//TODO: Update the values for $host, $user, $pwd, and $db
//using the values you retrieved earlier from the portal.
$host = "us-cdbr-azure-west-c.cloudapp.net";
$user = "b411a3239c5914";
$pwd = "7aee971d";
$db = "acsm_ac58c273e12d294";
// Connect to database.
try {
$conn = new PDO( "mysql:host=$host;dbname=$db", $user, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(Exception $e){
die(var_dump($e));
}
// Insert registration info
if(!empty($_POST)) {
try {
$name = $_POST['name'];
$email = $_POST['email'];
$date = date("Y-m-d");
// Insert data
$sql_insert = "INSERT INTO registration_tbl (name, email, date)
VALUES (?,?,?)";
$stmt = $conn->prepare($sql_insert);
$stmt->bindValue(1, $name);
$stmt->bindValue(2, $email);
$stmt->bindValue(3, $date);
$stmt->execute();
}
catch(Exception $e) {
die(var_dump($e));
}
echo "<h3>Your're registered!</h3>";
}
// Retrieve data
$sql_select = "SELECT * FROM registration_tbl";
$stmt = $conn->query($sql_select);
$registrants = $stmt->fetchAll();
if(count($registrants) > 0) {
echo "<h2>People who are registered:</h2>";
echo "<table>";
echo "<tr><th>Name</th>";
echo "<th>Email</th>";
echo "<th>Date</th></tr>";
foreach($registrants as $registrant) {
echo "<tr><td>".$registrant['name']."</td>";
echo "<td>".$registrant['email']."</td>";
echo "<td>".$registrant['date']."</td></tr>";
}
echo "</table>";
} else {
echo "<h3>No one is currently registered.</h3>";
}
?>
</body>
</html>
1. Buka aplikasi GitHub Desktop, dan kemudian pilih tombol commit to master untuk melakukan aksi push scripts anda kedalam Git repository.
2. Pilih tombol sync pada pojok kanan atas untuk melakukan aksi push local changes ke master yang ada di remote server.
3. Kembali ke pengaturan aplikasi web pada Azure. Pilih “Continuous Deployment” untuk melakukan automate build, test, dan deploy aplikasi web yang telah dibuat ketika anda melakukan check-in ke GitHub.
4. Tambahkan akun GitHub anda, dan pilih kode anda pada code repository.
5. Setelah anda mempublish aplikasi anda, maka anda dapat mengedit kode dari aplikasi tersebut jika dibutuhkan, anda cukup melakukan code check-in pada akun GitHub anda, dan Azure akan mengambil kode anda secara otomatis kemudian mempublish kode anda. Untuk melihat aplikasi, anda dapat mengakses tautan berikut http://bmis489web.azurewebsites.net/index.php.
Azure Mobile Services – Menambahkan Data Baru pada Table
Tutorial ini akan membahas bagaimana cara menambahkan data baru pada Azure Mobile Services.
Tutorial sebelumnya dapat dilihat di: https://erickkurniawan.net/2015/11/14/azure-mobile-services-rest-services/
Untuk menambahkan table pada windows azure mobile services, sebenarnya anda tidak perlu menggunakan SQL Server Management studio atau fasilitas managed database di SQL Azure. Anda dapat menambahkan table lewat menu Mobile Services.
Pertama kita akan menambahkan table baru dengan nama ‘Courses’.
Secara default table yang kita buat akan memiliki empat column sebagai berikut :
Jika anda buka table tersebut di SQL Server Management studio, dapat dilihat bahwa column Id akan digunakan sebagai primary key.
Tambahkan 3 column baru dengan nama Title – string, Description- string, dan Complete – boolean.
Setelah menambahkan column tersebut, sekarang kita akan mencoba untuk menambahkan data kedalam table yang sudah kita buat menggunakan fiddler. Untuk menambahkan data kita akan menggunakan method POST.
Jika data berhasil ditambah maka akan muncul status kode ‘201 Created’.
Jika kita lihat data yang kita inputkan pada windows azure adalah sebagai berikut :
Tutorial selanjutnya akan membahas bagaimana cara untuk mengupdate data pada object Table di Azure Mobile Services.