Webservice having trouble pass back to client - asp.net

I having trouble passing back the result which is multiple row getting from MS-SQL2012 to client. I have tried to google up but still not find the solution. Since I'm new in .NET and this is my first webservice, required an assistant to solve my problem or suggest any better solution.
Result need to pass back to client
Public Class Service1
Inherits System.Web.Services.WebService
Public Class Dealer
Public IDNo, ICFound, POFound As String
End Class
<WebMethod()> _
Public Function DailyCheckDealer(records As String()()) As String
Dim mylist As List(Of String()) = records.ToList()
Dim datarow As String = ""
Dim result As String = "Done"
For i As Integer = 0 To mylist.Count - 1
Dim m As String() = mylist(i)
For j As Integer = 0 To m.Length - 1
datarow += m(j) + " "
Next
Next
//Insert the array into the database.
Dim objDealer As New Dealer
Dim myConnString = System.Configuration.ConfigurationManager.AppSettings("MM_CONNECTION_STRING_iPRIS")
Dim myConnection1 = New SqlConnection(myConnString)
Dim myCommand = New SqlCommand()
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Connection = myConnection1
myCommand.CommandText = "DailyCheckDealer"
myCommand.Parameters.Add("#DataRow", SqlDbType.VarChar, 8000).Value = datarow
myConnection1.Open()
myCommand.ExecuteNonQuery()
myConnection1.Close()
// Get the record(s) after processing and return it back to client
Dim myConnection2 = New SqlConnection(myConnString)
Dim objComm As New SqlCommand("Select IDNo, IDFound, POFound From DailyDealerCheck Order By IDNo", myConnection2)
myConnection2.Open()
Dim sdr As SqlDataReader = objComm.ExecuteReader()
If sdr.Read() Then
objDealer.IDNo = sdr("IDNo").ToString()
objDealer.ICFound = sdr("IDFound").ToString()
objDealer.POFound = sdr("POFound").ToString()
End If
myConnection2.Close()
Return objDealer
End Function
End Class

You're getting your data and putting it into objDealer which is an instance of type Dealer. You then actually have Return objDealer
Clrearly you want to return an instance of Dealer. However your function is declared as returning a string. That shouldn't even compile! Change the declaration to this:
<WebMethod()> _
Public Function DailyCheckDealer(records As String()()) As Dealer
That will allow it to return a Dealer not a string.
EDIT - to return more than one Dealer:
<WebMethod()> _
Public Function DailyCheckDealer(records As String()()) As List(Of Dealer)
' code left out
Dim myConnection2 = New SqlConnection(myConnString)
Dim objComm As New SqlCommand("Select IDNo, IDFound, POFound From DailyDealerCheck Order By IDNo", myConnection2)
' Create list of Dealers for return
Dim dealerList as New List(Of Dealer)
myConnection2.Open()
Dim sdr As SqlDataReader = objComm.ExecuteReader()
If sdr.Read() Then
objDealer.IDNo = sdr("IDNo").ToString()
objDealer.ICFound = sdr("IDFound").ToString()
objDealer.POFound = sdr("POFound").ToString()
' Add the latest to the list
dealerList.Add(objDealer)
End If
myConnection2.Close()
' Return list of dealers
Return dealerList
End Function

Related

ASP.NET Web API List All Records from SQL Server Table

I'm trying to follow a simple example (link below) to learn Web API and am unable to get it list all records from my underlying table. The following will only list the last record in the table when making the api call.
<HttpGet>
Public Function GetEmployees() As Employee
Dim reader As SqlDataReader = Nothing
Dim myConnection As SqlConnection = New SqlConnection()
myConnection.ConnectionString = "myconnectionstring"
Dim sqlCmd As SqlCommand = New SqlCommand()
sqlCmd.CommandType = CommandType.Text
sqlCmd.CommandText = "Select * from tblEmployee"
sqlCmd.Connection = myConnection
myConnection.Open()
reader = sqlCmd.ExecuteReader()
Dim emp As Employee = Nothing
While reader.Read()
emp = New Employee()
emp.EmployeeId = Convert.ToInt32(reader.GetValue(0))
emp.Name = reader.GetValue(1).ToString()
emp.ManagerId = Convert.ToInt32(reader.GetValue(2))
End While
Return emp
myConnection.Close()
End Function
I've tried changing the function type to the following but get the error "Unable to cast object of type 'Employee' to type 'System.Collections.Generic.IEnumerable"
Public Function GetEmployees() As IEnumerable(Of Employee)
Credit to original tutorial:
http://www.c-sharpcorner.com/UploadFile/97fc7a/webapi-restful-operations-in-webapi-using-ado-net-objects-a/
In the code you provided, you're creating a single a variable "emp" of type "Employee". Your "While" loop executes and keeps resetting the "emp" variable on each iteration. Instead of using a single variable, you need a collection of Employees --
Public Function GetEmployees() As List(Of Employee)
Dim reader As SqlDataReader = Nothing
Dim myConnection As SqlConnection = New SqlConnection()
myConnection.ConnectionString = "myconnectionstring"
Dim sqlCmd As SqlCommand = New SqlCommand()
sqlCmd.CommandType = CommandType.Text
sqlCmd.CommandText = "Select * from tblEmployee"
sqlCmd.Connection = myConnection
myConnection.Open()
reader = sqlCmd.ExecuteReader()
Dim empList As New List(Of Employee)()
While reader.Read()
Dim emp As Employee = New Employee()
emp.EmployeeId = Convert.ToInt32(reader.GetValue(0))
emp.Name = reader.GetValue(1).ToString()
emp.ManagerId = Convert.ToInt32(reader.GetValue(2))
empList.Add(emp)
End While
myConnection.Close()
Return empList
End Function
To sum up the changes --
Function should return a List of Employee instead of a single Employee object
Create a new Employee on every loop, populate it, then add it to the list
Close your connection before returning
Return the list

