Build new applications in the cloud - or use interoperable services that run on Microsoft infrastructure to extend and enhance your existing applications. You choose what's right for you.

Table of Contents

 


 

Lab 2.1 — Windows Azure Data Storage

Getting Started

Blob Services

 

In this lab, you will learn how to use Windows Azure Storage Service by applying it to Blob Services.

 

You will use Windows Azure Blob Storage API through Windows Azure SDK for PHP to create an application that saves and retrieves text and image data stored as blobs in Windows Azure storage.

 


 

Task 0 — Prerequisites

 

Before doing this lab, if you not done so:

 

  1. Complete install of Windows Azure for Eclipse
  2. Complete first lab Getting Started
  3. This lab requires that you register for a developer account in order perform tasks pertaining to Window Azure Cloud.

     

    To register, please visit Windows Azure Platform — Account Information.

  4. Get Blobs Lab:   Download

 


 

Part 1 — Windows Azure Toolkit 4 Eclipse

 


 

 

Task 1 — Windows Azure Blob Storage

 

Binary large objects " Blobs " are just slabs of bytes.

 

Windows Azure Blob enables applications to store large sets of these slabs of bytes, up to 50GB each in the cloud. It supports a massively scalable blob system, 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.

 

Blob Data Model

Blob RESTful Interface

All access to Windows Azure Blob is done through a standard HTTP REST PUT/GET/DELETE interface.

 

To identify a particular blob, an application supplies a URI of the form:

 

http://<StorageAccount>.blob.core.windows.net/<Container>/<BlobName>

 

<StorageAccount> is a unique identifier assigned when a new storage account is created, while <Container> and <BlobName> are the names of a specific container and a blob within that container. Containers can’t be nested"they can contain only blobs, not other containers"so it’s not possible to create a hierarchy of blobs. Still, it’s legal for a blob name to contain a “/”, so a developer can create the illusion of a hierarchy if desired.

 

Recall that blobs can be large "up to 50 gigabytes" and so to make transferring them more efficient, each blob can be subdivided into blocks. If a failure occurs, retransmission can resume with the most recent block rather than sending the entire blob again. Once all of a blob’s blocks have been uploaded, the entire blob can be committed at once.

 

Containers can be marked as private or public. For blobs in a private container, both read and write requests must be signed using the key for the blob’s storage account. For blobs in a public container, only write requests must be signed; any application is allowed to read the blob. This can be useful in situations such as making video, photos, or other unstructured data generally available on the Internet.

 

     Learn more...

 

Windows Azure SDK for PHP

This SDK provides access through PHP class to Windows Azure's storage, computation and management interfaces by abstracting the REST/XML interface Windows Azure provides into a simple PHP API.

 

     Learn more...

 


 

Task 2 — Create Windows Azure PHP Project for Blob Storage

 

In this task, because Blob is a serviced Windows Azure Data Storage type, you will create a Windows Azure PHP Project that uses Windows Azure Data Storage.

 

  1. Start Eclipse with Windows Azure PHP Projects plug-in installed.
  2. Assign or Create workspace folder as Eclipse starts.
  3. Change Eclipse perspective from PHP to PHP Windows Azure.
    1. In Eclipse menu-bar, select Window menu.
    2. In Window menu, select Open Perspective menu-item.
    3. In Open Perspective menu-item, select Other... cascading menu-item.
    4. In Open Perspective panel, select PHP Windows Azure
  4. In the PHP Windows Azure perspective, create a new Windows Azure Web Project.
    1. In Eclipse menu-bar, select File menu.
    2. In File menu, select New menu-item.
    3. In New menu-item, select Windows Azure Web Project cascading menu-item.
    4. In new PHP Azure Project panel:
      1. Provide project name BlobStorage
      2. In Data Storage Options, select Windows Azure Data Storage
      3. Select Finish button
  5. Note that in the PHP Explorer, examine the structure of the created solution.

    Two PHP projects have been created:

    • BlobStorage
    • BlobStorage_WebRole

 


 

Task 3 — Default Contents of a PHP Windows Azure Storage Project

 

When creating a Windows Azure Web Project configured with Windows Azure Data Storage, Windows Azure Toolkit for Eclipse provides a solution that ready to run in both the Development Fabric and within the Windows Azure Cloud.

 

In this task, you are going to understand what are the default contents of new Windows Azure Web Project configured with Windows Azure Data Storage.

 

PHP Web Role Project created for Windows Azure Data Storage

The toolkit's default Web Role project created for Azure Storage is a standard PHP Web Role application project template that has been modified to work with Windows Azure Storage using PHP Azure SDK.

 

The Web Role Storage project for this lab is BlobStorage_WebRole

 

 

The toolkit's default contents of a Web Role project for Azure Storage are:

 

PHP Service Project for created Windows Azure Data Storage

The toolkit's default Service project created for Windows Azure Storage contains definition and configuration to run the Web Role Storage application in the Development Fabric and the Windows Azure Cloud.

 

The Service Storage project for this lab is BlobStorage

 

FILE ServiceDefinition.csdef

Discussion about file ServiceDefinition.csdef continues where Lab Getting Started leaves off.

 

ServiceDefinition.csdef now contains metadata needed by the Windows Azure fabric to handle Storage.

 

