Azure Table Storage dengan ASP.NET MVC (Part 2)

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.

image

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

image

Setelah berhasil anda dapat melihat isi dari Azure Table dan Azure Blob yang sudah anda buat di Visual Studio 2015 Cloud Explorer.

image

image

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s