Solved

ASP .net JSON webservice - Problems with returning multiple results (select sql output)

Posted on 2014-03-14
10
533 Views
Last Modified: 2014-03-15
Hello, I am having troubles with modifying this code to return multiple sql select output in json:
Imports System.IO
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.Data.SqlClient
Imports System.Runtime.Serialization.Json

<ServiceContract([Namespace]:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class GetFriends
    Inherits System.Web.UI.Page
    <OperationContract()> _
    Public Function GetFriendLocation(friendID As Integer) As String
        Dim friendinfo As New FriendInfo()
        Dim connectionString As String = "server=localhost;uid=sa;pwd=thiru;database=AdventureWorks;"
        Using connection As New SqlConnection(connectionString)
            Dim sql As String = "Select FullName, FriendLocation from Friend.Place " & " Where FriendID = " & friendID.ToString()
            connection.Open()
            Dim command As New SqlCommand(sql, connection)
            Dim reader As SqlDataReader = command.ExecuteReader()
            While reader.Read()
                friendinfo.FriendName = reader("FriendName").ToString()
                friendinfo.FriendLocation = reader("FriendLocation").ToString()
                friendinfo.FriendID = friendID
            End While
        End Using
        Dim stream As New MemoryStream()
        Dim serializer As New DataContractJsonSerializer(GetType(FriendInfo))
        serializer.WriteObject(stream, friendinfo)
        stream.Position = 0
        Dim streamReader As New StreamReader(stream)
        Return streamReader.ReadToEnd()
    End Function
End Class
<DataContract()> _
Public Class FriendInfo
    <DataMember()> _
    Public FriendID As Integer
    <DataMember()> _
    Public FriendName As String
    <DataMember()> _
    Public FriendLocation As String
End Class

Open in new window

I am getting a return like this(it selects the last as it is not multiple):
      {
         "FriendID": "11102",
         "FriendName": "Darwin NoName"
         "FriendLocation": "Fakestreet 211"
      }

Open in new window

I would like a result like this(multiple in a json tag named data):
{
   "data": [
      {
         "FriendID": "11101",
         "FriendName": "Newton NoName"
         "FriendLocation": "Fakestreet 3321"
      },
      {
         "FriendID": "11102",
         "FriendName": "Darwin NoName"
         "FriendLocation": "Fakestreet 211"
      }
   ]
}

Open in new window

How can this be done, I can not get this to work.
Thank you in advance
0
Comment
Question by:JoachimPetersen
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
10 Comments
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 39931140
Hi,

One major issue i see and it leads to your problem is the way you handle your data.

In your code you have:
Dim friendinfo As New FriendInfo()

Open in new window

This creates one instance of a FriendInfo object.
Then you iterate through your db results in your While...End While loop:
            While reader.Read()
                friendinfo.FriendName = reader("FriendName").ToString()
                friendinfo.FriendLocation = reader("FriendLocation").ToString()
                friendinfo.FriendID = friendID
            End While

Open in new window


What you do here is getting this one instance and changing its properties with each record you get from your DB, so you finally end up with the last record of your DB.

I would suggest defining a List(Of FriendInfo) and then adding in it each new FriendInfo instances.

Dim friendinfoList As New List(Of FriendInfo())
Dim connectionString As String = "server=localhost;uid=sa;pwd=thiru;database=AdventureWorks;"
   Using connection As New SqlConnection(connectionString)
       Dim sql As String = "Select FullName, FriendLocation from Friend.Place " & " Where FriendID = " & friendID.ToString()
       connection.Open()
       Dim command As New SqlCommand(sql, connection)
       Dim reader As SqlDataReader = command.ExecuteReader()
       While reader.Read()
           Dim friendinfo As New FriendInfo()
           friendinfo.FriendName = reader("FriendName").ToString()
           friendinfo.FriendLocation = reader("FriendLocation").ToString()
           friendinfo.FriendID = friendID
           friendInfoList.Add(friendInfo)
       End While
End Using
 

Open in new window


Then you end up with a List of your objects. Even better would be to use LINQ, but this is out of scope.

Then you would serialize your List object in JSON.

One last thing would be a suggestion on a change on your code.

The way you fetch data from your db could be prone to injection:
Dim sql As String = "Select FullName, FriendLocation from Friend.Place " & " Where FriendID = " & friendID.ToString()

Open in new window


It would be better if you would use SQLParameters:
Dim sql As String = "Select FullName, FriendLocation from Friend.Place Where FriendID = @friendId"
connection.Open()
Dim command As New SqlCommand(sql, connection)
command.Parameters.AddWithValue("@friendId", friendID.ToString())

Open in new window


Giannis
0
 

Author Comment

by:JoachimPetersen
ID: 39931208
Very good answer, I have tried something simular to this but failed.
when I try your provided code I get this error: "Value of type 'FriendInfo' cannot be converted to '1-dimensional array of FriendInfo'" at line "friendinfoList.Add(friendinfo)"
I am using framework 4.0
0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 39931224
Can you please supply your exact code?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:JoachimPetersen
ID: 39931271
Imports System.IO
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.Data.SqlClient
Imports System.Runtime.Serialization.Json
Imports System.Collections.Generic

<ServiceContract([Namespace]:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class App_Default
    Inherits System.Web.UI.Page
    <OperationContract()> _
    Public Function GetFriendLocation(ByVal friendID As Integer) As String
        Dim friendinfoList As New List(Of FriendInfo())
        Dim connectionString As String = "server=localhost;uid=sa;pwd=thiru;database=AdventureWorks;"
        Using connection As New SqlConnection(connectionString)
            Dim sql As String = "Select FullName, FriendLocation from Friend.Place " & " Where FriendID = " & friendID.ToString()
            connection.Open()
            Dim command As New SqlCommand(sql, connection)
            Dim reader As SqlDataReader = command.ExecuteReader()
            While reader.Read()
                Dim friendinfo As New FriendInfo()
                friendinfo.FriendName = reader("FriendName").ToString()
                friendinfo.FriendLocation = reader("FriendLocation").ToString()
                friendinfo.FriendID = friendID
                friendinfoList.Add(friendinfo)
            End While
        End Using
        'Dim stream As New MemoryStream()
        'Dim serializer As New DataContractJsonSerializer(GetType(FriendInfo))
        'serializer.WriteObject(stream, friendinfo)
        'stream.Position = 0
        'Dim streamReader As New StreamReader(stream)
        'Return streamReader.ReadToEnd()
    End Function
End Class
<DataContract()> _
Public Class FriendInfo
    <DataMember()> _
    Public FriendID As Integer
    <DataMember()> _
    Public FriendName As String
    <DataMember()> _
    Public FriendLocation As String
End Class

Open in new window

Error: Value of type 'FriendInfo' cannot be converted to '1-dimensional array of FriendInfo'. at "friendinfoList.Add(friendinfo)"
0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 39931280
A small error while copying and pasting....

Dim friendinfoList As New List(Of FriendInfo())

Open in new window


should be

Dim friendinfoList As New List(Of FriendInfo)

Open in new window


The parenthesis mean that the List would expect Arrays of FriendInfo.

Giannis
0
 

Author Comment

by:JoachimPetersen
ID: 39931417
Okay, when using a List(T), how would you then convert it into an JSON result, any automatic way ot should it be done by looping through each item?
After a quick search I saw an example, but something is wrong with the system.web.extension dll as it cannot find it, I can add it to reference but it can not find it when I write Import System.Web.Extensions
here is the code I would use if it worked, any similar method that will work?
Dim jSearializer As New System.Web.Script.Serialization.JavaScriptSerializer()
        Return jSearializer.Serialize(friendinfoList)

Open in new window

0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 39931439
The following seems to work:

   Dim stream As New MemoryStream()
   Dim serializer As New DataContractJsonSerializer(GetType(List(Of FriendInfo)))
   serializer.WriteObject(stream, friendinfoList)
   stream.Position = 0
   Dim streamReader As New StreamReader(stream)
   Return streamReader.ReadToEnd()

Open in new window


Giannis
0
 

Author Comment

by:JoachimPetersen
ID: 39931459
got any advice on adding them under a tag called data?
The output is:
[
      {
         "FriendID": "11101",
         "FriendName": "Newton NoName"
         "FriendLocation": "Fakestreet 3321"
      },
      {
         "FriendID": "11102",
         "FriendName": "Darwin NoName"
         "FriendLocation": "Fakestreet 211"
      }
   ]

Open in new window

I would like it to return it like:
{
   "data": [
      {
         "FriendID": "11101",
         "FriendName": "Newton NoName"
         "FriendLocation": "Fakestreet 3321"
      },
      {
         "FriendID": "11102",
         "FriendName": "Darwin NoName"
         "FriendLocation": "Fakestreet 211"
      }
   ]
}

Open in new window

0
 
LVL 23

Accepted Solution

by:
Ioannis Paraskevopoulos earned 500 total points
ID: 39931480
One dirty way (or maybe not...) would be to add another class that will have a property of List(Of FriendInfo) then you pass the instance of that object to the serializer:

Public Class FriendInfoList
    Public Data As List(Of FriendInfo)
    Public Sub New()
        Data = New List(Of FriendInfo)
    End Sub
End Class
<DataContract()> _
Public Class FriendInfo
    <DataMember()> _
    Public FriendID As Integer
    <DataMember()> _
    Public FriendName As String
    <DataMember()> _
    Public FriendLocation As String
End Class

<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class App_Default
    Inherits System.Web.UI.Page
    <OperationContract()> _
    Public Function GetFriendLocation(ByVal friendID As Integer) As String
        Dim friendinfoList As New FriendInfoList
        Dim connectionString As String = "server=localhost;uid=sa;pwd=thiru;database=AdventureWorks;"
        Using connection As New SqlConnection(connectionString)
            Dim sql As String = "Select FullName, FriendLocation from Friend.Place " & " Where FriendID = " & friendID.ToString()
            connection.Open()
            Dim command As New SqlCommand(sql, connection)
            Dim reader As SqlDataReader = command.ExecuteReader()
            While reader.Read()
                Dim friendinfo As New FriendInfo()
                friendinfo.FriendName = reader("FriendName").ToString()
                friendinfo.FriendLocation = reader("FriendLocation").ToString()
                friendinfo.FriendID = friendID
                friendinfoList.Data.Add(friendinfo)
            End While
        End Using
        Dim stream As New MemoryStream()
        Dim serializer As New DataContractJsonSerializer(GetType(FriendInfoList))
        serializer.WriteObject(stream, friendinfoList)
        stream.Position = 0
        Dim streamReader As New StreamReader(stream)
        Return streamReader.ReadToEnd()
    End Function
End Class

Open in new window

0
 

Author Closing Comment

by:JoachimPetersen
ID: 39931507
Perfect, very helpfull and very good solutions
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question