Information retreival from sql server database - asp.net

I want to retreive customer information from microsoft sql server database using just his/her user id onto a web form, can i get some help with this.

You could start by writing a class which will define what a customer is:
Public Class Customer
Public Property Id As Integer
Public Property FirstName As String
Public Property LastName As String
End Class
Then a method to retrieve this customer from the database:
Public Function GetCustomer(ByVal CustomerId As Integer) As Customer
Using conn = New SqlConnection("Data Source=serverName;Initial Catalog=databaseName;User Id=username;Password=password;")
Using cmd = conn.CreateCommand()
conn.Open()
cmd.CommandText = "SELECT id, first_name, last_name FROM customers WHERE id = #id"
cmd.Parameters.AddWithValue("#id", CustomerId)
Using reader = cmd.ExecuteReader()
While reader.Read()
Dim Customer = New Customer()
Customer.Id = reader.GetInt32(reader.GetOrdinal("id"))
Customer.FirstName = reader.GetInt32(reader.GetOrdinal("first_name"))
Customer.LastName = reader.GetInt32(reader.GetOrdinal("last_name"))
Return Customer
End While
End Using
End Using
End Using
Return Nothing
End Function
and finally call this function in your web form:
Dim Customer = GetCustomer(123)
FirstNameTextBox.Text = Customer.FirstName
...
And if you want to avoid writing SQL queries in your code you could use an ORM such as the Entity Framework.

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

select as sql and use in asp.net

i want select from my sql and create a session from one table field
string strquery = "select * from Registration where username=#username ";
SqlConnection connection2 = DBConnection.getConnection();
connection2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection;
cmd2.CommandText = strquery;
cmd2.Parameters.Add("#username", txt1_username.Text);
SqlDataReader nwReader = cmd2.ExecuteReader();
string cus = "";
if (nwReader.Read())
{
cus = nwReader["customer_id"].ToString();
}
nwReader.Close();
connection.Close();
Session["customer_id_se"] = cus.ToString();
Response.Redirect("Wedding.aspx");
my problem is: i can't use that field and use in session
You are doing few mistakes, let me point them first(obviously it will solve the issue too).
As i mentioned in the comment, "you are creating connection2 and
opening connection using connection.Open(); it should be either
connection2.Open(); or remove connection2 from the block.
The .Parameters.Add() method expect SqlDbType specify them and add its value using the following statement.
cmd2.Parameters.Add("#username",SqlDbType.VarChar).Value = txt1_username.Text;
There may be situations where nwReader will not having any rows(query returns no result). Accessing value from it in such situation will give you exception as "Invalid attempt to read when no data is present", So you need to check for existence of data in the Reader before accessing it.
That is you should use like the following:
SqlDataReader nwReader = cmd2.ExecuteReader();
string customerId = String.Empty;
if (nwReader.HasRows)
{
customerId = nwReader["customer_id"].ToString();
}
4. customerId is already a string so you need not to convert it again using .ToString() before assigning to the session. So the complete scenario can be coded as like the following:
string strquery = "select * from Registration where username=#username";
SqlConnection connection = DBConnection.getConnection();
connection.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection;
cmd2.CommandText = strquery;
cmd2.Parameters.Add("#username", SqlDbType.VarChar).Value = txt1_username.Text;
SqlDataReader nwReader = cmd2.ExecuteReader();
string customerID = "";
if (nwReader.HasRows)
{
customerID = nwReader["customer_id"].ToString();
}
nwReader.Close();
connection.Close();
Session["customer_id_se"] = customerID;
Note :-
If nwReader.HasRows is false means there is no such record for the
specific username, in this case customerID and hence
Session["customer_id_se"] will be blank.
Updates as per HansKesting's comment,
Select * will fetch the entire rows which satisfies the condition in the Where clause. If you requires only a single value and you are sure that the result will be either empty or a single value then you can use SELECT column_name from ... and in such situations use ExecuteScalar to get the value.

Return a string Value from SQL Server stored procedure