From previous lab, ServiceDefinition.csdef differs because Web Role element now has ConfigurationSettings metadata, which describes a collection of configuration settings for the web role.

XML — ServiceDefinition.csdef — ConfigurationSettings
<ConfigurationSettings>
  <!-- Azure Storage Account for Cloud Environment -->
  <Setting name="AzureCloudStorageAccountName"/>
  <Setting name="AzureCloudStorageAccountKey"/>      
  
  <!-- Azure Storage Account for Dev Environment -->
  <Setting name="AzureDevStorageAccountName"/>
  <Setting name="AzureDevStorageAccountKey"/>       
</ConfigurationSettings>

 

FILE ServiceConfiguration.cscfg

Discussion about ServiceConfiguration.cscfg continues where Lab Getting Started leaves off.

 

ServiceConfiguration.cscfg now has settings needed by the Windows Azure fabric to handle Storage.

 

From previous lab, ServiceConfiguration.cscfg differs because Web Role element now has ConfigurationSettings:

 

XML — ServiceConfiguration.cscfg
<ConfigurationSettings>
  <!-- Azure Storage Account for Cloud Environment -->
  <Setting name="AzureCloudStorageAccountName" value="MyAccountName"/>
  <Setting name="AzureCloudStorageAccountKey" value="MyAccountKey"/>      
  
  <!-- Azure Storage Account for Dev Environment -->
  <Setting name="AzureDevStorageAccountName" value="devstoreaccount1"/>
  <Setting name="AzureDevStorageAccountKey" value="Eby8vd...=="/>
</ConfigurationSettings>

 

Development Storage Account Information
Account Name — devstoreaccount1
Account Key — Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==

 


 

Task 4 — Windows Azure Storage Explorer

 

Provided with the installation of Windows Azure 4 Eclipse plug-in is a very powerful tool, Windows Azure Storage Explorer, which is used for browsing storage locally in Development Storage or remotely within your remote Windows Azure Storage account.

 

To browse storage locally in Development Storage:

  1. In Eclipse menu-bar, select Windows Azure menu.
  2. In Windows Azure menu, select Open Windows Azure Storage Explorer menu-item.
  3. In Windows Azure Storage Explorer panel, there is a pull-down menu below Storage Account.
  4. Select devstoreaccount1 and then Open button to show current storage contents within your local Development Storage.
  5. To manage other Storage Account(s), select Manage link
  6. From here, more storage accounts can be added for viewing by Windows Azure Storage Explorer.

 

 Note:

Storage Account — devstoreaccount1

Upon initial opening of Windows Azure Storage Explorer, the local Development Storage account informatin should already be configured:

Development Storage Account Information
Account Name — devstoreaccount1
Account Key — Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==

 

 


 

Task 5 — Windows Azure Data Storage — Blob Sample Files

 

In this task you will review the contents of the default PHP Blob sample files provided by toolkit when creating a PHP Windows Azure Web Project intended for using Windows Azure Data Storage.

 

When creating a PHP Windows Azure Web Project and setting Data Storage Option to None, the toolkit will include within the Web Role project only one PHP sample file: index.php, which is essentially Hello World header and phpinfo().

 

When creating a PHP Windows Azure Web Project and setting Data Storage Option to Windows Azure Data Storage, the toolkit will include within the Web Role project these sample files:

 

Default Blob Sample Files

BlobSample.php

A boiler-plate PHP sample file to get started using Blob Services within Windows Azure Data Storage programming with Windows Azure SDK for PHP.

index.php

Essentially a simple phpinfo() page and provides a link to perform Windows Azure blob storage operations by loading boiler-plate PHP sample file BlobSample.php.

WindowsAzure.jpg

Sample image file used to demonstrate what an Azure Blob can store.

WindowsAzureAccountInfo.php

This configuration file defines Windows Azure Storage Account information for dev and cloud storage.

 

Blob Sample Code Review

BlobSample.php's code is broken into two parts:

  1. Building and Managing a Blob Container
  2. Applying Signed Access Signature to Blob Container

 

All actions performed within the sample are printed within the browser.

Building and Managing a Blob Container

The initial code within BlobSample.php does the following:

  1. Create a blob container.
  2. Apply modifications to blob container that is initially only visible by its owner.
  3. Make blob container public, thereby make it contents (blobs) viewable by anonymous users.

Begin code review...

  1. Construct Windows Azure Blob Storage Client
      Create an instance of class Microsoft_WindowsAzure_Storage_Blob.

     

    This storage client instance will provide blob storage access to the local Development Fabric and the Window Azure Cloud using their associated accounts defined in file ServiceConfiguration.cscfg.

  2. Cleanup of Storage Account
    1. Delete Container — "testcontainer" container if exists.
    2. Delete Container — "privatecontainer" container if exists.
    3. List Containers — Should be empty.
  3. Create and Modify Private Storage Account — Accessable only by the owner of the storage container.
    1. Create Container — "testcontainer" container.
    2. List Containers — Should contain "testcontainer" container.
    3. Put Blob — Put binary data of file WindowsAzure.jpg into "testcontainer" container with blob name "WindowsAzure.jpg".
    4. Put Blob — Put binary data of file WindowsAzure.jpg into "testcontainer" container with blob name "WindowsAzure2.jpg".
    5. Construct Blob URL —
      • Blob Service IP Address
      • + Blob name "WindowsAzure.jpg" in "testcontainer" container
    6. Print Blob URL in default browser.
    7. List Blobs — In "testcontainer" container.
    8. Set Blob Metadata — To blob "WindowsAzure.jpg" in "testcontainer" container.
    9. Get Blob Metadata — From blob "WindowsAzure.jpg" in "testcontainer" container.
    10. Get Blob — Download data from blob "WindowsAzure.jpg" in "testcontainer" container.
  4. Modify access to Storage Account — Give anonymous users read permissions to a container and its blobs, you can set the access control list (ACL) for the container to allow public access. Anonymous users can read blobs within a publicly accessible container without authenticating the request.
    1. Set Container ACL — Set access for "testcontainer" container to be "public".
    2. Now the previously printed Blob URL is now accessible to anonymous users.

