Imports System.Data.SqlClient
Imports System.Web.Configuration

Partial Class CheckForMessage
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim reader As SqlDataReader
        Dim recipient As String

        ' Set the content type
        Response.ContentType = "text/plain"
        Response.ContentEncoding = Encoding.UTF8

        ' Prevent page from being cached when we are polling
        Response.Expires = -1

        If Request.Form("recipientname") <> "" Then
            recipient = Request.Form("recipientname")

            Try
                connection = New SqlConnection(WebConfigurationManager.ConnectionStrings("StudentMessagesConnectionString").ConnectionString)
                command = New SqlCommand("SELECT * FROM Message WHERE Recipient=@Recipient ORDER BY DateReceived DESC", connection)
                command.Parameters.AddWithValue("@Recipient", recipient)

                Using connection
                    connection.Open()
                    reader = command.ExecuteReader()

                    If reader.HasRows Then
                        reader.Read()
                        Response.Write(CType(reader("DateReceived"), Date) & "<br/>")
                        Response.Write("||")
                        Response.Write(CType(reader("Sender"), String) & "<br/>")
                        Response.Write("||")
                        Response.Write(CType(reader("Text"), String) & "<br/>")
                    Else
                        Response.Write("-1||No matching row found")
                    End If

                    connection.Close()
                End Using
            Catch
                Response.Write("-1||An error occurred")
            End Try

        Else
            Response.Write("-1||No key provided for search")
        End If

    End Sub
End Class