I have the following method and stored procedure.
My question is how to return a string value from stored procedure to use in addStaffName method ?
public string addStaffName()
{
string staffName = string.Empty;
string sConnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection SqlCOn = new SqlConnection(sConnectionString);
SqlCommand SqlCmd = new SqlCommand();
SqlCOn.Open();
SqlCmd.Connection = SqlCOn;
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCmd.CommandText = "FetchStaffName";
SqlCmd.Parameters.AddWithValue("email", email);
//???
return staffName;
}
create procedure fetchStaffName
#email varchar(100)
AS
begin
select (employeeName)
from employee
where email = #email
end
If you can be sure that you'llonly ever get one row, one column as a result set - then you can use .ExecuteScalar() on your SqlCommand like this:
string staffName = string.Empty;
string sConnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
using (SqlConnection sqlCon = new SqlConnection(sConnectionString))
using (SqlCommand sqlCmd = new SqlCommand("FetchStaffName", sqlCon)
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#email", email);
sqlCon.Open();
staffName = sqlCmd.ExecuteScalar().ToString();
sqlCon.Close();
return staffName;
}
I also put the usage of SqlConnection and SqlCommand into using() { ... } blocks which is the recommended best practice for anything that's deriving from IDisposable to ensure proper disposal of the objects after their use
Consider to make fetchStaffName a scalar function rather than stored procedure. By definition stored procedures are required to perform a set of actions with data. Scalar function guarantees there will be exactly one output value for the set of input values.
CREATE FUNCTION fetchStaffName (
#email VARCHAR(100)
)
RETURNS VARCHAR(?) --Place the length of employeeName field instead of ? symbol.
BEGIN
RETURN (SELECT employeeName FROM employee WHERE email = #email)
END
And then your .NET code transforms into the following:
using (SqlConnection SqlCOn = new SqlConnection(sConnectionString))
{
SqlCommand SqlCmd = new SqlCommand("SELECT fetchStaffName(#email)", SqlCOn);
SqlCmd.CommandType = CommandType.Text;
SqlCmd.Parameters.AddWithValue("#email", email);
SqlCOn.Open();
staffName = (string)SqlCmd.ExecuteScalar();
}
As you can see CommandType changed from StoredProcedure to Text. I also wrapped the work with SqlConnection object into using construction to dispose its resources and close automatically.

Needing to get a list of strings into a webservice

I am creating a web service via asp.net. I want to pull as a list the Address's of the Fuel Stops as shown below unfortunately what I am getting is the string name of address's as shown below from the xml...
Unfortunately when I do run this I get a xml file filled with
-<FuelStop>
<Physical_Address_Street>Physical_Address_Street</Physical_Address_Street>
<Physical_Address_Local>Physical_Address_Local</Physical_Address_Local>
<Physical_Address_State>Physical_Address_State</Physical_Address_State>
<Physical_Address_Zip>Physical_Address_Zip</Physical_Address_Zip>
<Phone_Number>Phone_Number</Phone_Number>
</FuelStop>
Versus getting the address info that is populated in the database.
Below is my code.
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
<System.Web.Services.WebService(Namespace:="http://watersports.com 8010/", Description:="Holds Fuel Stop and Shelter information", Name:="ShelterandFuelService")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class Service1
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetAddresses(ByVal skip As Integer, ByVal take As Integer) As FuelStop()
Dim sqlCon As New SqlConnection
Dim resultList = New List(Of FuelStop)()
Try
sqlCon.ConnectionString = "Data Source=google.watersports.com;Initial Catalog=myDb;Persist Security Info=True;Connect Timeout=30;User ID=****;Password=******"
Dim command As New SqlCommand("SELECT #Physical_Address_Street, #Physical_Address_Local, #Physical_Address_State, #Physical_Address_Zip, #Phone_Number FROM Gas_Stations WHERE Location_Type = 1")
command.Parameters.Add("#Physical_Address_Street", SqlDbType.VarChar, 50).Value = "Physical_Address_Street"
command.Parameters.Add("#Physical_Address_Local", SqlDbType.VarChar, 50).Value = "Physical_Address_Local"
command.Parameters.Add("#Physical_Address_State", SqlDbType.VarChar, 50).Value = "Physical_Address_State"
command.Parameters.Add("#Physical_Address_Zip", SqlDbType.VarChar, 50).Value = "Physical_Address_Zip"
command.Parameters.Add("#Phone_Number", SqlDbType.VarChar, 50).Value = "Phone_Number"
command.Connection = sqlCon
sqlCon.Open()
'command.ExecuteNonQuery()
Using reader = command.ExecuteReader()
While reader.Read()
Dim fuelStop = New FuelStop()
fuelStop.Physical_Address_Street = reader.GetString(0)
fuelStop.Physical_Address_Local = reader.GetString(1)
fuelStop.Physical_Address_State = reader.GetString(2)
fuelStop.Physical_Address_Zip = reader.GetString(3)
fuelStop.Phone_Number = reader.GetString(4)
resultList.Add(fuelStop)
End While
End Using
Catch ex As Exception
sqlCon.Close()
Finally
sqlCon.Close()
End Try
Return resultList.Skip(skip).Take(take).ToArray()
Based on the Sql Command below I will return possibly a few hundred address's how do I incorporparate this into my vb.net logic to return the list of address's?
Dim command As New SqlCommand("SELECT Physical_Address_Street, Physical_Address_Local, Physical_Address_State, Physical_Address_Zip, Phone_Number FROM Gas_Stations WHERE Location_Type = 1")
And here is my Fuel stop class
Public Class FuelStop
Property Physical_Address_Street As String
Property Physical_Address_Local As String
Property Physical_Address_State As String
Property Physical_Address_Zip As String
Property Phone_Number As String
End Class
The below code should give you what you are looking for. I am not sure if WebMethods can return custom objects like the Address object below. If it can not do that then you could convert the return type to String() and turn each Address object into a json object.
If I was doing this from scratch, I would just return a single JSON array that contained a list of Address objects.
Also, I have included in this method signature a skip and take parameter, as you mentioned in your comment, the web service sql query is unbounded so it could return hundreds of addresses. By using the skip and take you can limit how many are returned at once and can page through them from the client. To reduce the size of the sql query you could pass the skip and take parameters into the sql query to reduce the number of rows returned, which would improve performance as the number of addresses grows.
There are additional safety checks you can include in the below code to prevent errors but this can get you moving.
<WebMethod> _
Public Function GetAddresses(skip As Integer, take As Integer) As Address()
Dim resultList = New List(Of Address)()
Using sqlCon As New SqlConnection()
sqlCon.ConnectionString = "Data Source=google.watersports.com;Initial Catalog=myDb;Persist Security Info=True;Connect Timeout=30;User ID=****;Password=******"
Dim command As New SqlCommand("SELECT Physical_Address_Street, Physical_Address_Local, Physical_Address_State, Physical_Address_Zip, Phone_Number FROM Gas_Stations WHERE Location_Type = 1")
sqlCon.Open()
Using reader = command.ExecuteReader()
While reader.Read()
Dim addr = New Address()
addr.Physical_Address_Street = reader.GetString(0)
addr.Physical_Address_Local = reader.GetString(1)
addr.Physical_Address_State = reader.GetString(2)
addr.Physical_Address_Zip = reader.GetString(3)
addr.Phone_Number = reader.GetString(4)
resultList.Add(addr)
End While
End Using
End Using
Return resultList.Skip(skip).Take(take).ToArray()
End Function
Below is a temp class object that is used above.
public class Address
{
public string Physical_Address_Street { get; set; }
public string Physical_Address_Local { get; set; }
public string Physical_Address_State { get; set; }
public string Physical_Address_Zip { get; set; }
public string Phone_Number { get; set; }
}

populating a formview

If I have a class called "car" and this car class uses a SQL query to fill properties like ID, Name, Type, Model, Engine, and Size. How can I populate an asp:formview with that data?
I tried this:
Private currentCar As car
fvCarview.DataSource = currentCar
fvCarview.DataBind()
but I keep on getting this error:
Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource.
Any help would be appreciated!
Thanks
An easy way would be to use a List(Of Car) with a single car in it or a single IEnumerable(Car) via carList.Where(Function(c) c.ID = carID). You could also use a SqlDataAdapter to fill a DataTable and table.Where(Function(r) r.Field(Of Int32)("ID") = carID). Or just select the single car from database which is also the most efficiant way when you don't need the complete list anyway:
DataTable:
Private Sub fillFormView(carID As Int32)
Using con = New SqlConnection(My.Settings.SqlConnection)
Using da = New SqlDataAdapter("SELECT ID, Name, Type, Model, Engine, Size FROM TCAR WHERE ID=#ID", con)
da.SelectCommand.Parameters.AddWithValue("#ID", carID)
Dim table = New DataTable
da.Fill(table)
fvCarview.DataSource = table
fvCarview.DataBind()
End Using
End Using
End Sub
Here's your custom Car-Class approach with a single car in a List(Of Car):
Class Car
Public Property ID As Int32
Public Property Name As String
Public Property Type As String
Public Property Model As String
Public Property Engine As String
Public Property Size As Double
End Class
Private Sub fillFormView(carID As Int32)
Using con = New SqlConnection(My.Settings.SqlConnection)
Using cmd = New SqlCommand("SELECT ID, Name, Type, Model, Engine, Size FROM TCAR WHERE ID=#ID", con)
cmd.Parameters.AddWithValue("#ID", carID)
con.Open()
Using rd = cmd.ExecuteReader()
rd.Read()
Dim carList = New List(Of Car)
Dim car = New Car()
car.ID = rd.GetInt32(0)
car.Name = rd.GetString(1)
car.Type = rd.GetString(2)
car.Model = rd.GetString(3)
car.Engine = rd.GetString(4)
car.Size = rd.GetDouble(5)
carList.Add(car)
fvCarview.DataSource = carList
fvCarview.DataBind()
End Using
End Using
End Using
End Sub

Resources