Applying Signed Access Signature to Blob Container

The task here is to create a private blob container and apply it with a Shared Access Signature. This signature will be set the container to accessible only for a specified time interval.

 

  1. Create Container — "privatecontainer" container.
  2. Set Container ACL — Set access for "privatecontainer" container to be "private".
  3. Put Blob — Put binary data of file WindowsAzure.jpg into "privatecontainer" container with blob name "WindowsAzure.jpg".
  4. Construct Credentials
      Create an instance of class Microsoft_WindowsAzure_SharedAccessSignatureCredentials.

  5. Create Shared Access Signature — Using Credentials, create a signature valid for a time interval of 10 minutes.
  6. Construct Blob URL with Signature —
    • Blob Service IP Address
    • + Blob name "WindowsAzure.jpg" in "testcontainer" container
    • + Shared Access Signature
  7. Print Blob URL in default browser.

 


 

Task 6 — Run in local Development Fabric

 

In this task, you will run Blob Service locally in the Development Fabric.

 

  1. Start Development Fabric and Storage:
    1. Right-click its icon in the system tray and select Start Development Fabric Service
    2. Right-click its icon in the system tray and select Start Development Storage Service
  2. Start deployment of Web Role in local Development Fabric:
    1. Open PHP Explorer view
    2. Select either Service PHP project BlobStorage or Web Role PHP project BlobStorage_WebRole
    3. In Eclipse menu-bar, select Windows Azure menu.
    4. In Windows Azure menu, select Run in Development Fabric menu-item.
  3. When service begins:
    • Default browse should open and present the defaultDocument of index.php at the next available port, typically at URL http://127.0.0.1:81/index.php
    • Explorer should open to workspace folder of Service project BlobStorage.
    • Development Storage UI shows that Blob storage is Running.
  4. With defaultDocument opened to index.php, select link within:

     

    Click here to perform Windows Azure Blob Storage Operations.

     

  5. Within the browser, it should present results from actions executed within BlobSample.php.

     

    For review of expected Blob service actions performed, See Blob Sample Code Review

     

  6. Run BlobSample.php — Results example

    Windows Azure Blob Storage Operations

    List of Containers:

    New container with name 'testcontainer' is created.

    List of Containers:
    - testcontainer

    New blob with name 'WindowsAzure.jpg' is created.

    New blob with name 'WindowsAzure2.jpg' is created.

    Blob URL: http://127.0.0.1:10000/devstoreaccount1/testcontainer/WindowsAzure.jpg

    List of blobs in container 'testcontainer':
    - WindowsAzure.jpg
    - WindowsAzure2.jpg

    Set metadata for 'WindowsAzure.jpg' blob!

    metadata for 'WindowsAzure.jpg' blob:
    array(2) { ["createdby"]=> string(8) "PHPAzure" ["filetype"]=> string(3) "jpg" }

    Downloaded WindowsAzure.jpg blob to ...\deployment(57).BlobStorage.WebRole.0\...

    Made container 'testcontainer' public!

    SharedSignature for 'privatecontainer/WindowsAzure.jpg' with 10 minutes validity:
    http://127.0.0.1:10000/devstoreaccount1/privatecontainer/WindowsAzure.jpg?...

    Deleted blob 'WindowsAzure2.jpg' from container 'testcontainer'

     

  7. Within the BlobSample.php results, the Blob URL should point to WindowsAzure.jpg image from blob within 'testcontainer' container.

     

    Blob URL http://127.0.0.1:10000/devstoreaccount1/testcontainer/WindowsAzure.jpg

  8.  

Within Windows Azure Storage Explorer panel under Storage Account devstoreaccount1, two Blob Containers were created and each containing a Blob WindowsAzure.jpg.

 


 

Task 7 — Deploy to remote Windows Azure Cloud

 

