Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.6.0+

Azure Blob: List Versions and Recover Deleted Content

See more Azure Cloud Storage Examples

For a flat-namespace account, list the versions, snapshots and soft-deleted entries for one blob. Keep version IDs and snapshot timestamps as strings. The default action only lists choices; change action deliberately to undelete, restore-version or restore-snapshot and supply the selected ID.

Undelete recovers eligible soft-deleted content within its retention period. When versioning is enabled, undelete does not automatically make an older version the current base blob: restore the selected live version by copying it to the base name. A deleted snapshot/version may first require undelete. Restoring over an existing base requires its current quoted ETag; otherwise this example only creates an absent base. Retention expiration, permanent deletion and immutability policies can prevent recovery. Hierarchical-namespace accounts use a different recovery workflow with deletion IDs.

Uses direct Chilkat.Rest requests and Azure public-cloud endpoints with verified HTTPS. REST requests select service version 2026-04-06. Create local input/output directories before running. Account-key examples read account and access_key string fields from private qa_data/azure/storage.json; do not embed secrets in distributed applications. Entra examples explain their own configuration. Keep credentials, bearer tokens, SAS URLs and diagnostic dumps private. Shared Key is supported only where allowed by account policy; Entra authentication is preferred where available.

Transport success and HTTP status are checked separately. Writes are not automatically replayed after an uncertain response. IDs, ETags, continuation markers and file sizes are strings; counters and explicitly bounded offsets use int. No webhook or web server is required.

Microsoft reference.

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

'  StringBuilder compares text by value in every generated language.
Dim textCompare As ChilkatStringBuilder
textCompare.Initialize
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
Dim config As ChilkatJsonObject
config.Initialize
config.Strict = True
success = config.LoadFile("qa_data/azure/storage.json")
If success <> True Then
    Log("Could not load private Azure configuration.")
    Return
End If

textCompare.Clear
textCompare.SetString(config.StringOf("account"))
Dim sameText1 As Boolean = textCompare.ContentsEqual("", True)
If (config.JsonTypeOf("account") <> 1) Or (sameText1 = True) Then
    Log("Supply the storage account name.")
    Return
End If

'  access_key is the base64 account key, not a connection string or SAS.
textCompare.Clear
textCompare.SetString(config.StringOf("access_key"))
Dim sameText2 As Boolean = textCompare.ContentsEqual("", True)
If (config.JsonTypeOf("access_key") <> 1) Or (sameText2 = True) Then
    Log("Supply the base64 account access key.")
    Return
End If

Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
success = endpoint.Append(config.StringOf("account"))
If success <> True Then
    Log("Could not prepare the request.")
    Return
End If

success = endpoint.Append(".blob.core.windows.net")
If success <> True Then
    Log("Could not prepare the request.")
    Return
End If

'  resourcePath is already URL-encoded. Encode each path segment once when adapting it.
'  Keep slash separators; names and paths are case-sensitive.
Dim resourcePath As String = "/examplecontainer"
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
Dim azAuth As ChilkatAuthAzureStorage
azAuth.Initialize
azAuth.Account = config.StringOf("account")
azAuth.AccessKey = config.StringOf("access_key")
azAuth.Service = "Blob"
azAuth.Scheme = "SharedKey"
azAuth.XMsVersion = "2026-04-06"
success = rest.SetAuthAzureStorage(azAuth)
If success <> True Then
    Log("Could not configure Shared Key signing.")
    Return
End If

Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
    Log("TLS connection failed; inspect diagnostics privately.")
    Return
End If

'  Do not replay a write automatically after losing its response.
success = rest.UseConnection(connection, False)
If success <> True Then
    Log("Could not prepare the request.")
    Return
End If

Dim responseText As String
Dim result As ChilkatXml
result.Initialize
result.Strict = True
'  Flat-namespace Blob account. Default is inspection only.
'  Choose list, undelete, restore-version, or restore-snapshot.
Dim action As String = "list"
Dim selectedId As String = ""
'  For restoring over an existing base blob, supply its current quoted ETag.
'  Empty means restore only when the base blob is absent.
Dim destinationEtag As String = ""
success = rest.AddQueryParam("restype", "container")
If success <> True Then
    Log("Could not prepare the request.")
    Return
End If

success = rest.AddQueryParam("comp", "list")
If success <> True Then
    Log("Could not prepare the request.")
    Return
End If

success = rest.AddQueryParam("prefix", "example.bin")
If success <> True Then
    Log("Could not prepare the request.")
    Return
End If

success = rest.AddQueryParam("include", "versions,snapshots,deleted,deletedwithversions")
If success <> True Then
    Log("Could not prepare the request.")
    Return
End If

success = rest.AddQueryParam("maxresults", "1000")
If success <> True Then
    Log("Could not prepare the request.")
    Return
End If

