Share via


Creating a Container Using REST (VB)

[This document supports a preliminary release of a software product that may be changed substantially prior to final commercial release. This document is provided for informational purposes only.]

As described in Creating a Container Using REST, the following Visual Basic sample creates a container in the specified authority. The application performs the following steps:

  • Create an XML payload describing the container.
  • Initialize a WebRequest instance with the authority URI as the parameter. This is the authority in which the new container is created.
  • Set the Content-Type request header to application/x-ssds+xml indicating XML payload.
  • Send the request.
  • Process the response by printing the system assigned container version returned in the ETag response header.

Note

Credentials are required to access the service. To make a working sample, update following code and provide your existing authority id and unique id for the new container. Each container beneath an authority must have unique id.

If you are using the Microsoft Visual Studio integrated development environment, create a console application and add the following code.

Imports System
Imports System.Text
Imports System.Net
Imports System.IO
Imports System.Xml.Linq

Namespace CreateContainerUsingREST


    Class Program

        Private userName As String
        Private password As String
        Const authorityId As String = "trworth-vb"
        Const sampleContainerId As String = "c3_VB"

        Public Sub testMain() 'ByVal args As String())


            Console.Write("Username: ")
            userName = Console.ReadLine()
            Console.Write("Password: ")
            password = ReadPassword()

            ' Identify specific authority resource (to add a new container) 
            Dim AuthorityUri As String = String.Format("https://{0}.data.database.windows.net/v1/", authorityId)


            Dim containerUri As String = CreateContainer(AuthorityUri)

        End Sub 'Main'


        Public Function CreateContainer(ByVal authorityUri As String) As String

            Const HttpPostMethod As String = "POST"
            Const ssdsContentType As String = "application/x-ssds+xml"

            If String.IsNullOrEmpty(authorityUri) Then
                Throw New ArgumentOutOfRangeException(authorityUri)
            End If
            Dim containerUri As String = ""

            Try
                ' create XML (create container) request payload.
                Dim ContainerTemplate As String = "<s:Container xmlns:s='https://schemas.microsoft.com/sitka/2008/03/'>" & _
                                                    " <s:Id>{0}</s:Id>" & _
                                                    "</s:Container>"

                Dim requestPayload As String = String.Format(ContainerTemplate, sampleContainerId)
                ' Create the request to send.
                Dim request As HttpWebRequest = HttpWebRequest.Create(authorityUri)
                request.Credentials = New NetworkCredential(userName, password)
                ' POST=create PUT=update DELETE=delete GET=retrieve
                request.Method = HttpPostMethod
                Dim Encoding As UTF8Encoding = New UTF8Encoding()
                request.ContentLength = Encoding.GetByteCount(requestPayload)
                request.ContentType = ssdsContentType

                ' Write the request data over the wire.

                Using reqStm As Stream = request.GetRequestStream()

                    reqStm.Write(Encoding.GetBytes(requestPayload), 0, _
                                 Encoding.GetByteCount(requestPayload))
                End Using

                ' Get the response and read it in to a string.
                Using response As HttpWebResponse = request.GetResponse()
                    If response.StatusCode = HttpStatusCode.Created Then

                        Console.WriteLine("Container created. System assigned version: {0}", response.Headers("ETag"))
                        ' Since current implementation returns response.Headers[HttpResponseHeader.Location]
                        ' value null, construct container URI
                        containerUri = String.Format("https://{0}.data.database.windows.net/v1/{1}", authorityId, sampleContainerId)

                    Else

                        Console.WriteLine("Failed to create the container. Unexpected status code returned: {0}", response.StatusCode.ToString())
                    End If
                End Using

            Catch ex As WebException

                Using response As HttpWebResponse = ex.Response

                    If Not response Is Nothing Then

                        Dim errorMsg As String = ReadResponse(response)
                        Console.WriteLine(String.Format("Error:{0}", errorMsg))
                        Console.WriteLine("Unexpected status code returned: {0} ", response.StatusCode.ToString())
                    End If
                End Using
            End Try

            Return containerUri
        End Function 'CreateContainer'

        Public Function ReadResponse(ByVal response As HttpWebResponse) As String

            ' Begin by validating our inbound parameters.
            '
            If (response Is Nothing) Then

                Throw New ArgumentNullException("response", "Value cannot be null")
            End If

            ' Then, open up a reader to the response and read the contents to a string
            ' and return that to the caller.
            '
            Dim responseBody As String = ""
            Using rspStm As Stream = response.GetResponseStream()

                Using reader As StreamReader = New StreamReader(rspStm)

                    responseBody = reader.ReadToEnd()
                End Using
            End Using

            Return responseBody
        End Function 'ReadResponse'

        Private Function ReadPassword() As String

            Dim retval As StringBuilder = New StringBuilder()
            Dim keyInfo As ConsoleKeyInfo = Console.ReadKey(True)

            While keyInfo.Key <> ConsoleKey.Enter

                Console.Write("*")
                retval.Append(keyInfo.KeyChar)

                keyInfo = Console.ReadKey(True)
            End While
            Console.WriteLine()

            Return retval.ToString()
        End Function 'ReadPassword


    End Class 'Program'
End Namespace 'CreateContainerUsingREST'

To verify results, specify the container URI in the browser:

https://<authority-id>.data.database.windows.net/v1/<container-id> 

Note

When querying for non-blob entities your browser need to be aware of the application/x-ssds+xml SSDS content type. For Internet Explorer this can be done by adding a new key in the registry. For more information, see Guidelines and Limitations.

It returns container metadata as shown:

<s:Container xmlns:s="https://schemas.microsoft.com/sitka/2008/03/" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xmlns:x="http://www.w3.org/2001/XMLSchema">
  <s:Id>YourContainerId</s:Id>
  <s:Version>version-number</s:Version>
</s:Container>

You can specify an empty query with the specific authority in the scope to find all the containers in it. For details about queries, see Querying SQL Data Services.

https://<authority-id>.data.database.windows.net/v1?q=''