Microsoft Azure Blob API

From RAD Studio
Jump to: navigation, search
Warning: DSAzure API is deprecated and has been replaced by Data.Cloud.AzureAPI. You are encouraged to use the new API when developing cloud computing applications. See Cloud Computing with DataSnap for more information.

The Microsoft Azure Blob API is located in the Data.Cloud.AzureAPI unit, in the Data.Cloud.AzureAPI.TAzureBlobService class.

The principal available functions include:

  • Getting a list of containers
  • Creating a container, deleting a container
  • Creating a block blob
  • Creating a page blob
  • Modifying the content of a blob
  • Copying a blob
  • Deleting a blob
  • Creating a snapshot
  • Acquiring, renewing, breaking, or releasing a lease on a blob
  • Getting the properties and metadata of a blob or a container

The following instructions assume you already have an instance created of TAzureBlobService. In any code snippets, this instance is referred to as FBlobService. It is also assumed that you have an XML parser at hand and that it is already configured appropriately for use. The API in some cases returns an XML, which you need to know how to parse.

Container Actions

Containers have properties and metadata, and can own blobs. The following are a summary of the actions available with a container.

Create a Root Container

Having a root container allows you to provide a container address, which is shorter, as it has no container name in it. You can create a root container with the following code:

Success := FBlobService.CreateRootContainer(Access);

where Access is the value to be used in the 'x-ms-blob-public-access' header, which can be an empty string, container or blob, depending on if/how you want the information to be publicly accessible. If Access is left out, a default value of blob will be used. Alternatively, you can create a root container like this:

Success := FBlobService.CreateContainer('$root', MetaData, Access);

where MetaData is a TStringList of optional metadata for the root container. You can leave the MetaData parameter out altogether, as there is an overloaded function that omits it.

Once a root container is created, you can work with it as you would with any other container.

Create a Container

To create a regular container, use the same code as for creating a root container (the example above that uses the call to CreateContainer, passing in a name), except that you specify a name other than $root.

The container name must following these naming conventions:

  • Between 3 and 65 characters in length
  • Alpha-numeric and hyphen characters only
  • Cannot start with a hyphen
  • Lowercase only

Deleting a Container

To delete the root container, call:

Success := FBlobService.DeleteRootContainer;

To delete any other container, call:

Success := FBlobService.DeleteContainer('container-name');

where you pass in the container's actual name. Both of these functions return True if the deletion is successful, False otherwise.

Getting a list of all Containers

To get a list of all available containers, use the following code:

xmlStr := ListContainers(['include'], ['metadata']);

The parameters are two arrays:

  • An array of parameters to pass along with the request to the cloud.
  • An array of the values for the first array.

These two arrays should be the same length, as an item in the first array directly maps to the item at the same index of the other. In the above code, passing in the parameter include with value "metadata" says to include each container's metadata in the returned XML. This can be called with no parameters, and no metadata is returned. Another parameter you can specify in these arrays is maxresults, which allows you to limit the number of containers to return from this query.

The XML returned looks like this:

<?xml version="1.0" encoding="utf-8"?>
<EnumerationResults ...>

For a complete example of the returned XML, see the MSDN documentation in the See Also section.

In the above XML you will see that there is a Containers element that contains all of the Container items. Each container has a name, URL, properties, and metadata (if you chose to populate metadata.)

Getting Properties of a Container

You can see in the above XML that each container has properties associated with it. You can have these properties populated when you retrieve the list of all containers, but you can also re-populate the properties independently by using the following code:

Success := FBlobService.GetContainerProperties('container-name');
Props := TStringList.Create;
if Success then

With the above code, you now have a TStringList populated with the key/value property pairs, provided the initial request was successful.

Getting the Metadata of a Container

You can also see in the above XML that, when you retrieve the list of containers (setting the 'include' property as 'metadata'), you get a collection of key/value metadata pairs returned. The node name (metadata-name in the above example) is the actual metadata key. The value is, not unsurprisingly, the metadata key's corresponding value.

You can also get the metadata by itself for a specific container. To do this, use the following code:

Success := FBlobService.GetContainerMetadata('container-name');
Meta := TStringList.Create;
if Success then
  FBlobService.PopulateContainer('x-ms-meta-', Meta);

