Web services - returning custom objects

by Andrei Hetel 13. November 2008 14:12

This article is focused on web services, more exactly about the way you can return a custom object into your client application (in my case a windows mobile application). The easiest way is to use a simple example. On web service project let's create a simple class with only 2 properties CastleId, CastleName:

 

<Serializable()> _
Public Class CCastle

  Private _CastleId As Int64
  Private _CastleName As String

  Public Sub New()
  End Sub
  Public Sub New(ByVal newCastleId As Int64, ByVal newCastleName As String)
    _CastleId = newCastleId
    _CastleName = newCastleName
  End Sub

  Public Property CastleId() As Int64
    Get
      Return _CastleId
    End Get
    Set(ByVal value As Int64)
      _CastleId = value
    End Set
  End Property
  Public Property CastleName() As String
    Get
      Return _CastleName.Trim
    End Get
    Set(ByVal value As String)
      _CastleName = value
    End Set
  End Property

End Class

 

Please note that the class is marked as serializable and the properties are public read/write, to be able to use it into the client application created later.

Now, let's create a collection class, also serializable:

 

<Serializable()> _
Public Class CCastleList
  Private _CastleList As List(Of CCastle)

  Public Property CastleList() As List(Of CCastle)
    Get
      Return _CastleList
    End Get
    Set(ByVal value As List(Of CCastle))
      _CastleList = value
    End Set
  End Property
End Class

 

Finally, web method:

 

<WebMethod()> _
Public Function CastleList() As CCastleList

  Dim cl As New CCastleList
  Dim myList As New List(Of CCastle)

  myList.Add(New CCastle(1, "Castle1"))
  myList.Add(New CCastle(2, "Castle2"))
  cl.CastleList = myList
  Return cl

End Function

 

That's all on the web service side. Now, let's create a client application, reference the web service and call the web method. Like this:

 

Public Sub LoadCastleList()

  Dim ws As localhost.YsaMain
  Dim cl As localhost.CCastleList
  Dim castle As localhost.CCastle

  Try
    ws = New localhost.YsaMain
    cl = ws.CastleList()

    For Each castle In cl.CastleList
      debug.writeline (castle.CastleId & " " & castle.CastleName)
    Next castle

  Catch ex As Exception
  End Try
End Sub

 

blog comments powered by Disqus