Creating an Authority 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 an Authority Using REST, the following Visual Basic example creates an authority. The application performs the following steps:

  • Create an XML payload describing the authority.
  • Initialize a WebRequest instance with the service URI as the parameter. Requests to create an authority are sent to the service. In the request, the Content-Type request header is set to application/x-ssds+xml because the request payload is XML.
  • Send the request.
  • Process the response. If authority creation is successful, application prints the message accordingly.

Note

Credentials are required to access the service. To make a working sample, update following code and provide id value for the authority.

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

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

Namespace CreateAuthorityUsingREST


    Class Program

        Private userName As String
        Private password As String
        Const sampleAuthorityId As String = "trworth-vb"

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


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

            ' When creating an authority, the service must be in scope. 
            Dim serviceUri As String = String.Format("https://data.database.windows.net/v1/")
            Dim authorityUri As String = CreateAuthority(serviceUri)

        End Sub 'Main'


        Public Function CreateAuthority(ByVal serviceUri As String) As String

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

            If String.IsNullOrEmpty(serviceUri) Then
                Throw New ArgumentOutOfRangeException(serviceUri)
            End If

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

                Dim requestPayload As String = String.Format(authorityTemplate, sampleAuthorityId)
                ' Create the request to send.
                Dim request As HttpWebRequest = HttpWebRequest.Create(serviceUri)
                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("Authority created. System assigned version: {0}", response.Headers("ETag"))
                        ' Since current implementation returns response.Headers[HttpResponseHeader.Location]
                        ' value null, construct authority URI
                        authorityUri = String.Format("https://{0}.data.database.windows.net/v1/", sampleAuthorityId)

                    Else

                        Console.WriteLine("Failed to create the authority. 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 authorityUri
        End Function 'CreateAuthority'

        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 'CreateAuthorityUsingREST'

To verify that the authority was created, enter the authority URI in the Web browser.

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

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.

This returns authority metadata as shown in the following sample XML:

<s:Authority 
   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>NewAuthorityID</s:Id>
<s:Version>version-number</s:Version>
</s:Authority>

See Also

Concepts

Creating an Authority Using REST
Guidelines and Limitations