In this task, you will run Blob Service remotely on Windows Azure using a Windows Azure Storage Account.

 

  1. Configure file WindowsAzureAccountInfo.php with your Cloud Storage account information.
    PHP — WindowsAzureAccountInfo.php default Cloud Storage account settings.
    /**
     * Windows Azure Storage Account for Cloud Environment
     */
    define('CLOUD_STORAGE_ACCOUNT', "MyAccountName");
    define('CLOUD_STORAGE_KEY', "MyAccountKey");
    

     

  2. Create a Windows Azure Service Package.
    1. Open PHP Explorer view
    2. Select either:
      • Service project BlobStorage
      • or Web Role project BlobStorage_WebRole
    3. In Eclipse menu-bar, select Windows Azure menu.
    4. In Windows Azure menu, select Package Application menu-item.

      This action will open a portal to Windows Azure, which will be gone in more detail later in this lab.

  3. When toolkit finishes creating Service Package, it opens default browser to Windows Live Sign-In in order to access your Windows Azure account.
  4. After sign-in, you are redirected to Windows Azure Portal
  5. Select deployment to Staging service.
  6. In Staging Deployment page
    1. From Service project BlobStorage workspace directory, browse to provide:
      • Application PackageBlobStorage.cspkg
      • Configuration SettingsServiceConfiguration.cscfg
    2. Set Service Deployment NameBlobStorage
    3. Select Deploy button and Staging begins copying over the two files for BlobStorage deployment.
  7. In Staging page, after deployment is Allocated, select Run button.
  8. In Staging page, after deployment is Started, select Web Site URL link.
  9. The Web Site URL from Staging Cloud should show the defaultDocument index.php.
  10. Select the link within index.php, and it should show the results from BlobSample.php.
  11. Within the BlobSample.php results, the Blob URL should point to WindowsAzure.jpg image from blob within 'testcontainer' container.

     

    Blob URL http://YOUR_ACCOUNT.blob.core.windows.net/testcontainer/WindowsAzure.jpg

  12.  

 


 

Part 2 — Windows Azure SDK for PHP — Blob Storage

 


 

 

Task 8 — Lab Files — Blob Storage

 

At this point of the lab, we will be focusing upon what Windows Azure SDK for PHP provides for handling Blob Storage.

 

Blob Storage is offered by Windows Azure as a REST API which is wrapped by the Windows Azure SDK for PHP in order to provide a native PHP interface to the storage account.

 

Blob Storage Example

Within this lab's download, there are two files we will be using within this task:

  1. BlobStorageExample.phpclass Blob_Storage_Example that encapsulates some of the key functionality of Windows Azure SDK for PHP.
  2. example.txt — Random latin text.

 

Copy files BlobStorageExample.php and example.txt into PHP project BlobStorage_WebRole.

 

Blob_Storage_Example::main()

Open file BlobStorageExample.php. Within class Blob_Storage_Example, there is a static function main() which will be used to execute example functions using Windows Azure SDK for PHP.

 

PHP — Blob_Storage_Example::main()
  /**
   * Main test body.
   * 
   * @return void
   */
  public static function main ()
  {
    self::setCLOUD_STORAGE_ACCOUNT(CLOUD_STORAGE_ACCOUNT);
    self::setCLOUD_STORAGE_KEY(CLOUD_STORAGE_KEY);
    self::setRUN_ON_PROD(false);
    
    $example = new Blob_Storage_Example();
    if(!$example->isValid()) {
      printf("%s::%d >> Failed %s\n", __METHOD__, __LINE__, "__construct");
      return;
    } 
    
    $strBlobContainerName = uniqid("testcontainer");
    $example->setBlobContainerName($strBlobContainerName);
    
    if (!$example->getBlobContainer($strBlobContainerName)) {
      printf("%s::%d >> Failed %s\n", __METHOD__, __LINE__, "getBlobContainer");
      return;
    }
 
    if (!$example->deleteBlobContainer($strBlobContainerName)) {
      printf("%s::%d >> Failed %s\n", __METHOD__, __LINE__, "deleteBlobContainer");
      return;
    }
    
    if (!$example->getBlobContainer($strBlobContainerName)) {
      printf("%s::%d >> Failed %s\n", __METHOD__, __LINE__, "getBlobContainer");
      return;
    }
    
    if (!$example->putBlob($strBlobContainerName, "example", "example.txt")) {
      printf("%s::%d >> Failed %s\n", __METHOD__, __LINE__, "putBlob");
      return;
    }
    
    if (!$example->getBlob($strBlobContainerName, "example", "example2.txt")) {
      printf("%s::%d >> Failed %s\n", __METHOD__, __LINE__, "getBlob");
      return;
    }
    
    if (!$example->copyBlob($strBlobContainerName, "example", 
                            $strBlobContainerName, "example2")) {
      printf("%s::%d >> Failed %s\n", __METHOD__, __LINE__, "copyBlob");
      return;
    }
    
    if (!$example->setBlobContainerPublic($strBlobContainerName)) {
      printf("%s::%d >> Failed %s\n", __METHOD__, __LINE__, "setBlobContainerPublic");
      return;
    }
    
    if (!$example->putBlobRootContainer("example", "example.txt")) {
      printf("%s::%d >> Failed %s\n", __METHOD__, __LINE__, "putBlobRootContainer");
      return;
    }
    
    printf("Success\n");
  }

 

Run Blob Storage Example

To execute provided Blob Storage example, perform either:

  1. Select file BlobEntityExample.php, and Run or Debug as PHP Script within Eclipse.
  2. OR, open command window within directory PHP project BlobStorage_WebRole, and execute php BlobEntityExample.php.

If everything goes well, then execution of BlobEntityExample.php should end with "Success".

 

 

