MDS VB Code Example


Imports System.Net

 

Namespace MRIS.MDS.Client.Example

''' <summary>

''' <para>Handles MDS client requests.</para>

''' </summary>

Public Class MDSClientHandler

'The user credentials

Private _userID As String

Private _password As String

 

'The user agent

Private _userAgent As String

 

'The endpoint

Private _endpoint As String

 

'Debug Mode property

Private debugMode As Boolean = False

 

'Use GZip property

Private requestGZip As Boolean = False

 

'Create the cookie container for all requests

Dim cookieJar As CookieContainer = New CookieContainer()

 

'Create the credential cache for all requests

Dim _credentials As NetworkCredential

 

''' <summary>

''' <para>Debug Property, when set to <code>TRUE</code>, enables debugging support.</para>

''' </summary>

''' <value>If <code>TRUE</code>, enables debugging dupport.</value>

''' <returns><code>TRUE</code> if debugging is enabled, <code>FALSE</code> if not.</returns>

Property Debug() As Boolean

   Get

      Return debugMode

   End Get

   Set(ByVal Value As Boolean)

      debugMode = Value

   End Set

End Property

 

''' <summary>

''' <para>GZip encoding property, when set to <code>TRUE</code>, enables GZip encoding.</para>

''' </summary>

''' <value>If <code>TRUE</code>, enables GZip support.</value>

''' <returns><code>TRUE</code> if GZip is enabled, false if not.</returns>

Public Property SupportGZip() As Boolean

   Get

    Return requestGZip

   End Get

   Set(ByVal Value As Boolean)

    requestGZip = Value

   End Set

End Property

 

''' <summary>

''' <para>Creates the <code>MDSClientHandler</code></para>

''' </summary>

''' <param name="userID">The User ID</param>

''' <param name="password">The Password</param>

''' <param name="userAgent">The User-Agent</param>

''' <param name="endpoint">The Endpoint</param>

Public Sub New(ByVal userID As System.String, ByVal password As System.String, ByVal userAgent As System.String, ByVal endpoint As System.String)

   _userID = userID

   _password = password

   _userAgent = userAgent

   _endpoint = endpoint

   If (_endpoint.EndsWith("/") = False) Then

    ' Ensure that the endpoint has a trailing "/"

    _endpoint = _endpoint + "/"

   End If

 

   ' Update the credentials

   _credentials = New NetworkCredential(_userID, _password)

End Sub

 

''' <summary>

''' <para>Performs a request for the Logout Service.</para>

''' </summary>

Public Sub Logout()

   Dim url As String = getResourceUrl("Logout")

   ProcessRequest(url)

 End Sub

 

''' <summary>

''' <para>Performs a request for the UserSessionInfo Service.</para>

''' </summary>

''' <returns></returns>

''' <remarks></remarks>

Public Function GetUserSessionInfo() As String

   Dim url As String = getResourceUrl("UserSessionInfo")

   Return ProcessRequest(url)

End Function

 

''' <summary>

''' <para>Executes a request</para>

''' </summary>

''' <param name="resourcePath">The resource path</param>

''' <param name="query">The MDS Query value</param>

''' <param name="count">Optional, if <code>TRUE</code>, indicates that only the record count is to be requested.</param>

''' <param name="limit">Optional, specifies the Limit</param>

''' <returns>The MDS Response</returns>

Public Function ExecuteRequest(ByVal resourcePath As String, ByVal query As String, Optional ByVal count As Boolean = False, Optional ByVal limit As Integer = Nothing)

   Dim url As String = getResourceUrl(resourcePath)

   url = url & "/?Query=" & query

   If (count) Then

    url = url & "&Count=1"

   End If

   If (Not IsNothing(limit)) Then

    url = url & "&Limit=" & limit

   End If

   Return ProcessRequest(url)

End Function

 

''' <summary>

 ''' <para>Executes a resource request</para>

''' </summary>

''' <param name="resourcePath">The resource path</param>

''' <param name="resourceKeys">The comma delimited list of resource keys</param>

''' <param name="selectFields">Optional, specifies the comma delimited list of Select fields</param>

''' <returns>The MDS Response</returns>

Public Function ExecuteRequest(ByVal resourcePath As String, ByVal resourceKeys() As String, Optional ByVal selectFields As String = Nothing)

   Dim url As String = getResourceUrl(resourcePath)

   Dim resourceKeyList As String = Nothing

   For Each resourceKey In resourceKeys

    If (IsNothing(resourceKeyList)) Then

    resourceKeyList = resourceKey

    Else

    resourceKeyList = "," & resourceKey

    End If

   Next

   url = url & "/" & resourceKeyList

   If (Not IsNothing(selectFields)) Then

    url = url & "?Select=" & selectFields

   End If

   Return ProcessRequest(url)

End Function

 

''' <summary>

''' <para>Processes an MDS request.</para>

''' </summary>

