Add User to Database not working - asp.net

I'm really new to ASP.net and I am currently trying to create a registration page on a site. I was successful in adding a user to the database but I decided to add another feature into the code to check what userID's were available. For example, if a user deleted their account their userID would become available for use again. I'm trying to find the min value and the max value and add or subtract 1 depending on whether it is min or max. I can run the code I have written for this with no errors but the user is not added to the database. Can anyone help me figure out what I'm missing from my code to do this?
EDIT >>>>>
Code adds a user to database but it adds the new user at -1 instead. I don't seem to be able to see where the issue is.
If (aDataReader2.Read() = False) Then
aConnection1 = New OleDbConnection(aConnectionString)
aConnection1.Open()
aQuery = "Insert Into UserDetails "
aQuery = aQuery & "Values ('" & userID & "','" & userFName & "','" & userLName & "','" & userEmail & "','" & userUsername & "','" & userPassword & "')"
aCommand = New OleDbCommand(aQuery, aConnection1)
aCommand.ExecuteNonQuery()
aConnection1.Close()
ElseIf (min = 1) Then
aConnection2 = New OleDbConnection(aConnectionString)
aConnection2.Open()
aCommand = New OleDbCommand(aQuery3, aConnection2)
aDataReader2 = aCommand.ExecuteReader()
userID = max + 1
aQuery = "Insert Into UserDetails "
aQuery = aQuery & "Values ('" & userID & "','" & userFName & "','" & userLName & "','" & userEmail & "','" & userUsername & "','" & userPassword & "')"
aCommand = New OleDbCommand(aQuery, aConnection2)
aCommand.ExecuteNonQuery()
aConnection2.Close()
Else
aConnection3 = New OleDbConnection(aConnectionString)
aConnection3.Open()
aCommand = New OleDbCommand(aQuery2, aConnection3)
aDataReader2 = aCommand.ExecuteReader
userID = min - 1
aQuery = "Insert Into UserDetails "
aQuery = aQuery & "Values ('" & userID & "','" & userFName & "','" & userLName & "','" & userEmail & "','" & userUsername & "','" & userPassword & "')"
aCommand = New OleDbCommand(aQuery, aConnection3)
aCommand.ExecuteNonQuery()
aConnection3.Close()
lblResults.Text = "User Account successfully created"
btnCreateUser.Enabled = False
End If
Here's the code I used to get the max and min values from the database. I'm getting a value of 0 for both of them - when min should be 1 and max should be 5
Dim minID As Integer
Dim maxID As Integer
aQuery2 = "Select Min(UserID) AS '" & [minID] & "' From UserDetails"
aQuery3 = "Select Max(UserID) AS ' " & [maxID] & "' From UserDetails"