Console — Executing PHP Script TableEntityExample.php
  Blob_Storage_Example::main
  Blob_Storage_Example::__construct
  Blob_Storage_Example::doCreateBlobStorageClient
  Unique Blob Container name: testcontainer4b16f1c7985f1
  Blob_Storage_Example::doDeleteAllBlobContainers
  Blob_Storage_Example::doGetBlobContainer
  Blob_Storage_Example::doDeleteBlobContainer
  Blob_Storage_Example::doGetBlobContainer
  Blob_Storage_Example::doListBlobContainers
  Blob Container name is: testcontainer4b16f1c7985f1
  Blob_Storage_Example::doAllBlobContainerMetadata
  Blob Container name is: testcontainer4b16f1c7985f1
  Array
  (
      [blobcontainer_key1] => value1
      [blobcontainer_key2] => value2
  )
  Blob_Storage_Example::doPutBlob
  Blob_Storage_Example::doGetBlobContainer
  Blob_Storage_Example::doGetBlob
  Blob_Storage_Example::doCopyBlob
  Blob_Storage_Example::doGetBlobContainer
  Blob_Storage_Example::doListBlobs
  Blob name is: example
  Blob name is: example2
  Blob_Storage_Example::doAllBlobMetadata
  Blob name is: example
  Array
  (
      [blob_key1] => value1
      [blob_key2] => value2
  )
  Blob name is: example2
  Array
  (
      [blob_key1] => value1
      [blob_key2] => value2
  )
  Blob_Storage_Example::doSetBlobContainerPublic
  Blob_Storage_Example::doDeleteBlob
  Blob_Storage_Example::doDeleteBlob
  Blob_Storage_Example::doPutBlobRootContainer
  Blob_Storage_Example::doGetBlobContainer
  Success
  Blob_Storage_Example::__destruct
  Blob_Storage_Example::doDeleteBlobContainer

 


 

Task 9 — SDK — Blob Container Methods

 

The focus of this task is upon the key methods that pertain specifically to blob containers, and not blobs.

 

Blob Storage Client

Create Instance

To start using Blob Storage, you need to create a Blob Storage client by creating an instance of class Microsoft_WindowsAzure_Storage_Blob.

 

This class encapsulates support for Windows Azure Storage's Blob Services.

 

It is an extension of class Microsoft_WindowsAzure_Storage which encapsulates a storage host's policy, credentials, and proxy; and it contains constants for use within cloud or development environment.

 

Method Microsoft_WindowsAzure_Storage_Blob::__construct() is called when instance is created.

 

Retry Policy

Method Microsoft_WindowsAzure_RetryPolicy::retryN() creates a retry policy, which is an instance of class Microsoft_WindowsAzure_RetryPolicy_RetryN.

 

The retry policies are there to help your application to perform storage operations even if the network is unreliable. Each of the policies works a different way, but generally they attempt to retry operations against storage that fail.

 

For example, if the failure is network-related, then trying again should succeed.

 

PHP — Create Blob Storage Client
  /**
   * Create a Blob Storage Client
   * 
   * @return boolean True upon success
   */
  public function doCreateBlobStorageClient() 
  {
    self::_doDisplay( __METHOD__ . "\n" );
    
    $fSuccess = false;
        
    try {  
      if (isset($_SERVER['USERDOMAIN']) && $_SERVER['USERDOMAIN'] == 'CIS')
      {
        $host = Microsoft_WindowsAzure_Storage::URL_CLOUD_BLOB;
        $accountName = CLOUD_STORAGE_ACCOUNT;
        $accountKey = CLOUD_STORAGE_KEY;
        $usePathStyleUri = true; 
    
        $retryPolicy = Microsoft_WindowsAzure_RetryPolicy::retryN(10, 250);
        
        $blobStorageClient = new Microsoft_WindowsAzure_Storage_Blob(
                                        $host,
                                        $accountName,
                                        $accountKey,
                                        $usePathStyleUri,
                                        $retryPolicy
                                        );
      }
      else
      {
        $blobStorageClient = new Microsoft_WindowsAzure_Storage_Blob();
      }
 
      $this->storageClient = $blobStorageClient;
      
      $fSuccess = true;
      
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    } catch ( Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    }
    
    return $fSuccess;
  }

 

Creating a Blob Container

 

PHP — Creating Blob Containiner
  /**
   * Get Blob Container
   *
   * @param IN string $strBlobContainerName
   * @param OUT Microsoft_WindowsAzure_Storage_BlobContainer $objBlobContainer
   * @return boolean True upon success
   */
  public function getBlobContainer(  
                      $strBlobContainerName,
                      &$_objBlobContainer = null
                    )
  {
    echo __METHOD__ . "\n";
    
    $fSuccess = false;
    
    if (!is_string($strBlobContainerName) || empty($strBlobContainerName) ) {
      throw new Exception('Invalid Parameter: strBlobContainerName.');
    }
    
    try {
       $objBlobContainer = null;
       
      if(!$this->_storageClient->containerExists($strBlobContainerName)) {
        $objBlobContainer = $this->_storageClient->createContainer($strBlobContainerName);
      } else {
        $objBlobContainer = $this->_storageClient->getContainer($strBlobContainerName);
      }
 
      if( !is_null($objBlobContainer) ) {
        $fSuccess = true;
        if (!is_null($_objBlobContainer) ) {
          $_objBlobContainer = $objBlobContainer;
        }
      }
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    } catch ( Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    }
    
    return $fSuccess;
  }

 

Within Windows Azure Storage Explorer panel under Storage Account devstoreaccount1, Blob storage has a new Blob Container testcontainer.

 

