Azure and SQL Database Tutorials - Tutorial 3: Using Azure Blob Service
This tutorial demonstrates how to use the Azure Blob Service.
Note
If you wish to contribute to this page, use the Edit tab at the top (sign-in required). If you wish to provide feedback for this documentation please either send e-mail to azuredocs@microsoft.com or use the Comment field at the bottom of this page (sign-in required).
In [[Windows Azure and SQL DatabaseTutorials - Tutorial 1: Using Windows Azure Web Role and Windows Azure Table Service|tutorial 1]], you created a simple golfer message board application. In the application, a Web role provides the front-end that allows golfers to view the contents of the message board and add new entries. Each entry contains a name and a message. When golfers post a new message, the Web role creates an entry using the Table service that contains the information entered by the golfers. The Web role also renders this information to the browser so golfers can view the content of the message board.
Tutorial 3 is based on tutorial 1. In this tutorial, you will modify the application you created in tutorial 1. In addition to golfer name and a short message for each message ported to the message board, you will also add an image. You will keep using the Table service for the text portion of the messages, but use the Blob service for images.
Last reviewed: 11/4/2011
Note: Completing tutorial 1 is not a pre-requisite for this tutorial. However, it helps with understanding the scenario.
Note: The tutorial code has been tested on Windows Azure SDK (October 2012).
Objectives
In this tutorial, you will learn how to:
- Use the Blob service
Prerequisites
Note the following requirements before you begin this lesson:
- Before you begin this step you must complete the steps in [[Windows Azure and SQL Database Tutorials (en-US)]].
Understanding the Architecture
The following diagram illustrates the development components and the runtime components involved in this tutorial:
- You develop the Windows Azure application using Visual Studio and Windows Azure SDK.
- You deploy the application to Windows Azure Emulator for testing, and to Windows Azure.
- A Windows Azure project includes two configuration files: ServiceDefinition.csdef and ServiceConfiguration.cscfg. These files are packaged with your Windows Azure application and deployed to Windows Azure.
- A service hosted in Windows Azure consists of one or more Web roles and worker roles. A Web role is an ASP.NET Web application accessible via an HTTP or HTTPS endpoint and is commonly the front-end for an application. A worker role is a role that is useful for generalized development, and may perform background processing for a Web role. The Tutorial 3 application contains a Web role project. For more information, see Overview of a Windows Azure Application at http://msdn.microsoft.com/en-us/library/gg432976.aspx.
- The Windows Azure storage services provide persistent, redundant storage in the cloud. The storage services include these fundamental services: Blob service, Queue service, and Table service. The Table service and the Blob service are used in this tutorial. For more information, see [[Understanding Data Storage Offerings on the Windows Azure Platform]].
Understanding the Blob Service
The Windows Azure Blob service enables applications to store large objects, up to 1TB each. It supports a massively scalable blob system via the Windows Azure CDN, where hot blobs will be served from many servers to scale out and meet the traffic needs of your application. Furthermore, the system is highly available and durable. You can always access your data from anywhere at any time, and the data is replicated at least 3 times for durability. In addition, strong consistency is provided to ensure that the object is immediately accessible once it is added or updated; a subsequent read will immediately see the changes made from a previously committed write.
An application must use a valid account to access Windows Azure Storage. An account can have many Blob containers. Each container provides a grouping of a set of blobs.
In this Article
Lesson 1: Modify the Application to Use the Blob Service
In this lesson, you modify the golfer message board application to use the Blob service for storing images.
Procedures
In this lesson, you will go through the following procedures:
- Open the golfer message board application
- Modify the table schema
- Modify the data source
- Modify default.aspx
- Modify default.aspx.cs
To open the Golfer Message Board application
- Click Start, point to All Programs, point to Microsoft Visual Studio 2012, right-click Visual Studio 2012, and then click Run as administrator.
- If the User Account Control dialog appears, click Yes.
- Click the FILE menu, point to Open, and then click Project/Solution.
- In File name, type C:\AzureTutorials\Tutorial3\GolferMessageBoard\GolferMessageBoard.sln, and the click Open.
In [[Windows Azure and SQL DatabaseTutorials - Tutorial 1: Using Windows Azure Web Role and Windows Azure Table Service|tutorial 1]], you defined a fixed schema for the Table serivce to storage messages. You must modify the schema to include a new data member for storing the URL to the image in the Blob service.
To modify the table schema
In Solution Explorer, expand MessageBoard_Data, and then double-click MessageBoardEntry.cs to open the file.
At the end of the class, define a new data member by adding the following line:
public string ImageURL {get; set;}
The file looks like the following after modification:
Press Ctrl+S to save the Default.aspx file.
Modify the data source
In Solution Explorer, expand MessageBoard_Data, and then double-click MessageBoardDataSource.cs to open the file.
At the beginning of the file, add the following namespace declaration:
using System.IO
At the beginning of the MesageBoardDataSource class, add new data members by inserting the code snippet Tutorial03-Lesson01-Task03_MessageBoardDataSourceDataMembers:
private const string messageImageBlobName = "golfermessageboardpics"; private CloudBlobClient blobClient; private CloudBlobContainer blobContainer;
Note: All letters in a container name must be lowercase. For more restrictions on container names, see Naming Containers, Blobs, and Metadata.
At the end of the default constructor, add code to create a blob container by inserting the code snippet Tutorial03-Lesson01-Task03_MessageBoardDataSourceDefaultConstructor:
blobClient = storageAccount.CreateCloudBlobClient(); blobContainer = blobClient.GetContainerReference(messageImageBlobName); blobContainer.CreateIfNotExist(); var permissions = blobContainer.GetPermissions(); permissions.PublicAccess = BlobContainerPublicAccessType.Container; blobContainer.SetPermissions(permissions);
Inside the class, add a new method for adding a blob by inserting the code snippet Tutorial03-Lesson01-Task03_MessageBoardDataSourceAddBlob:
public string AddBlob(string fileExtension, string fileContentType, Stream fileContent) { // upload the image to blob storage string uniqueBlobName = string.Format(messageImageBlobName + "/image_{0}{1}", Guid.NewGuid().ToString(), fileExtension); CloudBlockBlob blob = blobClient.GetBlockBlobReference(uniqueBlobName); blob.Properties.ContentType = fileContentType ; blob.UploadFromStream(fileContent ); return blob.Uri.ToString(); }
The file looks like the following after modification:
Press Ctrl+S to save the file.
In Solution Explorer, right-click MessageBoard_Data, and then click Rebuild.
Default.aspx presents the message board Web interface. You must modify the page so that golfers can upload an image, and the page can display images along with messages. See the screenshot at the beginning of the tutorial.
To modify the default.aspx file
In Solution Explorer, expand MessageBoard_WebRole, right-click Default.aspx, and then click View Markup.
Find the <div> tag with class=”inputSection”. At the end of the <dl> tag, add the code for uploading images by inserting the code snippet Tutorial03-Lesson01-Task03_WebRoleFileUpload.
<dt> <label for="FileUpload1">Photo:</label> </dt> <dd> <asp:FileUpload ID="FileUpload1" runat="server" size="16" /> <asp:RequiredFieldValidator ID="PhotoRequiredValidator" runat="server" ControlToValidate="FileUpload1" Text="*" /> <asp:RegularExpressionValidator ID="PhotoRegularExpressionValidator" runat="server" ControlToValidate="FileUpload1" ErrorMessage="Only .jpg or .png files are allowed" ValidationExpression="([a-zA-Z\\].*(.jpg|.JPG|.png|.PNG)$)" /> </dd>
If you don't see the code snippet, follow the instructions in [[Windows Azure and SQL Database Tutorials (en-US)]] to copy the code snippets.
The <div> tag looks like the following after the modification:
Find the <div> tag with class=”signature”. At the beginning of the <div> tag, add the code for displaying images by inserting the code snippet Tutorial03-Lesson01-Task03_WebRoleDisplayImage:
<div class="signatureImage"> <img src="<%# Eval("ImageUrl") %>" alt="<%# Eval("GolferName") %>" /> </div>
The <div> tag looks like the following after the modification:
Press Ctrl+S to save the Default.aspx file.
Next, you modify the default.aspx.cs for creating and using the Blob service. In the code, you define a lock to prevent the Blob service being created multiple times.
To modify the default.aspx.cs file
In Solution Explorer, expand MessageBoard_WebRole, right-click Default.aspx, and then click View Code.
At the top of the file, insert the following namespace declaration:
using System.IO;
Inside the btnSend_Click() method, add or modify the lines highlighted in the screenshot:
Press Ctrl+S to save the file.
In Solution Explorer, right-click MessageBoard_WebRole, and then click Rebuild.
What did I just do?
In this step, you introduced the Blob serivce to the golfer message board application.
Next Steps:
You will test the application and prepare the service package for the application.
Return to Top
Lesson 2: Test and Deploy the Application
In this lesson, you test the application in the compute emulator environment, package the application, and then deploy the application to Windows Azure.
Procedures
In this lesson, you will go through the following procedures:
- Test the application
- Generate the service package
- Sign in to Windows Azure
- Create a storage account. You need a storage account to utilize Windows Azure storage services, for example the table service.
- Create a cloud service. The cloud service is used to host the message board application.
- To configure the ServiceConfiguration.Cloud.cscfg file
- Deploy the application to the staging environment
- Test the application
- Promote the application to the production environment
To test the application
- In Solution Explorer, right-click MessageBoard, and then click Set as Startup Project.
- From the Debug menu, click Start Debugging. You will see a compute emulator icon added to the notification area of taskbar, and a new Internet Explorer window showing the Golfer Message Board application.
- Switch to Internet Explorer to view the message board application.
- Add a few entries to the message board by entering your name and a message before clicking Send.
- Close the Internet Explorer window.
After the application is tested successfully in the compute emulator environment, the next step is to create the service package and then deploy the application to Windows Azure.
To generate the service package
In Solution Explorer, right-click the MessageBoard cloud project, and then select Package.
In the Package Windows Azure Application dialog, select the following values:
Name Value Service configuration Cloud Build configuration Release Click Package. After Visual Studio builds the project and generates the service package, Windows Explorer opens with the current folder set to the location where the generated package is stored. The default directory is C:\AzureTutorials\Tutorial3\GolferMessageBoard\MessageBoard\bin\Release\app.publish. Make sure to write down the path. You will need it in the deployment lesson.
You will get a few warning messages about 'DataConnectionString" set up to use the local storage emulator. You can ignore these warning for now.
For deploying the golfer message board application, you must have a storage account for accessing the Windows Azure storage services, and a cloud service, which is a container for service deployments in Windows Azure. For better performance, you might want to create an affinity group to group the service and the storage accounts within a subscription according to geo-location.
To sign in to Windows Azure
Open a Web browser and browse to http://windows.azure.com/. This is the Windows Azure Management Portal.
Sign in using the Windows Live ID associated with your Windows Azure account.
Note: If you haven’t had a Windows Azure Platform subscription, see the Provisioning Windows Azure section of this tutorial.
The next step is to create a storage account for using Windows Azure table service and blob service. If you have created a storage account in [[Windows Azure and SQL DatabaseTutorials - Tutorial 1: Using Windows Azure Web Role and Windows Azure Table Service|tutorial 1]], you can skip this step.
To create a storage account for the golfer message board application to store its data
- From the portal, in the left pane, click STORAGE.
- On the bottom left corner, click NEW, click STORAGE, and then click QUICK CREATE.
- Type or select the following values.
Name Value URL <yourname>gmb (i.e. johndolegmb) REGION/AFFINITY GROUP (Choose the region where you wish your service to run, most likely, the one that is closest to your current location. Select an affinity group instead of a region if you want your storage services to be in the same data center with the cloud service that you will create in the next step. To create an affinity group, open the NETWORKS area of the Management Portal, click AFFINITY GROUPS, and then click CREATE.) - Click the check mark on the bottom right corner. Wait until the status of the storage account changes to Online. The process can take several minutes.
- Once the storage account is created, click the storage account from the storage account list to select it, and then click MANAGE KEYS on the bottom of the page.
- Record the STORAGE ACCOUNT NAME and PRIMARY ACCESS KEY. Later in the tutorial, you will need to configure your cloud service to use storage account by specifying the account name and the access key.
- Close the dialog.
If you have published other tutorial projects before, you can either update the existing cloud service, or create a new cloud service. If you choose to create a new cloud service, you must give a different cloud service URL.
To create a cloud service
- From the portal, in the left pane, click CLOUD SERVICES.
- On the bottom left corner of the portal page, click NEW, click COMPUTE, click CLOUD SERVICE, and then click CUSTOM CREATE.
- Type or select the following values.
Name Value URL <yourname>gmb Note: The URL prefix must be unique.
REGION/AFFINITY GROUP (For better performance, select the same region as the one you chose for the storage service, or use an affinity group.) Deployment a cloud service package now (not selected) - Click the check sign on the bottom right corner. Wait until the status changes to Created. This process could take several minutes.
When you create and test the application locally, the application is configured to use the development storage. Now you have created a storage account, you can configure the application to use the storage account before deploying the application to Windows Azure. The configuration information is in the ServiceConfiguration.Cloud.cscfg file. This file was created when you generated the service package.
To configure the ServiceConfiguration.Cloud.cscfg file
- Use Notepad to open C:\AzureTutorials\Tutorial3\GolferMessageBoard\MessageBoard\bin\Release\app.publish\ServiceConfiguration.Cloud.cscfg. This path can be different if you installed the tutorial files into a different folder than the c root directory. Notice the value of DataConnectionString is "UseDevelopmentStorage=true".
- Change the value of DataConnectionString to DefaultEndpointsProtocol=https;AccountName=<your storage account name>;AccountKey=<your storage account primary access key>. Replace <your storage account name> and <your storage account access key> accordingly.
- Change the value of Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString to DefaultEndpointsProtocol=https;AccountName=<your storage account name>;AccountKey=<your storage account primary access key>. You must replace <your storage account name> and <your storage account primary access key> with the actual account name and account key for the storage account that you created earlier in the tutorial.
- Optionally, you can increase the Instances count to scale out the application.
- Save the file and close Notepad.
To deploy the application to the staging environment
- From the portal, in the left pane, click CLOUD SERVICES.
- In the middle pane, click the cloud service you just created. The default name is <yourname>gmb..
- From the top of the page, click STAGING.
- Click UPLOAD A NEW STAGING DEPLOYMENT, or UPDATE on the bottom of the page if you have deployed a tutorial application before.
- From Upload a package, type or select the following value.
Name Value Deployment name v1.2.0.0 Package location C:\AzureTutorials\Tutorial3\GolferMessageBoard\MessageBoard\bin\Release
\app.publish\MessageBoard.cspkgConfiguration file C:\AzureTutorials\Tutorial3\GolferMessageBoard\MessageBoard\bin\Release
\app.publish\ServiceConfiguration.Cloud.cscfgDeploy(or Update) even if one or more roles contain a single instance (Selected). You can always increase the number of instances from the portal. Start deployment (this option is not available for update a service) (Selected) - Click the check sign on the bottom right corner of the page.
- Wait until the upload process is completed. The process can take several minutes to complete. Notice the DEPLOYMENT NAME is changed to v1.2.0.0.
To test the application in the staging environment
- From the portal, in the left pane, click CLOUD SERVICES.
- In the middle pane, click the cloud service you created.
- From the top of the page, click STAGING.
- On the right side of the page, click the site URL.
- Test the application by entering one or more entries.
After the application is working correctly in the staging environment, you are ready to promote it to the production environment.
To promote the application to production
From the portal, in the left pane, click CLOUD SERVICES.
In the middle pane, click the cloud service you created.
From the top of the page, click STAGING.
On the bottom of the page, click SWAP.
On the right, click YES.
On the top of the page, click PRODUCTION. It takes several minutes to complete the operation.
On the right, click the SITE URL.
In the Properties pane, click the URL in the DNS name box. The application is opened in a new browser tab or a new browser window depending on your browser configuration.
Note: Some DNS services take longer to replicate the records. If you get a page not found error, you might need to try browsing to the URL again in a few minutes.
Test the application in the production environment by entering one or more entries.
What did I just do?
In this step, you tested and deployed the golfer message board to Windows Azure.
Next Steps:
Congratulations! You have completed tutorial 3. [[Windows Azure and SQL Database Tutorials - Tutorial 4: Using Windows Azure Worker Role and Windows Azure Queue Service|Tutorial 4]] shows you how to use another Windows Azure storage called Windows Azure Queue service.
Return to Top
See Also
- [[Windows Azure and SQL Database Tutorials (en-US)]]
- Windows Azure and SQL Database Tutorials - Tutorial 1: Using Windows Azure Web Role and Windows Azure Table Service (en-US)
- Windows Azure and SQL Database Tutorials - Tutorial 2 Using SQL Database
- Windows Azure and SQL Database Tutorials - Tutorial 2.1 Create an OData Service
- Windows Azure and SQL Database Tutorials - Tutorial 4 Using Windows Azure Worker Role and Windows Azure Queue Service
- [[Using the Windows Azure Web Role and Windows Azure Table Service with PHP]]
- [[Using the Windows Azure Web Role and SQL Database with PHP]]
Return to Top