It's hard to say what
t the problem is exactly, since we see only a part of it. Where do min and max come from?
I cannot give you a solution, however, I suggest you to structure your code better. You have a lot (!) of redundant code. This makes the code difficult to read, to understand, to change and to test.
Put the user data into a class. This makes it easier to handle than a lot of individual variables.
Public Class User
Public Property ID As Integer
Public Property FirstName As String
Public Property LastName As String
Public Property EMail As String
Public Property Username As String
Public Property Password As String
End Class
Extract redundant code into subroutines
Private Sub CreateUser(ByVal u As User)
Const InsertQuery As String = _
"INSERT INTO UserDetails VALUES ({0},'{1}','{2}','{3}','{4}','{5}')"
Dim query As String = String.Format(InsertQuery, u.ID, u.FirstName, u.LastName, _
u.Email, u.Username, u.Password)
Using conn As New OleDbConnection(aConnectionString)
conn.Open()
Dim cmd As New OleDbCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
End Sub
The code then becomes something like this
If Not aDataReader2.Read() Then
CreateUser(user)
ElseIf min = 1 Then
...
user.userID = max + 1
CreateUser(user)
Else
...
user.userID = min - 1
CreateUser(user)
lblResults.Text = "User Account successfully created"
btnCreateUser.Enabled = False
End If
This looks much nicer now.
(My code is not tested, it's just to give you an idea.)
UPDATE
You cannot read the min and max values like this. Try something like this
Dim min, max As Integer
Using conn As New OleDbConnection(aConnectionString)
Dim cmd As OleDbCommand = _
New OleDbCommand("SELECT MIN(UserID), MAX(UserID) FROM UserDetails", conn)
conn.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader()
reader.Read()
If reader.IsDBNull(0) Then
' The table is empty
min = 1
max = 1
Else
min = reader.GetInt32(0)
max = reader.GetInt32(1)
End If
End Using
End Using

Related

select from database just can get first data [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Dim reserveTime As String
Dim Timer As String = ddlTime.SelectedValue
Dim dat As String
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Beauty shop\Beauty shop\Beauty.accdb'")
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
Dim reserveDate As String = Calendar1.SelectedDate
Dim bookingTime As String = "SELECT Booking_Date,Booking_Time FROM CustomerBooking where Booking_Date='" & reserveDate & "'"
Dim sqlcommand2 As New OleDbCommand(bookingTime, conn)
Dim dr2 As OleDbDataReader
dr2 = sqlcommand2.ExecuteReader
If dr2.HasRows Then
dr2.Read()
Dim count As Integer = dr2.FieldCount
While dr2.Read()
For i As Integer = 0 To count - 1
dat = dr2.Item("Booking_Date")
reserveTime = dr2.Item("Booking_Time")
Next
End While
dr2.Close()
If Timer = reserveTime And dat = reserveDate Then
ShowTimeLbl.Text = "This time have been reserve"
Else
Dim sqlString As String
sqlString = "Insert INTO CustomerBooking(Customer_Name, Package_Name, Price, Booking_Date, Booking_Time, Card_Bank, Cardholder_Name, Card_Number,Expired_Month,Expired_Date) VALUES ('" & User_Name & "','" & Package_Name & "','" & Price_Package & "','" & Calendar_Book & "','" & Time_Book & "','" & Card_Name & "','" & Card_Holder & "','" & CreditCard_Number & "','" & Month_Card & "','" & Year_Card & "')"
Dim sqlcommand As New OleDbCommand(sqlString, conn)
sqlcommand.ExecuteNonQuery()
conn.Close()
Response.Redirect("ConfirmBook.aspx?Name=" + Master.NameMaster + "&UserName=" + User_Name + "&PackageName=" + Package_Name + "&PackagePrice=" + Price_Package + "&Calender=" + Calendar_Book + "&TimeBook=" + Time_Book + "&CardName=" + Card_Name + "&CardHolder=" + Card_Holder + "&CreditCardNumber=" + CreditCard_Number + "&MonthCard=" + Month_Card + "&YearCard=" + Year_Card)
End If
End If
when i choose time all date cannot run, what is my problem, i want to compare the date and the time, if time has been booking it will show full,but just can read first date , why cannot run second date?the date is same
You have kept an extra dr.Read before while loop.
If dr2.HasRows Then
***dr2.Read()***
Dim count As Integer = dr2.FieldCount
While dr2.Read()
For i As Integer = 0 To count - 1
Remove the extra read() statement and get the field count inside while loop. It should work fine.
If dr2.HasRows Then
While dr2.Read()
Dim count As Integer = dr2.FieldCount
For i As Integer = 0 To count - 1
UPDATE-
I am putting a pseudo code just to give you an idea. There is a lot of room for improvement. But since it is not a code review, I will keep quite on that matter.
query = "SELECT Booking_Date,Booking_Time FROM CustomerBooking where Booking_Date= <inputDate> & and Booking_Time=<inputTime>"
dr2 = get datareader using <query>
If dr2.HasRows Then
'It means there are records in DB with input date and Time so show error
Else
'code to insert'
End If

How to insert the values of 3 droplists into a single column of an MS Access database, using asp.net

In my project i display an 3 droplists (Daydrplist, MonthDropList, YearDropList). When the user selects the values and clicks the button the values should be inserted to the access database in the BirthDate column of the Teacher table.
How can I do that?
Protected Sub NextBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles NextBtn.Click
con = New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\user\Desktop\web programming\\IULWebInformationSystem1\IULWebInformationSystem1\App_Data\IUlDB.accdb;Persist Security Info=True"
con.Open()
sqlquery = "insert into Teacher values ('" & FirstNameTxtBox.Text & "','" & MiddelNameTxtBox.Text & "','" & LastNameTxtBox.Text & "','" & POBTxtBox.Text & "','" & NationalityDropList.SelectedValue & "','" & Gendrplist.SelectedValue & "')"
cmd = New OleDbCommand(sqlquery, con)
cmd.ExecuteNonQuery()
con.Close()
FirstNameTxtBox.Text = ""
MiddelNameTxtBox.Text = ""
LastNameTxtBox.Text = ""
POBTxtBox.Text = ""
NationalityDropList.SelectedValue = ""
Gendrplist.SelectedValue = ""
lblmsg2.Text = "Personal Information was Added Successfully"
lblmsg2.Visible = True
Response.Redirect("PersonalAddress.aspx")
End Sub

How to do I send an email a target group based on stored procedure #Error message?

Please forgive me for asking too many questions.
I have been working on this all day and can't take it anymore.
I have a stored proc called sp_signup()
The stored proc first checks to see if the user has already signed up. If yes, then inform the user that s/he has already signed up for this class.
SET #ERROR = 'You have already signed up for this training'
This works a treat.
If no, then check to see if there are still available seats.
If seats are still available, sign the user up by inserting into training table and inform the user s/her has been signed up.
SET #ERROR = 'You have been registered for this class'
This works a treat.
If no seats remain, then put the user on waiting list by inserting the user's registration info into waitingList table and inform the user s/he has been placed on waiting list.
SET #ERROR = 'Sorry, but this class is full. However, you have been placed on waiting list.'
This works a treat as well.
So, the stored proc, when tested, works great.
However, on our .net app that calls the stored proc, we are sending users emails informing them that they have either been signed up for the class or have been placed on waiting list depending on what the #Error message says.
This is where we are having problem because the email is not going out.
Here are the conditionals for sending email:
If Label1.Text = "You have been registered for this class" Then
'Email code goes here and is sent to inform users they have been registered for class
ElseIf Label1.Text = "Sorry, but this class is full. However, you have been placed on waiting list." Then
'Email code goes here and is sent inform to users they have been placed on waiting list
Else
End If
below is where the stored procedure call is made:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim username = Session("Username")
Try
Dim s As String
s = "sp_signup"
Dim connStr As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim conn As New SqlConnection(connStr)
Dim cmd = New SqlCommand(s, conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#cosID", Request.QueryString("cosId"))
cmd.Parameters.AddWithValue("#locID", Request.QueryString("locid"))
cmd.Parameters.AddWithValue("#dat", Request.QueryString("iddate"))
cmd.Parameters.AddWithValue("#UserName", username)
cmd.Parameters.Add("#ERROR", SqlDbType.[Char], 500)
cmd.Parameters("#ERROR").Direction = ParameterDirection.Output
conn.Open()
cmd.ExecuteNonQuery()
message = DirectCast(cmd.Parameters("#ERROR").Value, String)
Dim cmdGetKey As New SqlCommand("SELECT ##IDENTITY", conn)
Dim skey As Integer = cmdGetKey.ExecuteScalar()
Session("TrainingId") = skey
conn.Close()
btnSendEmail_Click()
'Display some feedback to the user to let them know it was processed
Label1.ForeColor = System.Drawing.Color.Green
Label1.Text = message
Catch
'If the message failed at some point, let the user know
Label1.ForeColor = System.Drawing.Color.Red
Label1.Text = message
End Try
End Sub
The email code has been tested and works without the stored proc and is below:
Protected Sub btnSendEmail_Click()
Dim skey As Integer = Session("TrainingId")
'Response.Write(skey)
'Response.End()
Dim Conn As SqlConnection
'Dim param As SqlParameter
'Dim cmdcommand As SqlCommand
Conn = New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString)
Conn.Open()
If Label1.Text = "You have been registered for this class" Then
Dim emailcmd As New SqlCommand("select distinct lg.Email, lg.fullname, c.CourseName, l.location, d.trainingDates, d.trainingTime, i.instructorName from tblTrainings t Inner Join tblCourses c on t.courseId = c.courseId " & _
" Inner Join tblLocations l on t.locationId = l.LocationId " & _
" Inner Join tblTrainingDates d on t.dateid=d.dateid " & _
" Inner Join tblCourseInstructor ic on c.courseId = ic.CourseId " & _
" Inner Join tblInstructors i on ic.instructorId = i.instructorId " & _
" Inner Join tblLogin lg on t.username = lg.username where lg.username = '" & Session("username") & "' AND t.CourseID = " & Request.QueryString("cosId") & " AND t.LocationID = " & Request.QueryString("locid") & " AND t.dateId = " & Request.QueryString("iddate") & " AND TrainingId = " & skey & ";", Conn)
Dim dr = emailcmd.ExecuteReader()
If dr.Read() Then
email = dr.GetString(0)
fullname = dr.GetString(1)
courses = dr.GetString(2)
Loc = dr.GetString(3)
tdates = dr.GetDateTime(4)
ttime = dr.GetString(5)
End If
'code for other email requests
Dim objSmtpClient As SmtpClient = New SmtpClient("relay.smtp", 25)
Dim objSender As MailAddress = New MailAddress("name.emailadd.com", "name.emailadd.com")
Dim objMail As MailMessage = New MailMessage("name.emailadd.com", "name.emailadd.com")
objMail.Bcc.Add("name.emailadd.com")
objMail.To.Add(email)
'objMail.CC.Add("name.emailadd.com")
objMail.Subject = "About Your Training: " & courses & ""
objMail.Body = " Dear " & fullname & " <br>You have just signed up for <b>" & courses & "</b> training. <br><br>This training will be held at <b>" & Loc & "</b> on <b>" & tdates & "</b> starting from <b>" & ttime & "</b>.<br><br> For more details about this training, please visit <a href='Training/'> Training/</a>. "
objMail.IsBodyHtml = True
objSmtpClient.Send(objMail)
dr.Close()
ElseIf Label1.Text = "Sorry, but this class is full. However, you have been placed on waiting list." Then
Dim waitcmd As New SqlCommand("select distinct lg.Email, lg.fullname, c.CourseName, wl.location, d.trainingDates, d.trainingTime, i.instructorName from tblWaitingList wl Inner Join tblCourses c on wl.courseId = c.courseId " & _
" Inner Join tblLocations l on wl.locationId = l.LocationId " & _
" Inner Join tblTrainingDates d on wl.dateid=d.dateid " & _
" Inner Join tblCourseInstructor ic on c.courseId = ic.CourseId " & _
" Inner Join tblInstructors i on ic.instructorId = i.instructorId " & _
" Inner Join tblLogin lg on wl.username = lg.username where lg.username = '" & Session("username") & "' AND wl.CourseID = " & Request.QueryString("cosId") & " AND wl.LocationID = " & Request.QueryString("locid") & " AND wl.dateId = " & Request.QueryString("iddate") & " AND TrainingId = " & skey & ";", Conn)
Dim dr = waitcmd.ExecuteReader()
If dr.Read() Then
email = dr.GetString(0)
fullname = dr.GetString(1)
courses = dr.GetString(2)
Loc = dr.GetString(3)
tdates = dr.GetDateTime(4)
ttime = dr.GetString(5)
End If
'code for other email requests
Dim objSmtpClient As SmtpClient = New SmtpClient("relay.smtp", 25)
Dim objSender As MailAddress = New MailAddress("name.emailadd.com", "name.emailadd.com")
Dim objMail As MailMessage = New MailMessage("name.emailadd.com", "name.emailadd.com")
objMail.Bcc.Add("name.emailadd.com")
objMail.To.Add(email)
'objMail.CC.Add("name.emailadd.com")
objMail.Subject = "About Your Training: " & courses & ""
objMail.Body = " Dear " & fullname & " <br>You have been placed on the waiting list for <b>" & courses & "</b> training. <br><br>This training will be held at <b>" & Loc & "</b> on <b>" & tdates & "</b> starting from <b>" & ttime & "</b>.<br><br> Should a seat become available, notification will be based on first-come, first-served bases.<br>For more details about this training, please visit <a href='http://#/'> http://Training/</a>. "
objMail.IsBodyHtml = True
objSmtpClient.Send(objMail)
dr.Close()
Else
End If
End Sub
I guess you have the order of the following statements wrong:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
...
btnSendEmail_Click()
...
Label1.Text = message
I think you should set Label1.Text before calling btnSendEmail_Click(). It should be the other way round:
Label1.Text = message
...
btnSendEmail_Click()

Error on ExecuteNonQuery();

I get the following error from ExecuteNonQuery()
"String or binary data would be truncated. The statement has been terminated."
The problem is the variable to be sent is bigger that the one in the DB.
I am using the following code:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//GridViewRow row = GridView1.SelectedRow;
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
var Username = (Label)row.FindControl("Label3");
var Password = (Label)row.FindControl("Label4");
var Email = (Label)row.FindControl("Label5");
// var ID_Inscricao = ((Label)row.FindControl("Label1")).Text;
var ID_Inscricao = ((Label)row.FindControl("Label1")).Text;
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["FormacaoConnectionString"].ToString());
SqlCommand sqlComm = new SqlCommand();
sqlComm = sqlConn.CreateCommand();
sqlComm.Parameters.Add("#Username", SqlDbType.Text);
sqlComm.Parameters.Add("#Password", SqlDbType.Text);
sqlComm.Parameters.Add("#Email", SqlDbType.Text);
sqlComm.Parameters.Add("#ID_Inscricao", SqlDbType.Int);
sqlComm.Parameters["#Username"].Value = Convert.ToString(Username);
sqlComm.Parameters["#Password"].Value = Convert.ToString(Password);
sqlComm.Parameters["#Email"].Value = Convert.ToString(Email);
sqlComm.Parameters["#ID_Inscricao"].Value = Convert.ToInt32(ID_Inscricao);
string sql = "INSERT INTO Utilizadores (Username, Password, Email, ID_Inscricao) VALUES (#Username, #Password, #Email, #ID_Inscricao)";
sqlComm.CommandText = sql;
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
}
This happens when you try to insert something into a column that is too long for that column.
For example, when you have a column VARCHAR(10) and you try to insert the value "ABCDEFGHIJKLMNOP". This would lead to the data being truncated and that generates an error.
I can't tell which column it is in your case but it has to be one of Username, Password or Email.
The issue is the data type in the database you are trying to populate is smaller than one of the values you are passing. You need to check each of your parameters #Username, #Password and #Email and see which one is larger than the database data type. Then you can increase the size of the data type in the database if required, or trim the parameter values before sending.
Dim qry As String
qry = "inserg into Table1 values('" & TextBox1.Text & "'+'" & TextBox2.Text & "'+'" & DropDownList1.Text & "'+'" & DropDownList2.Text & "'+'" & TextBox4.Text & "'+'" & TextBox5.Text & "'+'" & RadioButtonList1.Text & "'+'" & RadioButton1.Text & "'+'" & RadioButtonList2.Text & "'+'" & CheckBoxList1.Text & "'+'" & TextBox6.Text & "'+'" & TextBox7.Text & "'+'" & TextBox8.Text & "'+'" & TextBox9.Text & "'+'" & TextBox10.Text & "'+'" & RadioButtonList3.Text & "'"
Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\MCALab\My Documents\net.mdb")
Dim cmd As New OleDbCommand(qry, cn)
cn.Open()
**cmd.ExecuteNonQuery()**this line have error please any one know mean debug it.
cn.Close()