Deleting a Blob Container

 

PHP — Deleting Blob Containiner
  /**
   * Delete Blob Container
   * 
   * @param string $strBlobContainerName
   * @return boolean True upon success
   */
  public function doDeleteBlobContainer($strBlobContainerName)
  {
    self::_doDisplay( __METHOD__ . "\n" );
    
    if (!is_string($strBlobContainerName) || empty($strBlobContainerName) ) {
      throw new Exception('Invalid Parameter: strBlobContainerName.');
    }
    
    $fSuccess = false;
    try {
      
      if($this->storageClient->containerExists($strBlobContainerName)) {
        $this->storageClient->deleteContainer($strBlobContainerName);
      }
      
      $fSuccess = !$this->storageClient->containerExists($strBlobContainerName);
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    } catch ( Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    }
    
    return $fSuccess;
  }

 

Listing Blob Containers

 

PHP — Listing Blob Containiners
  /**
   * List Blob Containers with Blob Storage account
   * 
   * @return boolean True upon success
   */
  public function doListBlobContainers() {
    self::_doDisplay( __METHOD__ . "\n" );
    
    $fSuccess = false;
    
    try {
      $aBlobContainer = $this->storageClient->listContainers();
      foreach ($aBlobContainer as $objBlobContainer)
      {
        self::_doDisplay( 'Blob Container name is: ' . $objBlobContainer->Name . "\n" );
      }
        
      $fSuccess = true;
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    } catch ( Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    }
    
    return $fSuccess;
  }

 

Delete All Blob Containers

 

PHP — Delete All Blob Containers
  /**
   * Delete all Blob Containers with Blob Storage account
   * 
   * @return boolean True upon success
   */
  public function doDeleteAllBlobContainers() {
    self::_doDisplay( __METHOD__ . "\n" );
    
    $fSuccess = false;
    
    try {
      $aBlobContainer = $this->storageClient->listContainers();
      foreach ($aBlobContainer as $objBlobContainer)
      {
        $strBlobContainerName = $objBlobContainer->Name;
        $this->storageClient->deleteContainer($strBlobContainerName);
      }
        
      $fSuccess = true;
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    } catch ( Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    }
    
    return $fSuccess;
  }

 

Setting and Getting Blob Container Metadata

 

PHP — Set and Get metadata for all Blob Containers
  /**
   * Set and Get metadata for all Blob Containers
   * 
   * @return boolean True upon success
   */
  public function doAllBlobContainerMetadata() {
    self::_doDisplay( __METHOD__ . "\n" );
    
    $fSuccess = false;
    
    $aMetaDataIN = array();
    $aMetaDataIN['BlobContainer_key1'] = 'value1';
    $aMetaDataIN['BlobContainer_key2'] = 'value2';
    
    try {
      $aBlobContainer = $this->storageClient->listContainers();
      foreach ($aBlobContainer as $objBlobContainer)
      {
        $strBlobContainerName = $objBlobContainer->Name;
        $this->storageClient->setContainerMetadata($strBlobContainerName, $aMetaDataIN);
      }
      
      foreach ($aBlobContainer as $objBlobContainer)
      {
        $strBlobContainerName = $objBlobContainer->Name;
        $aMetaDataOUT = $this->storageClient->getContainerMetadata($strBlobContainerName);
        
        self::_doDisplay( print_r($aMetaDataOUT, true));
      }
        
      $fSuccess = true;
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    } catch ( Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    }
    
    return $fSuccess;
  }

Setting a Blob Container to have Public Access

By default, Blob Containers on Windows Azure are protected from public viewing, in other words, private.

 

To allow public viewing of the blob contents within a Blob Container, its ACL has to be set to public.

 

 

PHP — Setting Blob Container Access to Public
  /**
   * Set Blob Container access to Public.
   * 
   * @param string $strBlobContainerName
   * @return boolean True upon success
   */
  public function setBlobContainerPublic($strBlobContainerName) {
    $fSuccess = false;
    
    if (  !is_string($strBlobContainerName) || 
          empty($strBlobContainerName) || 
          !$this->_storageClient->containerExists($strBlobContainerName)
          ) {
      throw new Exception('Invalid Parameter: strBlobContainerName.');
    }
 
    
    try {
      $this->_storageClient->setContainerAcl(
                                    $strBlobContainerName, 
                                    Microsoft_WindowsAzure_Storage_Blob::ACL_PUBLIC 
                                    );
                                          
      $fACL = $this->_storageClient->getContainerAcl($strBlobContainerName);
      
      $fSuccess = (Microsoft_WindowsAzure_Storage_Blob::ACL_PUBLIC == $fACL);
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    } catch ( Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    }
    
    return $fSuccess;
  }

 

Within Windows Azure Storage Explorer panel under Storage Account devstoreaccount1, the properties of Blob Container testcontainer now shows Public with value of Yes.

 

With Blob Container testcontainer now Public, Blob example is now viewable to the public.

 

To view Blob example, the URL is a concatenation of:

  • Protocol http://
  • Development Blob Storage URL 127.0.0.1:10000
  • Development Storage account name devstoreaccount1
  • Blob Container name testcontainer
  • Blob name example

 

URL — Blob 'example' within public Blob Container 'testcontainer'
http://127.0.0.1:10000/devstoreaccount1/testcontainer/example

 

