How to build basic web service with ASP.NET in VB.NET – step 1

Each web service begins as a stateless class with one or more methods that the remote clients call to invoke your code.

BookService is designed to allow remote clients to retrieve information about books provided by the store. The class provides GetBooks() method that returns a DataSet with the full set of books information. It also provides a GetBooksCount() method, which simply return the number of books in the database. In this case you need some basic ADO.NET code to provide these methods.

 

Public Class BooksService

Private connectionString As String

Public Sub New()

Dim connectionString As String = WebConfigurationManager.ConnectionStrings(“BookStore”).ConnectionString

End Sub

Public Function GetBooksCount() As Integer

Dim con As New SqlConnection(connectionString)

Dim sql As String = “SELECT COUNT(*) FROM Books”

Dim cmd As New SqlCommand(sql, con)

‘ Open the connection and get the value.

con.Open()

Dim numBooks As Integer = -1

Try

numBooks = CInt(cmd.ExecuteScalar())

Finally

con.Close()

End Try

Return numBooks

End Function

Public Function GetBooks() As DataSet

‘ Create the command and the connection.

Dim sql As String = “SELECT ISBN, AuthorLName, AuthorFName, Title, ” & “Pages, Price  FROM Books”

Dim con As New SqlConnection(connectionString)

Dim da As New SqlDataAdapter(sql, con)

Dim ds As New DataSet()

‘ Fill the DataSet.

da.Fill(ds, “Books”)

Return ds

End Function

End Class

 

You can use GetBooks() and GetBooksCount() in any web page in the same project, because both methods are public.