Dim seenMarkers As ChilkatHashtable
seenMarkers.Initialize
Dim marker As String = ""
Dim more As Boolean = True
Dim page As Int = 0
Do While (more = True)
    If page >= 1000 Then
        Log("Page limit reached; results are incomplete. Save the continuation marker.")
        Return
    End If

    responseText = rest.FullRequestNoBody("GET", resourcePath)
    If rest.LastMethodSuccess <> True Then
        Log("Request did not complete; outcome may be uncertain.")
        Return
    End If

    If rest.ResponseStatusCode <> 200 Then
        Log("HTTP status: " & rest.ResponseStatusCode)
        Log("Azure error code: " & rest.ResponseHdrByName("x-ms-error-code"))
        Log("Request ID: " & rest.ResponseHdrByName("x-ms-request-id"))
        '  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
        Return
    End If

    success = result.LoadXml(responseText)
    If success <> True Then
        Log("Expected well-formed XML.")
        Return
    End If

    If result.TagEquals("EnumerationResults") <> True Then
        Log("Unexpected XML response root.")
        Return
    End If

    Dim count As Int = result.NumChildrenAt("Blobs")
    Dim i As Int = 0
    Do While (i < count)
        result.I = i
        textCompare.Clear
        textCompare.SetString(result.GetChildContent("Blobs|Blob[i]|Name"))
        Dim sameText3 As Boolean = textCompare.ContentsEqual("example.bin", True)
        If sameText3 = True Then
            Log("Version ID: " & result.GetChildContent("Blobs|Blob[i]|VersionId"))
            Log("Snapshot: " & result.GetChildContent("Blobs|Blob[i]|Snapshot"))
            Log("Deleted: " & result.GetChildContent("Blobs|Blob[i]|Deleted"))
            Log("Current version: " & result.GetChildContent("Blobs|Blob[i]|IsCurrentVersion"))
            Log("Has versions only: " & result.GetChildContent("Blobs|Blob[i]|HasVersionsOnly"))
        End If

        i = i + 1
    Loop
    marker = result.GetChildContent("NextMarker")
    page = page + 1
    textCompare.Clear
    textCompare.SetString(marker)
    Dim sameText4 As Boolean = textCompare.ContentsEqual("", True)
    If sameText4 = True Then
        more = False
    Else
        If seenMarkers.Contains(marker) = True Then
            Log("Repeated marker; results are incomplete.")
            Return
        End If

        success = seenMarkers.AddInt(marker, 1)
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        If page > 1 Then
            success = rest.RemoveQueryParam("marker")
            If success <> True Then
                Log("Could not prepare the request.")
                Return
            End If

        End If

        success = rest.AddQueryParam("marker", marker)
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        rest.Disconnect(10)
        success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
        If success <> True Then
            Log("TLS reconnection failed.")
            Return
        End If

        success = rest.UseConnection(connection, False)
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

    End If