Now that Blob Container 'testcontainer' is Public, Blob 'example' is publicly viewable.

 

 

Creating a Root Container

Windows Azure Blob Storage provides support to work with a "root container". This means that a blob can be stored in the root of your Blob storage account, i.e. http://myaccount.blob.core.windows.net/somefile.txt.

 

In order to work with the root container, it should first be created using the createContainer() method, naming the container $root. All other operations on the root container should be issued with the container name set to $root.

 

PHP — Create '$root' Blob Container
  /**
   * Put File as Blob into Root Blob Container.
   * 
   * @param string $strBlobName
   * @param string $strFilePath
   * @return boolean True upon success
   */
  public function putBlobRootContainer( $strBlobName,
                                        $strFilePath
                                        ) {
    $fSuccess = false;
    
    if ( !is_string($strBlobName) || empty($strBlobName) ) {
      throw new Exception('Invalid Parameter: strBlobName.');
    }
    
    if ( !is_string($strFilePath) || empty($strFilePath) || 
         !file_exists($strFilePath) ) {
      throw new Exception('Invalid Parameter: strFilePath.');
    }
    
    try {
      
      if (self::getBlobContainer('$root')) {
        $this->_storageClient->putBlob( '$root', 
                                            $strBlobName, 
                                            $strFilePath
                                            );
                                            
        $this->_storageClient->setContainerAcl(
                                    '$root', 
                                    Microsoft_WindowsAzure_Storage_Blob::ACL_PUBLIC 
                                    );
                                            
        $fSuccess = $this->_storageClient->blobExists( '$root',
                                                           $strBlobName
                                                            );
      }
 
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    } catch ( Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    }
    return $fSuccess;
  }

 

Here is the Blob URL that is accessible from the '$root' Blob Container.

URL — Blob 'example' in Root Container
http://127.0.0.1:10000/devstoreaccount1/example

 

Now that Blob Container '$root' is Public, Blob 'example' is publicly viewable from root.

 


 

Task 10 — SDK — Blob Methods

 

Put a Blob in a Blob Container

 

PHP — Put Blob in Blob Container
  /**
   * Put File as Blob into a Blob Container.
   * 
   * @param string $strBlobContainerName
   * @param string $strBlobName
   * @param string $strFilePath
   * @return boolean True upon success
   */
  public function putBlob(  $strBlobContainerName,
                            $strBlobName,
                            $strFilePath
                          )
  {
    $fSuccess = false;
    
    if ( !is_string($strBlobContainerName) || empty($strBlobContainerName) ) {
      throw new Exception('Invalid Parameter: strBlobContainerName.');
    }
    if ( !is_string($strBlobName) || empty($strBlobName) ) {
      throw new Exception('Invalid Parameter: strBlobName.');
    }
    
    if ( !is_string($strFilePath) || empty($strFilePath) || 
         !file_exists($strFilePath) ) {
      throw new Exception('Invalid Parameter: strFilePath.');
    }
    
    try {
      
      if (self::getBlobContainer($strBlobContainerName)) {
        $this->_storageClient->putBlob( $strBlobContainerName, 
                                            $strBlobName, 
                                            $strFilePath
                                            );
                                            
        $fSuccess = $this->_storageClient->blobExists( $strBlobContainerName,
                                                           $strBlobName
                                                         );
      }
 
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    } catch ( Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    }
    return $fSuccess;
  }

 

Within Windows Azure Storage Explorer panel under storage account devstoreaccount1, Blob Container testcontainer now has a new Blob example.

 

Get a Blob from a Blob Container

PHP — Get Blob from Blob Container
  /**
   * Get Blob in a Blob Container.
   * 
   * @param string $strBlobContainerName
   * @param string $strBlobName
   * @param string $strFilePath
   * @return boolean True upon success
   */
  public function getBlob(  $strBlobContainerName,
                            $strBlobName,
                            $strFilePath
                          )
  {
    $fSuccess = false;
    
    if (  !is_string($strBlobContainerName) || 
          empty($strBlobContainerName) || 
          !$this->_storageClient->containerExists($strBlobContainerName)
          ) {
      throw new Exception('Invalid Parameter: strBlobContainerName.');
    }
    
    if (  !is_string($strBlobName) || 
          empty($strBlobName) || 
          !$this->_storageClient->blobExists($strBlobContainerName, $strBlobName)
          ) {
      throw new Exception('Invalid Parameter: strBlobName.');
    }
    
    try {
      if (file_exists($strFilePath)) {
        unlink($strFilePath);
      }
      
      $this->_storageClient->getBlob(
                                    $strBlobContainerName,
                                    $strBlobName,
                                    $strFilePath );
                                    
      $fSuccess = file_exists($strFilePath);
      
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    } catch ( Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    }
    
    return $fSuccess;
  } 

 

Deleting a Blob

 

PHP — Deleting Blob Instance within a Blob Container
  /**
   * Delete Blob within a Blob Container.
   * 
   * @param string $strBlobContainerName
   * @param string $strBlobName
   * @return boolean True upon success
   */
  public function doDeleteBlob(   $strBlobContainerName,
                                  $strBlobName
                                  )
  {
    self::_doDisplay( __METHOD__ . "\n" );
    $fSuccess = false;
 
    try {
      $this->storageClient->deleteBlob (
                                    $strBlobContainerName,
                                    $strBlobName
                                    );
                                    
      $fSuccess = !$this->storageClient->blobExists($strBlobContainerName, $strBlobName);
      
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    } catch ( Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    }
    
    return $fSuccess;
  } 

 

