Share via


Creating an Entity 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 Entity Using REST, the following Visual Basic sample creates a non-blob entity in the specified container. The application performs the following steps:

  • Create an XML payload describing the new entity.
  • Initialize a WebRequest instance with the container URI as the parameter. This is the container in which the new entity is created.
  • Set the Content-Type request header to application/x-ssds+xml indicating XML payload. For blob entities the Content-Type should be set to the appropriate MIME type.
  • Send the request.
  • Process the response by printing the system assigned entity 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, container id and a unique id for the new entity being created.

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 CreateEntityUsingREST


    Class Program

        Private userName As String
        Private password As String
        Const authorityId As String = "trworth-vb"
        Const containerId As String = "c3_VB"
        Const sampleEntityId As String = "e1"

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


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

            ' Identify specific container resource (to add a new entity) data.sitka-test.cloudds.com
            Dim ContainerUri As String = String.Format("https://{0}.data.database.windows.net/v1/{1}", authorityId, containerId)

            ' Data going over to the server
            Dim requestPayload As String = CreateBook(sampleEntityId, "My first used book imports REST", _
                                               "Some summary", "1-57880-057-9", _
                                               "Author A", "Publisher B")

            CreateEntity(ContainerUri, requestPayload)

        End Sub 'Main'

        Public Function CreateBook(ByVal id As String, ByVal title As String, ByVal summary As String, _
                                    ByVal isbn As String, ByVal author As String, ByVal publisher As String) As String


            ' Need to create request payload, as shown, describing the entity we want to create.
            Const EntityTemplate As String = _
                "<Book 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>{0}</s:Id> " & _
                     "<title xsi:type='x:string'>{1}</title>" & _
                     "<summary xsi:type='x:string'>{2}</summary> " & _
                     "<isbn xsi:type='x:string'>{3}</isbn> " & _
                     "<author xsi:type='x:string'>{4}</author> " & _
                     "<publisher xsi:type='x:string'>{5}</publisher> " & _
                 "</Book>"
            Return String.Format(EntityTemplate, id, title, summary, isbn, author, publisher)
        End Function 'CreateBook'

        Public Function CreateEntity(ByVal containerUri As String, ByVal requestPayload As String) As String



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

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


            If (String.IsNullOrEmpty(requestPayload)) Then

                Throw New ArgumentOutOfRangeException(requestPayload)
            End If

            Try

                ' Create the request to send.
                Dim request As WebRequest = HttpWebRequest.Create(containerUri)
                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("Entity created. System assigned version: {0}", response.Headers("ETag"))
                        ' Since current implementation returns response.Headers[HttpResponseHeader.Location]
                        ' value null, construct entity URI
                        entityUri = String.Format(containerUri + "/" + sampleEntityId)

                    Else

                        Console.WriteLine("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 entityUri
        End Function 'CreateEntity'

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

To verify the result, enter the entity URI in the browser to retrieve the specific entity:

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

Note

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

The result for the sample above might look like this:

<Book 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>SampleBookUsingREST</s:Id>
    <s:Version>version-number</s:Version>
    <title xsi:type="x:string">My first used book using REST</title>
    <summary xsi:type="x:string">Some summary</summary>
    <isbn xsi:type="x:string">1-57880-057-9</isbn>
    <author xsi:type="x:string">Author A</author>
    <publisher xsi:type="x:string">Publisher B</publisher>
</Book>

You can specify empty query with specific container in scope to find all the entities in that container:

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

For details about queries, see Querying SQL Data Services.

See Also

Concepts

Creating an Entity Using REST
Guidelines and Limitations