The initial call to GetContainerMetadata returns True if the call was successful. PopulateContainer then uses data collected from the previous call to populate the given TStringList with the metadata key/value pairs. Metadata is returned in the header of the response from the server, and each metadata key is prefixed with x-ms-meta-. The remainder of the key name is the actual metadata key name. The PopulateContainer procedure can take any prefix and populate a TStringList based on headers using that specified string as a prefix to filter out the header key/value pairs that are added to the list.

Modifying Metadata on a Container

To modify the metadata stored on a container, you can first use the above code to get a TStringList populated with the latest metadata, then modify that TStringList to add new metadata key/value pairs and/or modify/delete existing pairs. Then you can use the following code to commit these changes to the cloud:

Success := FBlobService.SetContainerMetadata('container-name', Meta);

where Meta is the TStringList with the key/value pairs you want to commit. True is returned if the update was successful, False otherwise. Note that, for the root container, you should specify '$root' as the name.

Note: You can also create Page Blobs and Block Blobs to store within containers. These are described in #Page Blob Actions and #Block Blob Actions.
Note: You cannot modify a container's properties.

General Blob Actions

The following actions are available on both Page Blobs and Block Blobs. Block blobs are optimized for streaming, while Page blobs are optimized for random read/write operations.

Delete a Blob

You can delete a blob with the following code:

Success := FBlobService.DeleteBlob('container-name', 'blob-name');

DeleteBlob also has three optional parameters, which are: Snapshot, LeaseId, and DeleteSnapshots. DeleteSnapshots can be left blank(only if the blob has no associated snapshots) or be set to include or only. If set to include, the blob and all snapshots are deleted, if set to only, then only the blob's snapshots are deleted, but not the blob itself.

You can specify a value for Snapshot if you just want to delete a specific snapshot of the blob. You must specify a LeaseId to successfully delete the blob if a lease has been acquired and has not yet expired.

Copy Blob

You can copy a blob into any container in the same storage account as the blob being copied. If you are copying into the same container as the source, then you obviously need to specify a different name for the target blob.

To copy a blob, you can use the following code:

Success := FBlobService.CopyBlob('destination-container', 'destination-blob-name', 'source-container', 'source-blob-name');

You can also specify a specific snapshot of the blob to copy, a date-time value to check the last modified date against for the source blob, so the copy is only done if it has been modified since that date, an 'unmodified date' where the copy only happens if the source blob has not been modified since that date, and several other optional parameters. See the documentation on TAzureBlobService or view the code in the DSAzure unit to see all of the optional parameters. Also note that one of the optional parameters is LeaseId, which would be for the target blob, in case one already exists there and a lease has been acquired for it.

Create a Snapshot

You can create a snapshot of a blob with the following code:

snapshot := FBlobService.SnapshotBlob('container-name', 'blob-name');

SnapshotBlob takes additional optional parameters of (in this order): IfModifiedSince, IfUnmodifiedSince, IfMatch, IfNoneMatch, LeaseId, MetaHeaders.

If you wanted to get an XML representation of the full blob, including any snapshot information, use this modified call to ListBlobs:

xml := FBlobService.ListBlobs('container-name', ['prefix', 'include', 'include'], ['blob-name', 'metadata', 'snapshots']);

where you'd substitute 'container-name' and 'blob-name' for their actual values.

Work with Leases

With all blobs you can acquire leases, renew leases, release leases, and break leases. When you successfully acquire a lease on a blob, you are able to have exclusive write access to that blob and its properties/metadata for one minute. Before the minute ends, you can choose to release the lease if you no longer need it, or renew the lease if you need another 60 seconds. You can continually renew the lease until someone chooses to break lease on the blob. When a breaking of a lease is requested, the remainder of the current minute is allowed to finish, but then no more renewing of the lease for that lease ID can happen.

Acquiring a Lease

To acquire a lease on a blob, use the following code:

LeaseId := FBlobService.LeaseBlob('container-name', 'blob-name');

With the lease ID returned, you can modify, renew, and release a lease, as all of these actions had an 'optional' parameter of LeaseID, which becomes a required parameter when the blob is leased to someone.

Renewing a Lease

To renew a lease, use the following code:

FBlobService.LeaseBlob('container-name', 'blob-name', 'renew', LeaseId);