Listing Blobs in a Blob Container

 

PHP — List Blob Instances within a Blob Container
  /**
   * List Blob Instances within a Blob Container
   * 
   * @param string $strBlobContainerName
   * @return boolean True upon success
   */
  public function doListBlobs($strBlobContainerName) {
    self::_doDisplay( __METHOD__ . "\n" );
    
    $fSuccess = false;
    
    try {
      $aBlobInstances = $this->storageClient->listBlobs($strBlobContainerName);
      foreach ($aBlobInstances as $objBlobInstance)
      {
        self::_doDisplay( 'Blob name is: ' . $objBlobInstance->Name . "\n" );
      }
        
      $fSuccess = true;
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    } catch ( Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    }
    
    return $fSuccess;
  }

 

Setting and Getting Blob Metadata

 

PHP — Set and Get metadata for all Blobs within a Blob Container
  /**
   * Set and Get metadata for all Blobs within a Blob Container
   * 
   * @param string $strBlobContainerName
   * @return boolean True upon success
   */
  public function doAllBlobMetadata($strBlobContainerName) {
    self::_doDisplay( __METHOD__ . "\n" );
    
    $fSuccess = false;
    
    $aMetaDataIN = array();
    $aMetaDataIN['Blob_key1'] = 'value1';
    $aMetaDataIN['Blob_key2'] = 'value2';
    
    try {
      $aBlobInstances = $this->storageClient->listBlobs($strBlobContainerName);
      foreach ($aBlobInstances as $objBlobInstance)
      {
        $strBlobName = $objBlobInstance->Name;
        $this->storageClient->setBlobMetadata(  $strBlobContainerName, 
                                                $strBlobName, 
                                                $aMetaDataIN
                                                );
      }
      
      foreach ($aBlobInstances as $objBlobInstance)
      {
        $strBlobName = $objBlobInstance->Name;
        $aMetaDataOUT = $this->storageClient->getBlobMetadata(  $strBlobContainerName,
                                                                $strBlobName
                                                                );
        
        self::_doDisplay( 'Blob name is: ' . $strBlobName . "\n" );
        self::_doDisplay( print_r($aMetaDataOUT, true));
      }
        
      $fSuccess = true;
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    } catch ( Exception $e ) {
      self::_doDisplay( sprintf("Failed: %s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage()));
    }
    
    return $fSuccess;
  }

 

Copying a Blob within Blob Storage Account

  • Method Microsoft_WindowsAzure_Storage_Blob::copyBlob() — Copies a Blob instance within Blob Storage Account.

     

    The advantage of using this method is that the copy operation occurs in the Azure cloud and does not involve downloading the blob.

 

PHP — Copy Blob within Blob Storage Account
  /**
   * Copy Blob within Blob Storage Account.
   * 
   * @param string $strBlobContainerNameSrc
   * @param string $strBlobNameSrc
   * @param string $strBlobContainerNameDest
   * @param string $strBlobNameDest
   * @return boolean True upon success
   */
  public function copyBlob( $strBlobContainerNameSrc,
                            $strBlobNameSrc,
                            $strBlobContainerNameDest,
                            $strBlobNameDest
                          )
  {
    $fSuccess = false;
    
    if (  !is_string($strBlobContainerNameSrc) || 
          empty($strBlobContainerNameSrc) || 
          !$this->_storageClient->containerExists($strBlobContainerNameSrc)
          ) {
      throw new Exception('Invalid Parameter: strBlobContainerNameSrc.');
    }
    
    if (  !is_string($strBlobNameSrc) || 
          empty($strBlobNameSrc) || 
          !$this->_storageClient->blobExists( $strBlobContainerNameSrc, 
                                                  $strBlobNameSrc
                                                  )
          ) {
      throw new Exception('Invalid Parameter: strBlobNameSrc.');
    }
    
    try {
      if (self::getBlobContainer($strBlobContainerNameDest)) {
        $objBlob = $this->_storageClient->copyBlob( 
                                            $strBlobContainerNameSrc,
                                            $strBlobNameSrc, 
                                            $strBlobContainerNameDest, 
                                            $strBlobNameDest
                                            );
                                            
        $fSuccess = $this->_storageClient->blobExists( $strBlobContainerNameDest,
                                                            $strBlobNameDest
                                                            );
      }      
    } catch ( Microsoft_WindowsAzure_Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    } catch ( Exception $e ) {
      printf("%s::%d >> %s\n", __METHOD__, __LINE__, $e->getMessage());
    }
    
    return $fSuccess;
  }

Within Windows Azure Storage Explorer panel under Storage Account devstoreaccount1, Blob Container testcontainer has a new Blob 'example2', which is a copy of Blob 'example'.

 

 

 


 

Summary

 

In this lab, you have learned how to...

  1. Configure Blob Service to use Windows Azure Data Storage for both:
    • local Development Fabric
    • remote Windows Azure Cloud
  2. Use Windows Azure Blob Storage API through Windows Azure SDK for PHP to create an application that saves and retrieves image data stored as blobs.

 

Good job!! You are done with this Lab.