Updating 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 Updating an Entity Using REST, the following Visual Basic sample the application illustrates a non-blob entity update. The application performs the following steps:
- Create an XML payload describing a sample book entity.
- Send a POST request to create the entity. In the request the application sets the
Content-Type
request header toapplication/x-ssds+xml
indicating XML payload. - Send a GET request to retrieve the entity.
- Load the response string into an
XmlDocument
object. - Add a new property
(<year>
) to the book XML - Serialize the
XmlDocument
object back to a string. - Send the updated string back in a PUT request.
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 sample entity.
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.Xml
Imports System.IO
Imports System.Xml.Linq
Namespace UpdateEntityUsingREST
Class Program
' Provide your data here
Private userName As String
Private password As String
Const authorityId As String = "trworth-vb"
Const containerId As String = "c3_VB"
Const sampleEntityId As String = "e2"
Const HttpGetMethod As String = "GET"
Const HttpPutMethod As String = "PUT"
Const ssdsContentType As String = "application/x-ssds+xml"
Public Sub testMain()
Console.Write("Username: ")
userName = Console.ReadLine()
Console.Write("Password: ")
password = ReadPassword()
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 using REST", "Some summary", "1-57880-057-9", "Author A", "Publisher B")
Try
' Send request to create book entity
Dim bookUri As String = CreateEntity(containerUri, requestPayload)
If bookUri = "" Then
Console.WriteLine("Book URI is null... problem creating sample entity")
Return
End If
Dim data As String = GetEntity(bookUri)
' Load book XML in
Dim bookXML As XmlDocument = New XmlDocument()
bookXML.LoadXml(data)
' Update data by adding new flex property "Year"
Dim newElem As XmlElement = bookXML.CreateElement("year")
newElem.InnerXml = "2005"
newElem.SetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance", "x:string")
bookXML.DocumentElement.AppendChild(newElem)
Dim updatedData As String = bookXML.OuterXml
' Send updated entity back
Dim request As HttpWebRequest = HttpWebRequest.Create(bookUri)
request.Method = HttpPutMethod
Dim Encoding As UTF8Encoding = New UTF8Encoding()
request.ContentLength = Encoding.GetByteCount(updatedData)
request.ContentType = ssdsContentType
request.Credentials = New NetworkCredential(userName, password)
' Write the request data over the wire.
Using reqStm As Stream = request.GetRequestStream()
reqStm.Write(Encoding.GetBytes(updatedData), 0, _
Encoding.GetByteCount(updatedData))
End Using
' Get the response and read it in to a string.
Using response As HttpWebResponse = request.GetResponse()
If response.StatusCode = HttpStatusCode.OK Then
Console.WriteLine("Entity update. Newer entity version: {0}", response.Headers("ETag"))
Else
Console.WriteLine("Unexpected status code returned: {0}", response.StatusCode)
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)
End If
end using
End Try
End Sub 'testMain
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 GetEntity(ByVal entityUri As String) As String
Dim data As String = ""
If (String.IsNullOrEmpty(entityUri)) Then
Throw New ArgumentOutOfRangeException("entityUri")
End If
Try
' retrieve
Dim request As WebRequest = HttpWebRequest.Create(entityUri)
request.Method = HttpGetMethod
'request.ContentLength = 0
request.ContentType = ssdsContentType
request.Credentials = New NetworkCredential(userName, password)
Using response As HttpWebResponse = request.GetResponse()
data = ReadResponse(response)
If response.StatusCode <> HttpStatusCode.OK Then
Console.WriteLine("Error: {0}", data)
Console.WriteLine("Unexpected status code returned: {0}", response.StatusCode)
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("Error:{0}", errorMsg)
Console.WriteLine("Unexpected status code returned: {0}", response.StatusCode)
Throw ex
End If
End Using
end try
Return data
End Function 'GetEntity
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 'UpdateEntityUsingREST
To verify the update, enter the entity URI in the browser.
https://<authority-id>.data.database.windows.net/v1/<container-id>/<entity-id>