Share via


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:

  1. Open the golfer message board application
  2. Modify the table schema
  3. Modify the data source
  4. Modify default.aspx
  5. Modify default.aspx.cs

To open the Golfer Message Board application

  1. Click Start, point to All Programs, point to Microsoft Visual Studio 2012, right-click Visual Studio 2012, and then click Run as administrator.
  2. If the User Account Control dialog appears, click Yes.
  3. Click the FILE menu, point to Open, and then click Project/Solution.
  4. 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

  1. In Solution Explorer, expand MessageBoard_Data, and then double-click MessageBoardEntry.cs to open the file.

  2. 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:

     

  3. Press Ctrl+S to save the Default.aspx file.

Modify the data source

  1. In Solution Explorer, expand MessageBoard_Data, and then double-click MessageBoardDataSource.cs to open the file.

  2. At the beginning of the file, add the following namespace declaration:

    using System.IO
    
  3. 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.

  4. 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);
    
  5. 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:

  6. Press Ctrl+S to save the file.

  7. 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

  1. In Solution Explorer, expand MessageBoard_WebRole, right-click Default.aspx, and then click View Markup.

  2. 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:

  3. 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:

  4. 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

  1. In Solution Explorer, expand MessageBoard_WebRole, right-click Default.aspx, and then click View Code.

  2. At the top of the file, insert the following namespace declaration:

    using System.IO;
    
  3. Inside the btnSend_Click() method, add or modify the lines highlighted in the screenshot:

  4. Press Ctrl+S to save the file.

  5. 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:

  1. Test the application
  2. Generate the service package
  3. Sign in to Windows Azure
  4. Create a storage account. You need a storage account to utilize Windows Azure storage services, for example the table service.
  5. Create a cloud service. The cloud service is used to host the message board application.
  6. To configure the ServiceConfiguration.Cloud.cscfg file
  7. Deploy the application to the staging environment
  8. Test the application
  9. Promote the application to the production environment

To test the application

  1. In Solution Explorer, right-click MessageBoard, and then click Set as Startup Project.
  2. 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.
  3. Switch to Internet Explorer to view the message board application.
  4. Add a few entries to the message board by entering your name and a message before clicking Send.
  5. 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

  1. In Solution Explorer, right-click the MessageBoard cloud project, and then select Package.

  2. In the Package Windows Azure Application dialog, select the following values:

    Name Value
    Service configuration Cloud
    Build configuration Release
  3. 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

  1. Open a Web browser and browse to http://windows.azure.com/. This is the Windows Azure Management Portal.

  2. 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

  1. From the portal, in the left pane, click STORAGE.
  2. On the bottom left corner, click NEW, click STORAGE, and then click QUICK CREATE.
  3. 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.)
  4. 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.
  5. 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.
  6. 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.
  7. 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

  1. From the portal, in the left pane, click CLOUD SERVICES.
  2. On the bottom left corner of the portal page, click NEW, click COMPUTE, click CLOUD SERVICE, and then click CUSTOM CREATE.
  3. 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)
  4. 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

  1. 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".
  2. 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.
  3. 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.
  4. Optionally, you can increase the Instances count to scale out the application.
  5. Save the file and close Notepad.

To deploy the application to the staging environment

  1. From the portal, in the left pane, click CLOUD SERVICES.
  2. In the middle pane, click the cloud service you just created.  The default name is <yourname>gmb..
  3. From the top of the page, click STAGING.
  4. Click UPLOAD A NEW STAGING DEPLOYMENT, or UPDATE on the bottom of the page if you have deployed a tutorial application before.
  5. 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.cspkg
    Configuration file C:\AzureTutorials\Tutorial3\GolferMessageBoard\MessageBoard\bin\Release
    \app.publish\ServiceConfiguration.Cloud.cscfg
    Deploy(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)
  6. Click the check sign on the bottom right corner of the page.
  7. 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

  1. From the portal, in the left pane, click CLOUD SERVICES.
  2. In the middle pane, click the cloud service you created.
  3. From the top of the page, click STAGING.
  4. On the right side of the page, click the site URL.
  5. 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

  1. From the portal, in the left pane, click CLOUD SERVICES.

  2. In the middle pane, click the cloud service you created.

  3. From the top of the page, click STAGING.

  4. On the bottom of the page, click SWAP.

  5. On the right, click YES.

  6. On the top of the page, click PRODUCTION. It takes several minutes to complete the operation.

  7. On the right, click the SITE URL.

  8. 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.

  9. 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

Return to Top