This call is similar to the call used when you initially created the lease, but has two additional parameters. The first parameter states that the type of action is a renew and the second parameter is the LeaseId you got when acquiring the lease. If this succeeds, you will be given an additional 60 seconds protected write access to the blob and its data.

Breaking a Lease

To break a lease that someone else has acquired (or yourself, if for some reason you do not want to just release the lease), you can use the following code:

FBlobService.LeaseBlob('container-name', 'blob-name', 'break');
duration := StrToInt(FBlobService.ResponseHeader['x-ms-lease-time']);

This breaks the lease, leaving the blob in an unlocked state after the number of seconds specified by duration.

Releasing a Lease

If you have acquired a lease on a blob, then you can choose to release it before the lease expires. To do this, use the following code:

FBlobService.LeaseBlob('container-name', 'blob-name', 'release', LeaseId);

This releases the lease on the specified blob, provided that the LeaseId is correct.

Download the Blob Content

You can download the blob content with the following code:

stream := TFileStream.Create(location, fmCreate);
Success := FBlobService.GetBlob('container-name', 'blob-name', stream); 

You can also specify an optional fourth parameter of the Blob Snapshot to download. Note that if the GetBlob call returns False, you can get the message returned by the server from FBlobService.ResponseText.

Get Blob Properties

Getting a blob's properties is similar to getting the properties of a container. The code looks like this:

Success := FBlobService.GetBlobProperties('container-name', 'blob-name');
Props := TStringList.Create;
if Success then

The call to GetBlobProperties can take an optional third parameter, which specifies a snapshot to get the properties for instead of the Blob itself. The call to GetBlobProperties returns True if successful, and then you can call PopulateContainerProperties to populate the actual properties.

Get Blob Metadata

Populating the Metadata for a blob is also similar to the same action on a container. You can accomplish this with the following code:

Success := FBlobService.GetBlobMetadata('container-name', 'blob-name');
Meta := TStringList.Create;
if Success then
  FBlobService.PopulateContainer('x-ms-meta-', Meta);

GetBlobMetadata also has the optional third option of a Snapshot to get the metadata for instead of the Blob itself.

Set Blob Properties

You can set the system properties for a blob with the following code:

Success := FBlobService.SetBlobProperties('container-name', 'blob-name', cache, contentType, encoding, language, md5, LeaseId);

All but the first two properties are optional, and they are all strings. (LeaseId must be specified if the blob has a lease acquired for it, and must not be specified if the blob has no active lease.)

Modify Blob Metadata

Modifying the metadata stored on a blob is quite similar to modifying the metadata for a container. Here is an example of the code:

Success := FBlobService.SetBlobMetadata('container-name', 'blob-name', Meta);

The Meta parameter is the key/value pairs of metadata. There is an optional fourth parameter, which is the LeaseId. This must be specified if there is an active acquired lease on the blob.

Block Blob Actions

The following are actions specific to Block Blobs:

  • Creating a Block Blob

To create a new block blob, use the following code:

Success := FBlobService.PutBlockBlob('container-name', 'blob-name', ContentBytes);

where ContentBytes is a TBytes instance that will be used as the blob's content. Optional parameters for PutBlockBlob are, in order, as follows: LeaseId, UserHeaders, ContentType, ContentEncoding, ContentLanguage, ContentMD5. You can find information about these optional parameters in the MSDN documentation below. Note that application/octet-stream is used as the content type if none is specified.

  • Updating Block Blob Content

After a block blob is created, you can modify any of its values. To do this, use the exact same code that you did for creating the blob. LeaseId becomes a useful parameter in this case, as you do not need a LeaseId for a blob that has not been created.

Page Blob Actions

The following is an action specific to Page Blobs:

  • Creating a Page Blob

To create a new page blob, use Data.Cloud.AzureAPI.TAzureBlobService.PutPageBlob as in the following code:

Success := FBlobService.PutPageBlob('container-name', 'blob-name', BlobSize);

Optional parameters (in order) include: ContainerName, BlobName, MaximumSize, LeaseID, OptionalHeaders, MetaData, ResponseInfo. View the MSDN documentation below to better understand these optional parameters. Note that application/octet-stream is used as the content type if none is specified.

See Also