''' <param name="url">The URL to request</param>

''' <returns>The MDS Response</returns>

''' <exception cref="System.Net.WebException">Thrown if there was an error executing the request.</exception>

''' <exception cref="System.Exception">Thrown if there was an unknown error executing the request.</exception>

Private Function ProcessRequest(ByVal url As String) As String

   Dim req As Net.HttpWebRequest = createRequest(url)

 

   Try

    ' Issue the request.

    Dim response As HttpWebResponse = CType(req.GetResponse(), HttpWebResponse)

 

    If (debugMode) Then

    Console.WriteLine(ControlChars.Lf + "Authentication Succeeded")

    'Displays all the Headers present in the response received from the URI.

    Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "The following headers were received in the response")

    'The Headers property is a WebHeaderCollection. Use it's properties to traverse the collection and display each header.

    Dim i As Integer

    While i < response.Headers.Count

    Console.WriteLine(ControlChars.Cr + ControlChars.Tab + "{0}: {1}", response.Headers.Keys(i), response.Headers(i))

    i = i + 1

    End While

     End If

 

    ' Calls the method GetResponseStream to return the stream associated with the response.

    Dim receiveStream As System.IO.Stream = response.GetResponseStream()

    If (response.ContentEncoding.ToLower().Contains("gzip")) Then

    receiveStream = New System.IO.Compression.GZipStream(receiveStream, System.IO.Compression.CompressionMode.Decompress)

    End If

 

    Dim responseStr As String = ""

    ' Pipes the response stream to a higher level stream reader with the required encoding format.

    Dim encode As System.Text.Encoding = System.Text.Encoding.GetEncoding("UTF-8")

    Dim readStream As New System.IO.StreamReader(receiveStream, encode)

 

    If (debugMode) Then Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "Response stream received")

 

    Dim read(256) As [Char]

    ' Reads 256 characters at a time.   

Dim count As Integer = readStream.Read(read, 0, 256)

 

    If (debugMode) Then Console.WriteLine("HTML..." + ControlChars.Lf + ControlChars.Cr)

 

    While count > 0

    ' Dumps the 256 characters to a string

    Dim str As New [String](read, 0, count)

    responseStr = responseStr & str

    If (debugMode) Then Console.WriteLine(str)

 

    count = readStream.Read(read, 0, 256)

    End While

 

    ' Releases the resources of the Stream.

    readStream.Close()

   ' Releases the resources of the response.

    response.Close()

 

    Return responseStr

    Catch e As WebException

    Dim response As HttpWebResponse = CType(e.Response, HttpWebResponse)

    If Not (response Is Nothing) Then

    Console.WriteLine(ControlChars.NewLine + "The following exception was raised : {0}", e.Message)

    Console.WriteLine(ControlChars.NewLine + "Received Status Code: {0}", response.StatusCode.ToString)

    'Displays all the Headers present in the response received from the URI.

    Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "The following headers were received in the response")

    'The Headers property is a WebHeaderCollection. Use it's properties to traverse the collection and display each header.

    Dim i As Integer

    While i < response.Headers.Count

    Console.WriteLine(ControlChars.Cr + ControlChars.Tab + "{0}: {1}", response.Headers.Keys(i), response.Headers(i))

    i = i + 1

    End While

    Else

    Console.WriteLine(ControlChars.NewLine + "Response Received from server was null")

    End If

    Throw e 'Rethrow the exception

   Catch e As Exception

    Console.WriteLine(ControlChars.NewLine + "The following exception was raised :{0}", e.Message)

    Throw e 'Rethrow the exception

   End Try

 

   Return Nothing

 

End Function

 

''' <summary>

''' <para>Creates a <code>HttpWebRequest</code> for the specified URL</para>

''' </summary>

''' <param name="url">The request URL</param>

''' <returns>The <code>HttpWebRequest</code></returns>

Private Function createRequest(ByVal url As String) As HttpWebRequest

   Dim req As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)

 

   'Set the User Agent

   req.UserAgent = _userAgent

 

   'Define the http method.

   req.Method = "GET"

 

   req.CookieContainer = cookieJar

 

   'Set the Digest credentials for authentication

   Dim credentialCache = New CredentialCache()

   credentialCache.Add(New Uri(url), "Digest", _credentials)

 

   req.Credentials = credentialCache

 

   If (requestGZip) Then

    req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip")

   End If

 

   Return req

End Function

 

''' <summary>

''' Gets the fully qualified URL for the specified resource path.

''' </summary>

''' <param name="resourcePath">The path to the resource</param>

''' <returns>The fully qualified resource URL</returns>

Private Function getResourceUrl(ByVal resourcePath As String) As String

   If (resourcePath.StartsWith("/") = True) Then

    resourcePath = resourcePath.Remove(0, 1)

   End If

   Dim url = _endpoint & resourcePath

 

   Return url

   End Function

End Class

 

End Namespace