Loop
textCompare.Clear
textCompare.SetString(action)
Dim sameText5 As Boolean = textCompare.ContentsEqual("list", True)
If sameText5 <> True Then
    success = rest.ClearAllQueryParams
    If success <> True Then
        Log("Could not prepare the request.")
        Return
    End If

    resourcePath = "/examplecontainer/example.bin"
    textCompare.Clear
    textCompare.SetString(action)
    Dim sameText6 As Boolean = textCompare.ContentsEqual("undelete", True)
    If sameText6 = True Then
        success = rest.AddQueryParam("comp", "undelete")
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        rest.Disconnect(10)
        success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
        If success <> True Then
            Log("TLS reconnection failed.")
            Return
        End If

        success = rest.UseConnection(connection, False)
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        responseText = rest.FullRequestNoBody("PUT", resourcePath)
        If rest.LastMethodSuccess <> True Then
            Log("Request did not complete; outcome may be uncertain.")
            Return
        End If

        If rest.ResponseStatusCode <> 200 Then
            Log("HTTP status: " & rest.ResponseStatusCode)
            Log("Azure error code: " & rest.ResponseHdrByName("x-ms-error-code"))
            Log("Request ID: " & rest.ResponseHdrByName("x-ms-request-id"))
            '  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
            Return
        End If

        Log("Undelete accepted. Rerun listing before selecting a version or snapshot.")
    Else
        textCompare.Clear
        textCompare.SetString(action)
        Dim sameText7 As Boolean = textCompare.ContentsEqual("restore-version", True)
        textCompare.Clear
        textCompare.SetString(action)
        Dim sameText8 As Boolean = textCompare.ContentsEqual("restore-snapshot", True)
        If (sameText7 <> True) And (sameText8 <> True) Then
            Log("Unknown recovery action.")
            Return
        End If

        textCompare.Clear
        textCompare.SetString(selectedId)
        Dim sameText9 As Boolean = textCompare.ContentsEqual("", True)
        If sameText9 = True Then
            Log("Select a version or snapshot ID from the listing first.")
            Return
        End If

        Dim encodedId As ChilkatStringBuilder
        encodedId.Initialize
        success = encodedId.Append(selectedId)
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        success = encodedId.Encode("url", "utf-8")
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        Dim restoreUrl As ChilkatStringBuilder
        restoreUrl.Initialize
        success = restoreUrl.Append("https://")
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        success = restoreUrl.Append(endpoint.GetAsString)
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        success = restoreUrl.Append(resourcePath)
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        textCompare.Clear
        textCompare.SetString(action)
        Dim sameText10 As Boolean = textCompare.ContentsEqual("restore-version", True)
        If sameText10 = True Then
            success = restoreUrl.Append("?versionid=")
            If success <> True Then
                Log("Could not prepare the request.")
                Return
            End If

        Else
            success = restoreUrl.Append("?snapshot=")
            If success <> True Then
                Log("Could not prepare the request.")
                Return
            End If

        End If

        success = restoreUrl.Append(encodedId.GetAsString)
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        success = rest.AddHeader("x-ms-copy-source", restoreUrl.GetAsString)
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        textCompare.Clear
        textCompare.SetString(destinationEtag)
        Dim sameText11 As Boolean = textCompare.ContentsEqual("", True)
        If sameText11 = True Then
            success = rest.AddHeader("If-None-Match", "*")
            If success <> True Then
                Log("Could not prepare the request.")
                Return
            End If

        Else
            success = rest.AddHeader("If-Match", destinationEtag)
            If success <> True Then
                Log("Could not prepare the request.")
                Return
            End If

        End If

        rest.Disconnect(10)
        success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
        If success <> True Then
            Log("TLS reconnection failed.")
            Return
        End If

        success = rest.UseConnection(connection, False)
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        responseText = rest.FullRequestNoBody("PUT", resourcePath)
        If rest.LastMethodSuccess <> True Then
            Log("Request did not complete; outcome may be uncertain.")
            Return
        End If

        If rest.ResponseStatusCode <> 202 Then
            Log("HTTP status: " & rest.ResponseStatusCode)
            Log("Azure error code: " & rest.ResponseHdrByName("x-ms-error-code"))
            Log("Request ID: " & rest.ResponseHdrByName("x-ms-request-id"))
            '  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
            Return
        End If

        Dim copyId As String = rest.ResponseHdrByName("x-ms-copy-id")
        textCompare.Clear
        textCompare.SetString(copyId)
        Dim sameText12 As Boolean = textCompare.ContentsEqual("", True)
        If sameText12 = True Then
            Log("Copy accepted without a copy ID; inspect before retrying.")
            Return
        End If

        Log("Copy ID: " & copyId)
        '  Save copyId and destination in application state if polling must survive restart.
        success = rest.ClearAllHeaders
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        success = rest.ClearAllQueryParams
        If success <> True Then
            Log("Could not prepare the request.")
            Return
        End If

        Dim polls As Int = 0
        Dim completed As Boolean = False
        Do While ((polls < 20) And (completed <> True))
            rest.Disconnect(10)
            success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
            If success <> True Then
                Log("TLS reconnection failed.")
                Return
            End If

            success = rest.UseConnection(connection, False)
            If success <> True Then
                Log("Could not prepare the request.")
                Return
            End If

            responseText = rest.FullRequestNoBody("HEAD", resourcePath)
            If rest.LastMethodSuccess <> True Then
                Log("Request did not complete; outcome may be uncertain.")
                Return
            End If

            If rest.ResponseStatusCode <> 200 Then
                Log("HTTP status: " & rest.ResponseStatusCode)
                Log("Azure error code: " & rest.ResponseHdrByName("x-ms-error-code"))
                Log("Request ID: " & rest.ResponseHdrByName("x-ms-request-id"))
                '  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
                Return
            End If

            textCompare.Clear
            textCompare.SetString(rest.ResponseHdrByName("x-ms-copy-id"))
            Dim sameText13 As Boolean = textCompare.ContentsEqual(copyId, True)
            If sameText13 <> True Then
                Log("Destination no longer reports this copy ID.")
                Return
            End If

            Dim copyStatus As String = rest.ResponseHdrByName("x-ms-copy-status")
            textCompare.Clear
            textCompare.SetString(copyStatus)
            Dim sameText14 As Boolean = textCompare.ContentsEqual("success", True)
            If sameText14 = True Then
                completed = True
            Else
                textCompare.Clear
                textCompare.SetString(copyStatus)
                Dim sameText15 As Boolean = textCompare.ContentsEqual("pending", True)
                If sameText15 <> True Then
                    Log("Copy failed, was aborted, or returned an unexpected status; inspect copy diagnostics privately.")
                    Return
                End If

                '  Pause between polls; the copy can outlast this example's bounded wait.
                connection.SleepMs(1000)
            End If

            polls = polls + 1
        Loop
        If completed <> True Then
            Log("Copy is still pending. Continue polling this ID; do not start another copy.")
            Return
        End If

        Log("Copy completed.")
    End If

End If

Log("Recovery workflow finished.")