Azure Basic - Insert data into BlockBlob, Table and Queue (with Diagnostic + Azure Storage Explore)


Insert data into BlockBlob, Table and Queue

Prerequisite Knowledge

Blob Storage


Queue Storage


Table Storage


About Table

  • References to System. Data. Services.Client and Microsoft. WindowsAzure. StorageClient , Table storage, under the hood, is exposed as an ADO.NET Data Service(obviously you also need a reference to service runtime if you're hitting table storage from within the cloud itself... remember that you can hit table storage from the desktop too, e.g. from WPF applications).
  • DataServiceContext. You're going to need this to interact with the tables in table storage. the pattern is to create your own context that derives from the base and exposes your tables as IQueryables. 
  • Entity objects. Every table that you have in table storage contains arbitrary columns. In other words, if you really wanted, you could have a different schema for every row in your table. However, to work with it using the Data Services client, each row needs to conform to a fixed schema - this fixed schema you'll represent with a regular C# classthat contains the necessary partition key and row key properties.This class also needs a parameterless constructor (required by the data services client to reconstitute instances of that class from the HTTP results)

Let us start now...

MainPage: About.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;

namespace WebRole1
{
    public partial class About : System.Web.UI.Page
    {
        private static CloudBlobClient blobStorage;
        private static CloudQueueClient queueStorage;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            #region upload the image to blob storage
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            blobStorage = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobStorage.GetContainerReference("guestbookpics");
            container.CreateIfNotExist();

            // configure container for public access
            var permissions = container.GetPermissions();
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;
            container.SetPermissions(permissions);

            // create block blob
            string uniqueBlobName = string.Format("image_{0}.jpg", Guid.NewGuid().ToString());
            CloudBlockBlob blob = container.GetBlockBlobReference(uniqueBlobName);
            blob.Properties.ContentType = FileUpload1.PostedFile.ContentType;

            // upload
            blob.UploadFromStream(FileUpload1.FileContent);
            System.Diagnostics.Trace.TraceInformation("Uploaded image '{0}' to blob storage as '{1}'",
                FileUpload1.FileName, uniqueBlobName);
            #endregion

            #region create a new entry in table storage

            GuestBookEntry entry = new GuestBookEntry() { GuestName = NameTextBox.Text, Message = MessageTextBox.Text, PhotoUrl = blob.Uri.ToString(), ThumbnailUrl = blob.Uri.ToString() };
            GuestBookEntryDataSource ds = new GuestBookEntryDataSource();
            ds.AddGuestBookEntry(entry);
            System.Diagnostics.Trace.TraceInformation("Added entry {0}-{1} in table storage for guest '{2}'", entry.PartitionKey, entry.RowKey, entry.GuestName);

            #endregion

            #region queue a message to process the image
            queueStorage = storageAccount.CreateCloudQueueClient();
            CloudQueue queue = queueStorage.GetQueueReference("guestthumbs");
            queue.CreateIfNotExist();

            var message = new CloudQueueMessage(String.Format("{0},{1},{2}", uniqueBlobName, entry.PartitionKey, entry.RowKey));
            queue.AddMessage(message);
            System.Diagnostics.Trace.TraceInformation("Queued message to process blob '{0}'", uniqueBlobName);
            #endregion
        }
    }
}

Other Pages for table storage

The pattern for using the Storage Client library to access Azure Tables is to create a class derived from TableServiceEntity to contain the data and a class derived from DataServiceContext to handle interaction with Azure Tables.

  1. GuestBookEntry.cs
  2. GuestBookDataContext.cs
  3. GuestBookEntryDataSource.cs

1.GuestBookEntry.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebRole1
{
    public class GuestBookEntry :
        Microsoft.WindowsAzure.StorageClient.TableServiceEntity
    {
        private string guestName;

        public string GuestName
        {
            get { return guestName; }
            set { guestName = value; }
        }

        private string message;

        public string Message
        {
            get { return message; }
            set { message = value; }
        }

        private string photoUrl;

        public string PhotoUrl
        {
            get { return photoUrl; }
            set { photoUrl = value; }
        }

        private string thumbnailUrl;

        public string ThumbnailUrl
        {
            get { return thumbnailUrl; }
            set { thumbnailUrl = value; }
        }

        public GuestBookEntry()
        {
            PartitionKey = DateTime.UtcNow.ToString("MMddyyyy");

            // Row key allows sorting, so we make sure the rows come back in time order.
            RowKey = string.Format("{0:10}_{1}", DateTime.MaxValue.Ticks - DateTime.Now.Ticks, Guid.NewGuid());
        }
        
        
    }
}

2. GuestBookDataContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;

namespace WebRole1
{
    public class GuestBookDataContext : TableServiceContext
    {
        public GuestBookDataContext(string baseAddress, StorageCredentials credentials)
            : base(baseAddress, credentials)
        { }

        public IQueryable<GuestBookEntry> GuestBookEntry
        {
            get
            {
                return this.CreateQuery<GuestBookEntry>("GuestBookEntry");
            }
        }
    }
}

3. GuestBookEntryDataSource.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace WebRole1
{
    public class GuestBookEntryDataSource
    {
        private static CloudStorageAccount storageAccount;
        private GuestBookDataContext context;

        static GuestBookEntryDataSource()
        {
            storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

            CloudTableClient.CreateTablesFromModel(
                typeof(GuestBookDataContext),
                storageAccount.TableEndpoint.AbsoluteUri,
                storageAccount.Credentials);
        }

        public GuestBookEntryDataSource()
        {
            this.context = new GuestBookDataContext(storageAccount.TableEndpoint.AbsoluteUri,
                storageAccount.Credentials);
            this.context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));
        }

        public IEnumerable<GuestBookEntry> Select()
        {
            var results = from g in this.context.GuestBookEntry
                          where g.PartitionKey == DateTime.UtcNow.ToString("MMddyyyy")
                          select g;
            return results;
        }

        public void AddGuestBookEntry(GuestBookEntry newItem)
        {
            this.context.AddObject("GuestBookEntry", newItem);
            this.context.SaveChanges();
        }

        public void UpdateImageThumbnail(string partitionKey, string rowKey, string thumbUrl)
        {
            var results = from g in this.context.GuestBookEntry
                          where g.PartitionKey == partitionKey && g.RowKey == rowKey
                          select g;

            var entry = results.FirstOrDefault<GuestBookEntry>();
            entry.ThumbnailUrl = thumbUrl;
            this.context.UpdateObject(entry);
            this.context.SaveChanges();
        }



    }
}


Global.asax

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

        }

Web.config Diagnostic

 <system.diagnostics>
    <trace  autoflush="true">
      <listeners>
        <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, 
             Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, 
             PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics">
          <filter type="" />
        </add>
        <add name="TestTracer"
        type="System.Diagnostics.TextWriterTraceListener, System, Version=2.0.3600.0, 
        Culture=neutral, PublicKeyToken=b77a5c561934e089"
        initializeData="TextWriterOutput.log" />
      </listeners>
    </trace>
  </system.diagnostics>


Result:

Diagnostic File (TextWriterOutput.log)

w3wp.exe Information: 0 : Uploaded image '1.png' to blob storage as 'image_8203982b-216b-41fc-bf22-359179c9d897.jpg'
w3wp.exe Information: 0 : Added entry 11172011-12520807269362209155_b1bdae27-ec8c-4789-afa7-2e5cdf7f0c69 in table storage for guest 'new image'
w3wp.exe Information: 0 : Queued message to process blob 'image_8203982b-216b-41fc-bf22-359179c9d897.jpg'
w3wp.exe Information: 0 : Uploaded image 'Demo3.png' to blob storage as 'image_1b6cee4b-04b1-4040-84ff-abee92353ae1.jpg'
w3wp.exe Information: 0 : Added entry 11172011-12520807268108757461_df87b8ca-57ca-4a6f-8d9d-55ea5fa9b2c4 in table storage for guest 'new image'
w3wp.exe Information: 0 : Queued message to process blob 'image_1b6cee4b-04b1-4040-84ff-abee92353ae1.jpg'

Azure Storage Explore

Blob


Table


Queue




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值