How can I update a database table programmatically? - asp.net

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)

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());
}

ASP.NET Login to grant access to specific type of group of people

Have a asp.net(vb.net) login page that I need set up to grant access to users base on EmployeeTypeID. The following code needs to be converted into vb.net from Access vb6 or written in vb.net
If rs!EmployeeTypeID = 2 Then
rs.Close
Me.LoginLabel.Visible = False
DoCmd.OpenForm "DetectIdleTIme", , , , , acHidden
DoCmd.OpenForm "frmProcessTimer", , , , , acHidden
DoCmd.OpenForm "frmCRMControlCenter"
DoCmd.Close acForm, Me.Name
Exit Sub
End If
If rs!EmployeeTypeID = 3 Then
Dim prop As Property
On Error GoTo SetProperty
If MsgBox("Would you like to turn on the ByPass Key?", vbYesNo, "Allow Bypass?") = vbYes Then
CurrentDb.Properties("AllowBypassKey") = True
Else
CurrentDb.Properties("AllowBypassKey") = False
End If
rs.Close
Me.LoginLabel.Visible = False
DoCmd.OpenForm "DetectIdleTIme", , , , , acHidden
DoCmd.OpenForm "frmProcessTimer", , , , , acHidden
DoCmd.OpenForm "frmCRMControlCenter"
DoCmd.Close acForm, Me.Name
Exit Sub
This should help :)
Protected Sub UserLogin()
Dim Username As String = Me.txtUserName.Text
Dim Password As String = Me.txtPassword.Text
Dim Connstr As String = "SERVER:BLAHBALHUID" ' Your connection string <<<<
Dim con As SqlConnection = New SqlConnection(Connstr)
'Query string - using paramters (#User and #Pwd to set the username and password criteria)
Dim qry As String = "SELECT Username, Password, EmployeeTypeID FROM Employees WHERE Username =#User AND Password=#Pwd"
Dim cmd As SqlCommand = New SqlCommand(qry, con)
'Using cmd.paramters means that you wont get any SQL injections
'- definately google SQL injections and check out some of the Youtubes!! :)
cmd.Parameters.Add("#User", SqlDbType.VarChar).Value = Username
cmd.Parameters.Add("#Pwd", SqlDbType.VarChar).Value = Password
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader
Dim Found_A_Record As Boolean = False
Dim EmployeeType As String = Nothing
While rdr.Read
'if there is a row - then we have found the username and password that matches
'Therefore - this must be a user with the username and matching password
Found_A_Record = True
EmployeeType = rdr("EmployeeTypeID")
End While
cmd.Dispose()
con.Close()
If Not Found_A_Record Then
'No records found - exit? or do whatever would be for not correct details
End If
Select Case EmployeeType
Case "1"
Response.Redirect("~/CustomerRelationshipManagement.aspx")
Case "2"
Response.Redirect("~/CRMControlCenter.aspx")
Case "3"
Response.Redirect("~/CRMControlCenter.aspx")
Case Else
Response.Write("<script>alert('Incorrect Username or Password.', 'Login Failed')</script>")
End Select
End Sub

ASP.Net Login Page with MySQL

Can anyone spot the error in this? I'm trying to create a simple login page (asp.net vb) that does a count on a mysql table. When i type anything in it logs me in even if the details do not match. I believe it'll be the case statement that's wrong but any help would be appreciated!
Protected Sub ValidateUser(sender As Object, e As EventArgs)
Dim userId As Integer = -1
Dim constr As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
Using con As New MySqlConnection(constr)
Using uscmd As New MySqlCommand("SELECT COUNT(*) FROM tblUser WHERE UName = ?#Username AND Pword = ?#Password", con)
uscmd.Parameters.AddWithValue("#Username", Login1.UserName)
uscmd.Parameters.AddWithValue("#Password", Login1.Password)
Using uuda As New MySqlDataAdapter(uscmd)
Dim ds As New DataSet()
uuda.Fill(ds)
userId = ds.Tables(0).Rows.Count.ToString()
End Using
End Using
Select Case userId
Case -1
Login1.FailureText = "Username and/or password is incorrect."
Exit Select
Case -2
Login1.FailureText = "Account has not been activated."
Exit Select
Case Else
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
Exit Select
End Select
End Using
End Sub
Your query "SELECT COUNT()..." will always return 1 record. After execute the query, you make an assignment
userId = ds.Tables(0).Rows.Count.ToString()
So the value of userId will be always 1. So it always run into CASE ELSE of the CASE statement. That's why whatever you type, it logs you in even if the details do not match.
To check the username and password have been registered or not, you could update your code like following
Protected Sub ValidateUser(sender As Object, e As EventArgs)
Dim userCount As Integer = -1
Dim constr As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
Using con As New MySqlConnection(constr)
Using uscmd As New MySqlCommand("SELECT COUNT(*) FROM tblUser WHERE UName = ?#Username AND Pword = ?#Password", con)
uscmd.Parameters.AddWithValue("#Username", Login1.UserName)
uscmd.Parameters.AddWithValue("#Password", Login1.Password)
Using uuda As New MySqlDataAdapter(uscmd)
Dim ds As New DataSet()
uuda.Fill(ds)
Integer.TryParse(ds.Tables(0).Rows(0)(0), userCount)
End Using
End Using
If userCount > 0 Then
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
Else
Login1.FailureText = "Username and/or password is incorrect."
End If
End Using
End Sub

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

Providing Search facility

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

Resources