Handle DBNull in an object initializer

In my asp.net web service, I have an object class which get data from database, but I counter the following problem when some data is null in database:
(1) If I don't handle the NULL value in database and use the code as below:
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
detail = New customerInfo() With { _
.CustomerID = dr("CUSTOMER_ID"), _
.CustomerName = dr("CUSTOMER_NAME"), _
.RegisterDate = dr("REGISTER_DATE"), _
.Address = dr("ADDRESS") _
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Public Class customerInfo
Public CustomerID As String = String.Empty
Public CustomerName As String = String.Empty
Public RegisterDate As String = Date.Now.ToString("dd/MM/yyyy")
Public Address As String = String.Empty
End Class
I got the error:
System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.
(2) if I handle the NULL in database as below:
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
detail = New customerInfo() With { _
.CustomerID = dr("CUSTOMER_ID"), _
.CustomerName = dr("CUSTOMER_NAME"), _
.RegisterDate = dr("REGISTER_DATE"), _
If dr("ADDRESS") = System.DBNull.Value Then
.Address = ""
Else
.Address = dr("ADDRESS") _
End if
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Public Class customerInfo
Public CustomerID As String = String.Empty
Public CustomerName As String = String.Empty
Public RegisterDate As String = Date.Now.ToString("dd/MM/yyyy")
Public Address As String = String.Empty
End Class
I got the error:
Compiler Error Message: BC30985: Name of field or property being initialized in an object initializer must start with '.'.
I want to know how to handle the DBNull value for string and date in an object initializer.
You can use Convert.ToString
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
Dim registerDate As Date
If Date.TryParse(Convert.ToString(dr("REGISTER_DATE")), registerDate ) = False Then
'Do what you need to do if the cell is not a valid date time value
End If
detail = New customerInfo() With { _
.CustomerID = Convert.ToString(dr("CUSTOMER_ID")), _
.CustomerName = Convert.ToString(dr("CUSTOMER_NAME")), _
.RegisterDate = registerDate.ToString("dd/MM/yyyy"), _
.Address = Convert.ToString(dr("ADDRESS"))
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Edited based on OP's comment below.
While the other methods would work, I think a re-usable extension method with generics support would be ideal.
You can pass the work off to the extension method and check if the value is equal to the value of DBNull.Value
Public Module DataRowExtensions
<System.Runtime.CompilerServices.Extension>
Public Function GetValueOrDefault(Of TExpectedType)(dr As DataRow, propertyName As String) As TExpectedType
If DBNull.Value.Equals(dr(propertyName)) Then
Return Nothing
End If
Return DirectCast(dr(propertyName), TExpectedType)
End Function
End Module
You can see this DotNetFiddle to see it in action with various data types.
Do make note that the extension method Field<T> does exist and is similar, but it doesn't handle DBNull values.
You can't use an if statement inside an object initializer like that.
You have to instantiate the object, then set the properties in separate lines.
detail = New customerInfo()
'Then in separate lines, populate the properties individually
If dr("ADDRESS") = System.DBNull.Value Then
detail.Address = ""
Else
detail.Address = dr("ADDRESS")

Value of type ... cannot be converted to

I keep receiving the following error whenever I try to run my code. Are there any suggestions on what may be causing me to not be able to convert? It seems as though both types are the same, so I'm a little confused on this one.
Value of type 'System.Collections.Generic.List(Of CVE)' cannot be converted to 'System.Collections.Generic.List(Of CVE)'
Error is occurring here:
Dim cveList As List(Of CVE)
cveList = CVERepository.GetInstance.ReadAllCVEs
Here's the CVERepository class:
Public Class CVERepository
Private Sub New()
End Sub
Public Shared ReadOnly Property GetInstance As CVERepository
Get
Static Instance As CVERepository = New CVERepository
Return Instance
End Get
End Property
Public Function ReadAllCVEs() As List(Of CVE)
Dim objAdapter As OleDb.OleDbDataAdapter
Dim dtCVE As New DataTable()
Dim strSQL As String
Dim strConn As String
Dim dvCVE As DataView
strConn = ConnectStringBuild()
strSQL = "Select * From CVE"
objAdapter = New OleDb.OleDbDataAdapter(strSQL, strConn)
objAdapter.Fill(dtCVE)
dvCVE = dtCVE.DefaultView
Dim cveList As New List(Of CVE)
'Put it into an object list to make it more managable.
For index = 0 To dvCVE.Count - 1
Dim cve As New CVE
cve.ID = dvCVE(index)("CVEID")
cve.PublishedDate = dvCVE(index)("PublishedDate")
cve.Availability = dvCVE(index)("Availability")
cve.CVSSScore = dvCVE(index)("CVSSScore")
cve.Confidentiality = dvCVE(index)("Confidentiality")
cve.Integrity = dvCVE(index)("Integrity")
cve.Summary = dvCVE(index)("Summary")
cveList.Add(cve)
Next
Return cveList
End Function
Public Shared Function ConnectStringBuild() As String
'Grabbing connection string from web.config
Return System.Configuration.ConfigurationManager.ConnectionStrings("CVEConnectionString").ConnectionString
End Function
End Class
Any suggestion on the error?
just a little change
Dim cveList As List(Of CVE)
cveList.AddRange(CVERepository.GetInstance.ReadAllCVEs)

return query into stringbuilder

im just trying to return a query into stringbuilder in order to generate dinamicly html
Partial Class _Default
Inherits System.Web.UI.Page
<WebMethod()> _
Public Shared Function BuscarTurbos(referencia As String) As String
Dim sb As StringBuilder = New StringBuilder
Dim conexion As SqlConnection = New SqlConnection("Data Source=PC-TOSH\misql ;Initial Catalog=Rotomaster;Integrated Security=True")
conexion.Open()
Dim cmd As SqlCommand
cmd = New SqlCommand("SELECT VehicleModel,Year FROM TURBOSNUEVO WHERE TurboModel like '%" + referencia + "%'", conexion)
Dim dr As SqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
While dr.Read
sb.Append("<p style='background-color:red;width:50%;height:100px'>'" + dr("VehicleModel").ToString(), CType(dr("Year"), Double) + "' </p>")
End While
End If
Return sb.ToString
End Function
End Class
I would change your
sb.Append("<p style='background-color:red;width:50%;height:100px'>'" + dr("VehicleModel").ToString(), CType(dr("Year"), Double) + "' </p>")
into this:
sb.AppendFormat("<p style='background-color:red;width:50%;height:100px'>{0} {1}</p>", dr("VehicleModel").ToString(), dr("Year").ToString())
One note about string concatenating (joining together) - strings are immutible meaning each time you join strings together, it has to create a new string object since they cannot be changed. By using AppendFormat, it saves you from having to create extra string objects.

How to sort a List?

I have tried to sort the list in many ways, but none work for me. I must be doing something wrong. I want to sort the List details then serialize it and send it to the UI, so that i have a sorted List in the UI.
So basically i want Return strJson to return the sorted(sorted by the sort property) List. Hope i am making sense.
<WebMethod(Description:="Get Home Page Items Page Wise", EnableSession:=True)> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function GetHomePageItemsPageWise(ByVal pageIndex As String) As Object
Dim details As New List(Of HomePageObject)()
Dim idObject As New List(Of GetIdBasedOnInterest)()
idObject = CType(BLL.GetDataByInterests(CType(BLL.GetAccIdFromSocialAuthSession(), Integer)), List(Of GetIdBasedOnInterest))
Dim cmd As DbCommand = _db.GetStoredProcCommand("GetHomePageObjectPageWise")
_db.AddInParameter(cmd, "PageIndex", SqlDbType.VarChar, pageIndex)
_db.AddInParameter(cmd, "PageSize", SqlDbType.Int, 10)
_db.AddOutParameter(cmd, "PageCount", SqlDbType.Int, 1)
_db.AddInParameter(cmd, "whereStoryID", SqlDbType.VarChar, idObject(0).StoryIds)
_db.AddInParameter(cmd, "whereAlbumID", SqlDbType.VarChar, idObject(0).AlbumIds)
_db.AddInParameter(cmd, "wherePictureID", SqlDbType.VarChar, idObject(0).PictureIds)
Try
Using ds As DataSet = _db.ExecuteDataSet(cmd)
For Each rs As DataRow In ds.Tables(0).Rows
Dim homePageObject As New HomePageObject()
homePageObject.AlbumId = rs("AlbumId").ToString()
homePageObject.StoryTitle = rs("StoryTitle").ToString()
homePageObject.AlbumName = rs("AlbumName").ToString()
homePageObject.AlbumCover = rs("AlbumCover").ToString()
homePageObject.Votes = rs("Votes").ToString()
homePageObject.PictureId = rs("PictureId").ToString()
homePageObject.TableName = rs("tableName").ToString()
homePageObject.PageCount = CType(cmd.Parameters("#PageCount").Value, Integer)
homePageObject.Sort = Guid.NewGuid()
details.Add(homePageObject)
Next
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Dim js As New JavaScriptSerializer()
Dim strJson As String = js.Serialize(details.ToArray)
Return strJson
End Function
To randomize the list you can do the following. (And you do not need the Sort property in HomePageObject to accomplish this)
Dim rnd As new Random()
Dim strJson As String = js.Serialize(details.OrderBy(Function(x) rnd.Next()).ToArray())

Resources