Providing Search facility - asp.net

I have a web page with following fields
name,address,post
with three textboxes.I want to provide the search facility to the user.if user enter only the name and hit search it should search only by name, if user enter the values for all the textboxes it should query the database with all 3 values.like wise how can i write the sql query for all the searching possibilities?

select *
from Table1
where
(coalesce(#Name, '') = '' or Name = #Name) and
(coalesce(#Address, '') = '' or Address = #Address) and
(coalesce(#Post, '') = '' or Post = #Post)

I prefer this option for the query. If the user enters a value in only one of the fields, then pass a null to the parameter of the other respective fields.
Create PROCEDURE [dbo].[uspGetPeople]
#name varchar(50),
#Address varchar(200),
#Post varchar(5)
AS
SET NOCOUNT ON;
Select name, address, post
from tblPeople
where (name = #Name or #Name IS NULL) and
(address = #Address or #Address IS NULL) and
(post = #Post or #Post IS NULL)
A simple VB.NET example to call the stored procedure:
Dim strName As String = NameTextBox.Value
Dim strAddress as string = AddressTextBox.Value
Dim strPost as string = PostTextBox.Value
Dim strSQL As String = "uspGetPeople"
Dim strConn As String = "My.Database.ConnectionString"
Dim cn As New SqlConnection(strConn)
Dim cmd As New SqlCommand(strSQL, cn)
cmd.CommandType = CommandType.StoredProcedure
If not string.isnullorempty(strName) then
cmd.Parameters.AddWithValue("#Name", strName)
Else
cmd.Parameters.AddWithValue("#Name", dbnull.value)
End if
If not string.isnullorempty(strPost) then
cmd.Parameters.AddWithValue("#Post", strPost)
Else
cmd.Parameters.AddWithValue("#Post", dbnull.value)
End if
If not string.isnullorempty(strAddress) then
cmd.Parameters.AddWithValue("#Address", strAddress)
Else
cmd.Parameters.AddWithValue("#Address", dbnull.value)
End if
Dim dr As SqlDataReader
Using cn
cn.Open()
dr = cmd.ExecuteReader
While dr.Read
'process records returned
'dr("name")
'dr("address")
'dr("post")
End While
cn.Close()
End Using

Related

Error parsing - Insert value Textbox inside database

I have this form ASP.NET that have two textbox and a label, where the user enters only the expiration date in the last textbox, while the others are inserted automatically if the user clicks on another button inside the repeater where the customer code and company name are found.
The problem is that I created a class to do the insertion: I used a stored procedure for the insertion and I used the query parameterization.
When I parse the code and date it gives me 0 and a default date as a result, while my goal is to insert them into a table inside a db and then have it displayed inside the repeater.
P.S. I add that for reading the data I have another class with another stored procedure and that I have some values ​​that are inside another table (the code and the name of the company).
This is the method:
Public Sub INSERT_EXP_DATE_TABLE()
Dim id_customer As Integer
Dim exp_date As Date
Try
cmd.Connection = cn
cmd.CommandType = CommandType.StoredProcedure
MyParm = cmd.Parameters.Add("#COD_CUSTOMER", SqlDbType.Int)
If (Integer.TryParse(txt_COD_CUSTOMER.Text, id_customer)) Then
MyParm.Value = id_customer
Else
MsgBox("customer not found", vbCritical)
End If
MyParm = cmd.Parameters.Add("#COMPANY_NAME", SqlDbType.NVarChar)
MyParm.Value = lbl_COMPANY_NAME.Text.ToString
MyParm = cmd.Parameters.Add("#EXP_DATE", SqlDbType.Date)
If (Date.TryParse(txt_EXP_DATE.Text, exp_date)) Then
MyParm.Value = exp_date
Else
MsgBox("Exp Date not found", vbCritical)
End If
cmd.CommandText = "LST_INSERT_TABLE_01"
cmd.Connection.Open()
cmd.ExecuteNonQuery()
MsgBox("Date registred", vbInformation)
Catch ex As Exception
MsgBox(ex.Message)
Finally
cn.Close()
End Try
End Sub
And this is the stored procedure:
#ID_CUSTOMER int,
#COMPANY_NAME varchar(50),
#EXP_DATE date,
AS
BEGIN
INSERT INTO TABLE
(
ID_CUSTOMER,
COMPANY_NAME,
EXP_DATE,
)
VALUES(
#ID_CUSTOMER,
#COMPANY_NAME,
#EXP_DATE,
)
END
Keep your connection local to the method where it is used. Connections use unmanaged resources so they include a .Dispose method which releases these resources. To ensure that the database objects are closed and disposed use Using...End Using blocks.
Do you parsing before you start creating database objects. Exit the sub so the user has a chance to correct the problem.
Side note: I don't think a message box will work in an asp.net application.
You set up the company name parameter as an NVarChar but your stored procedure declares it as a VarChar. Which is correct?
It is not necessary to call .ToString on a .Text property. A .Text property is already a String.
You are providing a parameter called "#COD_CUSTOMER" but your stored procedure does not have such parameter.
Public Sub INSERT_EXP_DATE_TABLE()
Dim id_customer As Integer
If Not Integer.TryParse(txt_COD_CUSTOMER.Text, id_customer) Then
MsgBox("Please enter a valid number.", vbCritical)
Exit Sub
End If
Dim exp_date As Date
If Not Date.TryParse(txt_EXP_DATE.Text, exp_date) Then
MsgBox("Please enter a valid date.")
Exit Sub
End If
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("LST_INSERT_TABLE_01", cn)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
.Add("#ID_CUSTOMER", SqlDbType.Int).Value = id_customer
.Add("#COMPANY_NAME", SqlDbType.VarChar, 50).Value = lbl_COMPANY_NAME.Text
.Add("#EXP_DATE", SqlDbType.Date).Value = exp_date
End With
Try
cn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Sub
{
string CN = Interaction.InputBox("Enter Company Name","Customer","",-1,-1);
string Cname = Interaction.InputBox("Enter Customer Name", "Customer", "", -1, -1);
SqlConnection con = new SqlConnection(#"Data Source=Adnan;Initial Catalog=Production;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO hello(Company_Name,Customer_name ) VALUES ( #Company_Name,#Customer_name )");
cmd.Connection = con;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Company_Name", CN.ToString() );
cmd.Parameters.AddWithValue("#Customer_name", Cname.ToString());
}

Different output from stored procedure in SSMS and ASP.NET

I created a stored procedure to include a new user for my system. Parameters are: Name, Mail and Password (all varchar). The stored procedure first checks if the mail is already in the database. If not, then the information in added to the table. At the end, the output is a table with the user data.
CREATE PROCEDURE [dbo].[user_new]
(#name VARCHAR(50),
#mail VARCHAR(50),
#password VARCHAR(100)
)
AS
BEGIN
SET NOCOUNT ON
DECLARE #exist INT
SELECT #exist = COUNT([id])
FROM [dbo].[User]
WHERE [mail] = #mail
IF #exist = 0
INSERT INTO [dbo].[User] ([name], [mail], [password])
VALUES (#name, #mail, #password)
SELECT
#exist AS [exist], [id], [name], [mail]
FROM
[dbo].[User]
WHERE
[mail] = #mail
END
GO
When I execute the stored procedure in SSMS, everything works fine: when I insert a new mail, field [exist] returns 0. When I insert a mail that already exist, field [exist] returns 1. So far, so good.
When I execute the stored procedure from my .NET application (which has a lot of other calls that are working fine), the error happen: no matter if I try to add a new or an existing mail, [exist] always returns 1. I tried to change the logic several times, but I always get the wrong result.
Here is the .NET code:
Public Function api_v2_player_new(<FromBody> s As User) As Object
Dim arrParameters(,) As String = {{"#name", s.Name}, {"#mail", s.Mail}, {"#password", s.Password}}
Dim dtc As Data.DataTableCollection = SQL.Execute("dbo.user_new", arrParameters)
Return SQL.toJson(dtc(0))
End Function
Public Class SQL
Public Shared Function runStoredProcedure(ByVal cmd As SqlCommand) As Data.DataTableCollection
Dim spName As String = cmd.CommandText.ToString
cmd.CommandTimeout = 120
Dim cs As String = System.Configuration.ConfigurationManager.ConnectionStrings("csKickerliga").ConnectionString
Dim connection As SqlConnection = Nothing
connection = New SqlConnection(cs)
Dim dt As DataTable = New DataTable()
cmd.Connection = connection
connection.Open()
Dim adp As New SqlDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
cmd.ExecuteNonQuery()
adp.Fill(ds, spName)
Return ds.Tables
connection.Close()
End Function
Shared Function Execute(spName As String, arrParameters(,) As String) As Data.DataTableCollection
Dim cmd As SqlCommand = New SqlCommand(spName)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
For i = 0 To (arrParameters.Length / 2) - 1
.AddWithValue(arrParameters(i, 0), arrParameters(i, 1))
Next
End With
Dim dtc = runStoredProcedure(cmd)
Return dtc
End Function
Shared Function toJson(dt As DataTable) As List(Of Object)
Dim oList As New List(Of Object)
Dim o As New Dictionary(Of String, Object)
Dim data As Object
For Each r As DataRow In dt.Rows
o = New Dictionary(Of String, Object)
For Each c As DataColumn In dt.Columns
If IsNumeric(r(c.ColumnName)) Then
If Not r(c.ColumnName).ToString.Contains(".") Then
data = CInt(r(c.ColumnName))
Else
data = r(c.ColumnName).ToString
End If
Else
data = r(c.ColumnName).ToString
End If
o.Add(c.ColumnName, data)
Next
oList.Add(o)
Next
Return oList
End Function
End Class
Found the issue. The code was executing the stored procedure twice:
cmd.ExecuteNonQuery()
adp.Fill(ds, spName)
Therefore on the recond run the record already existed because it was created on the first run. I removed one of the lines and now it's working!

Check if Record Exists IN DB Using ASP VB

I am trying to check whether an email exists in my sql database from an an asp code behind
Basically a user will fill in a form and submit, I need to check wther that email exists first before inserting
Protected Sub btnSignup_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSignup.Click
Response.Cookies("survey")("fullname") = TextBoxFullName.Text
Response.Cookies("survey")("surname") = TextBoxSurname.Text
Response.Cookies("survey")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("survey")("contactnumber") = TextBoxPhone.Text
Response.Cookies("survey")("email") = TextBoxEmail.Text
Response.Cookies("survey").Expires = DateTime.Now.AddDays(365)
'InsertCommand="INSERT INTO [Comp_20140409_Broadband] ([SignupName], [SignupGender], [SignupIDNo], [SignupEmailAddress], [CurrentProvider], [CurrentSpeed], [CurrentUsage]) VALUES (#SignupName, #SignupGender, #SignupIDNo, #SignupEmailAddress, #CurrentProvider, #CurrentSpeed, #CurrentUsage)"
If Not Page.IsValid Then Exit Sub
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim updateSql3 As String = "Select [PersonId] FROM [Users] WHERE [Email] = #Email"
Dim PersonId As Integer
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(updateSql3, myConnection)
myCommand.Parameters.AddWithValue("#Email", TextBoxEmail.Text)
PersonId = myCommand.ExecuteScalar()
myConnection.Close()
End Using
Dim updateSql2 As String = " INSERT INTO [Survey_Legal] ([LegalInsurance],[ThirdParty], [LegalIssues], [RequestLegal], [PersonId], [Category_Type]) VALUES (#LegalInsurance, #ThirdParty, #LegalIssues, #RequestLegal, #PersonId, #Type )"
Using myConnection2 As New SqlConnection(connectionString)
myConnection2.Open()
Dim myCommand2 As New SqlCommand(updateSql2, myConnection2)
myCommand2.Parameters.AddWithValue("#LegalInsurance", DDLLegal1.SelectedValue)
myCommand2.Parameters.AddWithValue("#ThirdParty", DDLLegal2.SelectedValue)
myCommand2.Parameters.AddWithValue("#LegalIssues", DDLLegal3.SelectedValue)
myCommand2.Parameters.AddWithValue("#RequestLegal", DDLLegal4.SelectedValue)
myCommand2.Parameters.AddWithValue("#PersonId", PersonId)
myCommand2.Parameters.AddWithValue("#Type", "Legal-Insurance")
myCommand2.ExecuteNonQuery()
myConnection2.Close()
End Using
This is how I do this. I check for a duplicate email address in my stored procedure with an output parameter.
CREATE Procedure sp_AddSubscriber
#Name as nvarchar(50),
#Email as nvarchar(50),
#AddSubscriber bit OUTPUT
AS
IF (SELECT COUNT(Email)
FROM TSubscribers
WHERE Email = #Email) = 0
BEGIN
INSERT TSubscribers (Name, Email)
VALUES (#Name, #Email)
SET #AddSubscriber = False
END
ELSE
SET #AddSubscriber = True
GO

ASP.NET - Could not find stored procedure

I've been searching the depths of the internet and all the solutions I found did not solve this problem.
I am using Visual Web Developer 2010 Express with SQL Server 2008, using VB.
I am trying to execute a stored procedure to insert some data coming from a textbox control to a database, if the id doesn't exist it inserts both the id given in the textbox and the current date (time_scanned_in), if the id exists already, it will insert the current datetime in the [time_scanned_out] column, if all 3 fields in the db are full, it will return #message = 1.
Here is the sql stored procedure:
ALTER PROCEDURE dbo.InsertDateTime
#barcode_id nchar(20),
#message char(1) = 0 Output
AS
BEGIN
if not exists(select * from tblWork where barcode_id = #barcode_id)
begin
INSERT INTO [tblWork] ([barcode_id], [time_scanned]) VALUES (#barcode_id, GetDate())
end
else if exists(select * from tblWork where barcode_id = #barcode_id AND time_scanned_out IS NOT NULL )
begin
SET #message=1
end
else if exists(select * from tblWork where barcode_id = #barcode_id AND time_scanned_out IS NULL)
begin
UPDATE [tblWork] SET [time_scanned_out] = GetDate() WHERE [barcode_id] = #barcode_id
end
RETURN #message
end
If I execute this (by right clicking on the SP), it works flawlessly and returns the values when all fields have been filled.
But when executed through the vb code, no such procedure can be found, giving the error in the title.
Here is the vb code:
Dim opconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Dim sqlConnection1 As New SqlConnection(opconn)
Dim cmd As New SqlCommand
Dim returnValue As Object
cmd.CommandText = "InsertDateTime"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
With cmd.Parameters.Add(New SqlParameter("#barcode_id", TextBox.Text))
End With
With cmd.Parameters.Add(New SqlParameter("#message", SqlDbType.Char, 1, Label3.Text))
End With
returnValue = cmd.ExecuteScalar()
sqlConnection1.Close()
Note, I haven't done the code for the return part yet, will do that once I get it to locate the SP.
Tried listing all objects with the sys.objects.name for each of the databases in a gridview, it listed everything but the stored procedure I want.
Why is this, any ideas? Would be much appreciated, spent hours trying to find a solution.
If anyone needs any more code or information feel free to ask.
try cmd.parameters.clear() first and then start adding parameters in cmd object. also instead of cmd.executescaler(), try cmd.executenonquery or cmd.executeReader()
Try this
cmd.Parameters.AddWithValue("#barcode_id", TextBox.Text)
SqlParameter prmOut = cmd.Parameters.Add("#message",SqlDbType.Char, 1)
prmOut.Value = Label3.Text
prmOut.Direction = ParameterDirection.InputOutput
cmd.ExecuteNonQuery()
returnValue = prmOut.Value.ToString()
Recreated the whole project with a whole new database, copied all the same code, and now it all works flawlessly! Still have no idea what was wrong, but thank you all, you were all prompt and knowledgable.
Here was the final VB code for anyone who's interested:
Dim myConnection As New SqlConnection(opconn)
Dim cmd As New SqlCommand()
Dim myReader As SqlDataReader
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = myConnection
cmd.CommandText = "InsertTimes"
cmd.Parameters.AddWithValue("#message", OleDbType.Integer)
cmd.Parameters.AddWithValue("#barcode_id", TextBox.Text)
cmd.Parameters("#message").Direction = ParameterDirection.Output
Try
myConnection.Open()
myReader = cmd.ExecuteReader()
Dim returnMessage As String = cmd.Parameters("#message").Value
If returnMessage = 1 Then
label_confirmation.Text = "Record successfully submitted!"
TextBox.Text = ""
ElseIf returnMessage = 2 Then
label_confirmation.Text = "A finish time already exists for the record '" & TextBox.Text & "', would you like to override the finish time anyway?"
button_yes.Visible = True
button_no.Visible = True
ElseIf returnMessage = 3 Then
label_confirmation.Text = "Record submitted, work operation status complete!"
TextBox.Text = ""
End If
Catch ex As Exception
label_confirmation.Text = ex.ToString()
Finally
myConnection.Close()
End Try

How can I update a database table programmatically?

I have a button which when pressed, sets the user's rights in the db. (If Administrator UserTypeID is set to '2' and if Customer it is set to '1'). However when I run the below code, everything remains the same. I think it's from the SQL statement but I;m not sure. Can anyone help please?
Protected Sub btnSetUser_Click(sender As Object, e As System.EventArgs) _
Handles btnSetUser.Click
Dim conn As New OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\...\WebSite3\db.mdb;")
Dim cmd As OleDbCommand = _
New OleDbCommand("UPDATE [User] SET [UserTypeID] WHERE Username=?", conn)
conn.Open()
cmd.Parameters.AddWithValue("#Username", txtUser.Text)
If ddUserType.SelectedItem.Text = "Administrator" Then
cmd.Parameters.AddWithValue("#UserTypeID", "2")
cmd.ExecuteNonQuery()
lblSetUser.Text = txtUser.Text + "was set to Administrator."
ElseIf ddUserType.SelectedItem.Text = "Customer" Then
cmd.Parameters.AddWithValue("#UserTypeID", "1")
cmd.ExecuteNonQuery()
lblSetUser.Text = txtUser.Text + "was set to Customer."
End If
conn.Close()
End Sub
End Class
If you add a parameter #Username your command should have such a parameter
SELECT [UserTypeID] FROM [User] WHERE Username = #Username
Also, you add an additional parameter later, which does not occur at all in your query! You call cmd.ExecuteNonQuery(), which works only for INSERT, UPDATE and DELETE queries.
Your query should probably look like this
UPDATE [User]
SET UserTypeID = #UserTypeID
WHERE Username = #Username
Dim cmd As OleDbCommand = New OleDbCommand( _
"UPDATE [User] SET UserTypeID = #UserTypeID WHERE Username = #Username", conn)
Dim userType As String = ddUserType.SelectedItem.Text
Dim userTypeId As Integer = If(userType = "Administrator", 2, 1)
cmd.Parameters.AddWithValue("#UserTypeID", userTypeId)
cmd.Parameters.AddWithValue("#Username", txtUser.Text)
conn.Open()
cmd.ExecuteNonQuery()
lblSetUser.Text = txtUser.Text + "was set to " & userType
UPDATE (some clarifications)
In "UDATE [User] SET UserTypeID = #UserTypeID WHERE Username = #Username"
[User] is the name of the table
UserTypeID is the name of the user type id column
#UserTypeID is the name of the user type id parameter (the new value)
Username is the name of the user name column
#Username is the name of the user name parameter
You might have to change these names in order to match your actual situation.
You are only performing a Select Query - which will not modify any data at all.
You will want to use an Update Query, supplying parameters for both the username and the user rights number.
You're doing a SELECT instead of an UPDATE...
New OleDbCommand("SELECT [UserTypeID] FROM [User] WHERE Username=?", conn)
should be
New OleDbCommand("UPDATE [User] SET [UserTypeID] = #UserTypeID WHERE Username = #Username", conn)

Resources