Insert into Access DB (loop)

I have this code and its coming up with an INSERT INTO statement error...
Its probably something but I have been at it for a while... please help.
'Add items to db'
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
For intCounter = 0 To objDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath2 & ";"
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.CommandText = "INSERT INTO order(order_date, coupon_id, customer_id, quantity) values('" & System.DateTime.Now & "','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) & "','" & Int32.Parse(objDR("quantity")) &"')"
myCommand2.Connection = con2
con2.Open()
myCommand2.ExecuteReader()
con2.Close()
test.Text += "Order ID: " & objDR("ID") & "Order Date: " & System.DateTime.Now & ", Cust ID: " & custID & ", Quantity: " & objDR("quantity") &" "
Next
End Function
I think you are getting an error by not enclosing the Date inside Pound signs. You have to do this in Jet (Access) when using variables not parameters.
VALUES('#" & DateTime.Now.Date & "#',...
I also took the liberty of refactoring this code for you since you are creating a new connection for each record which is bad news. Use a Try Catch Finally block and move all that stuff outside the For Loop (please see below)
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" <-- etc
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.Connection = con2
con2.Open()
Try
For intCounter = 0 To obDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
myCommand2.CommandText = "INSERT INTO order(order_date,coupon_id,customer_id,quantity)" _
& "VALUES ('#" & System.DateTime.Now.Date & "#','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) _
& "','" & Int32.Parse(objDR("quantity")) & "')"
myCommand2.ExecuteReader()
Next
Catch ex As Exception
'handle errors here
Finally
If con2.State = ConnectionState.Open Then
con2.Close()
End If
End Try
End Function
Remember to mark as answered if this helps.
I've sorted it out by removing the single quotes. Thanks everybody to contributed to this.

Resources