return query into stringbuilder - asp.net

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.

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

Webservice having trouble pass back to client

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

Using Eval function in my code behind?

Here's my code:
Partial Class VideoPlayer
Inherits System.Web.UI.Page
Protected strFileName As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim con As New OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim vidID As Integer = Integer.Parse(Request.QueryString("ID"))
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = |DataDirectory|/webvideos.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim strSQL As String = "SELECT * FROM Videos WHERE ID=" & vidID
strFileName = "videos/TrainingVideos/" & Eval("Filename")
con.Close()
End Sub
End Class
So when I run the code, it tells me it can't run Eval on my string. What am I missing?
Eval will work in your .aspx code with a DataBoundControl.
When in code-behind, you are setting up the connectionstring, sql query and other variables but you are not actually executing the query.
So your code should be something like below:
Dim con As New OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim vidID As Integer = Integer.Parse(Request.QueryString("ID"))
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = |DataDirectory|/webvideos.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim strSQL As String = "SELECT * FROM Videos WHERE ID=" & vidID
//Create an OleDbCommand object.
//Pass in the SQL query and the OleDbConnection object
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
//Execute the command
Dim reader As OleDbDataReader = cmd.ExecuteReader
//Read the first record from the reader
reader.Read()
strFileName = "videos\TrainingVideos\" & reader(1)
con.Close()
First the most important, you are open for sql-injection here:
"SELECT * FROM Videos WHERE ID=" & vidID
Use sql-parameters instead.
You can use Eval only in a databinding context. So you need to call Me.DataBind before.
Me.DataBind()
Dim fileName = Me.Eval("Filename").ToString()
strFileName = System.IO.Path.Combine("videos/TrainingVideos", fileName)
However, i don't know what you're actually trying to achieve here. Why do you need it at all?
Global variable, forgot to add it up there.
Then access it directly.

cannot display image in image control

Its my handler (.ashx)
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else Throw New ArgumentException("No parameter specified") End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Everything is working fine.Only the imageData length is 0 so the image is unable to display.
#Sean: its elsewhr.. here the querystring correctly takes the employeeid passed...
heres the code for db access:
Public Sub bind()
Dim ds1 As New DataSet()
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
con.Open()
Dim query As String = "select * from EmployeeTable"
Dim cmd As New SqlCommand()
Dim da1 As New SqlDataAdapter(query, con)
da1.Fill(ds1, "EmployeeTable")
GridView1.DataSource = ds1.Tables("EmployeeTable")
GridView1.DataBind()
con.Close()
End Sub
You're loading a load of data into the GridView but nothing is being loaded into your imageData variable. So we'll just connect to the database and pull that data out. I'm assuming your image column is called imageData but please change as appropriate.
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring
Using con As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
Using cmd As New SqlCommand("SELECT imageData FROM EmployeeTable WHERE EmployeeID = #EmployeeID", con) 'select imageData column, change column name as appropriate
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID)
Try
con.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
If rdr.Read() Then
imageData = CType(rdr("imageData"), Byte()) 'convert imageData column from result set to byte array and assign to variable
End If
End Using
Catch ex As Exception
'do any error handling here
End Try
End Using
End Using
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Changed the code in the handler to this:
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim Image() As Byte = {}
' get the image data from the database using the employeeId Querystring
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
Dim cmd As New SqlCommand("SELECT Image FROM EmployeeTable WHERE EmployeeID = #EmployeeID", con)
'select imageData column, change column name as appropriate
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID)
Try
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Image = CType(rdr("Image"), Byte())
'convert imageData column from result set to byte array and assign to variable
End While
Catch ex As Exception
'do any error handling here
End Try
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(Image)
End Sub
Worked for me, may be it will work for you too...

how to check existed username when signUp

I want to check if the username is already exist or not. this what I've reached but it's not working.
Dim cmdstr As String = "Select count(*) from Registration where username = '" & txtName.Text & "'"
Dim userExist As SqlCommand = New SqlCommand(cmdstr, con)
Dim temp As Integer = Convert.ToInt32(userExist.ExecuteScalar().ToString())
If (temp = 1) Then
Response.Write("user name is already Exist!!")
End If
Your open for SQL-Injection. Don't concatenate strings to a sql-query but use SqlParameters
You haven't opened the connection (i assume)
Here's a full sample:
Public Shared Function GetUserCount(userName As String) As Int32
Const sql = "SELECT COUNT(*) FROM Registration where username = #UserName"
Using con As New SqlConnection(connectionString)
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#UserName", userName)
con.Open()
Using reader = cmd.ExecuteReader()
If reader.HasRows
reader.Read()
Dim count As Int32 = reader.GetInt32(0)
Return count
End If
End Using
End Using
End Using
End Function
and use the method in this way:
Dim userCount As Int32 = GetUserCount(txtName.Text.Trim())
If userCount > 0
LblWarning.Text = "User-name already exists!"
End If

Resources