Creating User twice in sql server for new registration - asp.net

I'm trying to create a new user and everything works fine but it enters the same records twice to my db. I have already tried to kept some breakpoints but couldn't find where am I going wrong.
This is my Registration.aspx code:
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim msg As MailMessage
Dim UserID As String
Dim ActivationUrl As String = String.Empty
Dim emailId As String = String.Empty
UserID = Guid.NewGuid.ToString
'Create ConnectionString and Inser Statement
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim insertSql As String = "INSERT INTO Users (UserID,UserName,Password,Email,Mobile,Address,CreatedDate)" & " values (#UserID,#UserName,#Password,#Email,#Mobile,#Address,#CreatedDate)"
'Create SQL connection
Dim con As New SqlConnection(connectionString)
'Create SQL Command And Sql Parameters
Dim cmd As New SqlCommand(insertSql, con)
Dim usernumber As New SqlParameter()
usernumber.ParameterName = "#UserID"
usernumber.Value = UserID
cmd.Parameters.Add(usernumber)
Dim username As New SqlParameter()
username.ParameterName = "#Username"
username.Value = txtUserName.Text.ToString()
cmd.Parameters.Add(username)
Dim password As New SqlParameter()
password.ParameterName = "#Password"
password.Value = txtPassword.Text.ToString()
cmd.Parameters.Add(password)
Dim email As New SqlParameter()
email.ParameterName = "#Email"
email.Value = txtEmail.Text.ToString()
cmd.Parameters.Add(email)
Dim mobile As New SqlParameter()
mobile.ParameterName = "#Mobile"
mobile.Value = txtMobile.Text.ToString()
cmd.Parameters.Add(mobile)
Dim address As New SqlParameter()
address.ParameterName = "#Address"
address.Value = txtAddress.Text.ToString()
cmd.Parameters.Add(address)
Dim createddate As New SqlParameter()
createddate.ParameterName = "#CreatedDate"
createddate.Value = Date.Now.ToString("MM/dd/yyyy hh:mm:ss tt")
cmd.Parameters.Add(createddate)
Try
con.Open()
cmd.ExecuteNonQuery()
lblMsg.Text = "User Registration successful"
Catch ex As SqlException
Dim errorMessage As String = "Error in registering user"
errorMessage += ex.Message
Throw New Exception(errorMessage)
Finally
con.Close()
End Try
Try
'Sending activation link in the email
msg = New MailMessage()
Dim smtp As New SmtpClient()
emailId = txtEmail.Text.Trim()
'sender email address
msg.From = New MailAddress("voletykiran#gmail.com")
'Receiver email address
msg.[To].Add(emailId)
msg.Subject = "Confirmation email for account activation"
'For testing replace the local host path with your lost host path and while making online replace with your website domain name
ActivationUrl = Server.HtmlEncode("http://localhost:8769/UserRegistration/ActivateAccount.aspx?UserID=" & FetchUserId(emailId) & "&Email=" & emailId)
msg.Body = "Hi " & txtUserName.Text.Trim() & "!" & vbLf & "Thanks for showing interest and registring in <a href='http://www.webcodeexpert.com'> webcodeexpert.com<a> " & " Please <a href='" & ActivationUrl & "'>click here to activate</a> your account and enjoy our services. " & vbLf & "Thanks!"
msg.IsBodyHtml = True
smtp.Credentials = New NetworkCredential("voletykiran#gmail.com", "india#1a")
smtp.Port = 587
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
smtp.Send(msg)
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Confirmation Link to activate account has been sent to your email address');", True)
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
Return
Finally
ActivationUrl = String.Empty
emailId = String.Empty
con.Close()
End Try
End Sub
Private Function FetchUserId(emailId As String) As String
Dim cmd As New SqlCommand()
cmd = New SqlCommand("SELECT UserID FROM users WHERE Email=#Email", con)
cmd.Parameters.AddWithValue("#Email", emailId)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim UserID As String = Convert.ToString(cmd.ExecuteScalar())
con.Close()
cmd.Dispose()
Return UserID
End Function
Private Sub clear_controls()
txtUserName.Text = String.Empty
txtPassword.Text = String.Empty
txtConfirmPassword.Text = String.Empty
txtEmail.Text = String.Empty
txtMobile.Text = String.Empty
txtAddress.Text = String.Empty
txtUserName.Focus()
End Sub
Can anyone say me where am I misleading?

Related

VB.Net Code not executing when value is not nullorempty

I'm trying to make fb login for my website. So I put condition if user already exist then it will do login & if not then it perform insert user data.
In following code if string is Not Null Or Empty then I am trying to execute code but by putting breakpoint on my statement I see that if string has value then rest code not executing. What could be the reason? Is I am doing something wrong? My first block of code is working fine(users data fetching from facebook). Problem is in second block where I am checking condition.
Private Sub login_Load(sender As Object, e As EventArgs) Handles Me.Load
FaceBookConnect.API_Key = "XXXXXXX"
FaceBookConnect.API_Secret = "XXXXXXX"
If Not IsPostBack Then
If Request.QueryString("error") = "access_denied" Then
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('User has denied access.')", True)
Return
End If
Dim code As String = Request.QueryString("code")
If Not String.IsNullOrEmpty(code) Then
Dim data As String = FaceBookConnect.Fetch(code, "me")
Dim faceBookUser As FaceBookUser = New JavaScriptSerializer().Deserialize(Of FaceBookUser)(data)
faceBookUser.PictureUrl = String.Format("https://graph.facebook.com/{0}/picture", faceBookUser.Id)
pnlFaceBookUser.Visible = True
lblId.Text = faceBookUser.Id
lblUserName.Text = faceBookUser.UserName
lblName.Text = faceBookUser.Name
lblEmail.Text = faceBookUser.Email
ProfileImage.ImageUrl = faceBookUser.PictureUrl
btnLogin.Enabled = False
End If
End If
If IsPostBack Then
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 50000
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Response.Write("User Already Exist")
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
dr.Close()
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Response.Write("User Added")
Catch ex As Exception
Response.Write(ex)
End Try
End If
con.Close()
End If
End If
End Sub
End Class

Facebook & Google Login for asp.net website

For my asp.net website I was trying put feature of FB & Google Login. I found tutorial from ASPSNIPPETS. Now in this what I have done is If user click on Facebook Login button then It first authorize the user & get user details in panel. Then I put my code to check whether user already exist in my db or not. If not then it Inserts user & then put login code. My Problem is after executing first line of code it stops executing further so that It is unable to check whether user is logged in or not & so on. I think it may be because of redirect url which stops further codes o execute. How Can I eliminate this problem?
Protected Sub Login(sender As Object, e As EventArgs)
FaceBookConnect.Authorize("user_photos,email", Request.Url.AbsoluteUri.Split("?"c)(0))
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
welcome.Visible = True
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
dr.Close()
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
End Try
Dim con2 As New MySqlConnection("connectionstring")
con2.Open()
Dim cmd3 As New MySqlCommand("Select ID, email From users where ID=#id", con2)
cmd3.Parameters.AddWithValue("#id", lblId.Text)
Dim dr2 As MySqlDataReader = cmd3.ExecuteReader()
If dr2.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con2)
con2.Open()
Dim da As New MySqlDataAdapter(cmd3)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Catch ex As Exception
Response.Write(ex)
con2.Close()
End Try
con.Close()
End If
End If
End If
con.Close()
End Sub
First you can optimise your code :
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim str As String = "select * from users where ID=#id"
con.Open()
Dim cmd2 As New MySqlCommand(str, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim da As New Common.DataAdapter(cmd2)
Dim ds As New Data.DataSet()
da.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
'Do Login Code here
Try
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
welcome.Visible = True
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values(#id, #img,#name)"
Dim cmd As New MySqlCommand
cmd = New SqlCommand(req, con)
cmd.Parameters.Add(New SqlParameter("#id", lblId.Text))
cmd.Parameters.Add(New SqlParameter("#img", ProfileImage.ImageUrl.ToString))
cmd.Parameters.Add(New SqlParameter("#name", lblName.Text))
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
End Try
'After insertion you don't have to select from database just send the parameters to cookies
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
End If
con.Close()
End If

How to Use a parameter within SQL in Vb 2010 (web developer)

I am trying to work out SQL code in VB but I am having problems I have a simple database with the table admin with the columns UserName and Password.
I want to be able to read data from a text box and then input it into a SQL string… the SQL string works (I've tested it) and I can get it to output with a simple SELECT statement but I can't seem to get the SQL to read my Parameter.
Help?
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call Password_Check(txtTestInput.Text)
End Sub
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", Answer)
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
in your code above:
--> Dim parameter As New SqlParameter("#Username", Answer)
Can I suggest two options:
Dim parameter As New SqlParameter("#Username", sqldbtype.nvarchar)
parameter.value = Answer
or
cmd.CommandText = string.format("SELECT Password FROM Admin WHERE (UserName = {0})", Answer)
Full Code:
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", SqlDbType.NVarChar)
parameter.Value = Answer
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
Regarding to your Database system it is possible that it does not support parameter names. Have you tried ? Wat DB System you used?
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = ?)"

query string is throwing exception for being null when its not

Here is whats happening , If the user is logged in - this is called directly from Page_Load
Protected Sub EnterNewTransInDb()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("connstring").ConnectionString)
Dim comm As New SqlCommand("INSERT INTO tblRegisterRedirect (RegID , UserID, EventID, TimeStamp) VALUES (#RegID, #UserID, #EventID , getdate()) ;", conn)
Dim RegID As Guid
RegID = Guid.NewGuid()
Dim GIUDuserid As Guid
GIUDuserid = New Guid(HttpContext.Current.Request.Cookies("UserID").Value.ToString())
Dim GIUDevnetid As New Guid(HttpContext.Current.Request.QueryString("id").ToString())
comm.Parameters.AddWithValue("#RegID", RegID)
comm.Parameters.AddWithValue("#UserID", GIUDuserid)
comm.Parameters.AddWithValue("#EventID", GIUDevnetid)
Try
conn.Open()
Dim i As Integer = comm.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
Dim errors As String = ex.ToString()
End Try
Dim URL As String = Request.QueryString("url").ToString()
Response.Redirect(URL + "?aid=854&rid=" + RegID.ToString())
End Sub
This works great, but if their not logged in , then they enter their log-in credentials - this happens on Button_Click event, in the click event I call this function EnterNewTransInDb() , When I run it this time , after logging in - SAME CODE , it throws an exception - Object reference is null - referring to the querystring
Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click
'took out code SqlConnection onnection and SqlDataReader Code
dbCon.Open()
'If Email and PW are found
If dr.Read Then
Dim appCookie As New HttpCookie("UserID")
appCookie.Value = dr("GUID").ToString()
appCookie.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie)
Dim appCookie1 As New HttpCookie("UserName")
appCookie1.Value = dr("UserName").ToString
appCookie1.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie1)
Dim appCookie2 As New HttpCookie("UserEmail")
appCookie2.Value = txtEmail.Text.ToLower()
appCookie2.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie2)
Dim appCookie3 As New HttpCookie("Lat")
appCookie3.Value = dr("GeoLat").ToString()
appCookie3.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie3)
Dim appCookie4 As New HttpCookie("Long")
appCookie4.Value = dr("GeoLong").ToString()
appCookie4.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie4)
Dim appCookie5 As New HttpCookie("City")
appCookie5.Value = dr("City").ToString()
appCookie5.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie5)
Dim appCookie6 As New HttpCookie("State")
appCookie6.Value = dr("State").ToString
appCookie6.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie6)
HttpContext.Current.Response.Cookies("EO_Login").Expires = Now.AddDays(30)
HttpContext.Current.Response.Cookies("EO_Login")("EMail") = txtEmail.Text.ToLower()
Dim sUserData As String = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserID").Value) & "|" & HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserName").Value) & "|" & HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserEmail").Value)
' Dim sUserData As String = "dbcf586f-82ac-4aef-8cd0-0809d20c70db|scott selby|scottselby#live.com"
Dim fat As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
dr("UserName").ToString, DateTime.Now, _
DateTime.Now.AddDays(6), True, sUserData, _
FormsAuthentication.FormsCookiePath)
Dim encTicket As String = FormsAuthentication.Encrypt(fat)
HttpContext.Current.Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
'If Email and Pw are not found
Else
dr.Close()
dbCon.Close()
End If
'Always do this
dr.Close()
sSql = "UPDATE eo_Users SET LastLogin=GETUTCDATE() WHERE GUID=#GUID; "
cmd = New SqlCommand(sSql, dbCon)
cmd.Parameters.AddWithValue("#GUID", HttpContext.Current.Session("UserID"))
cmd.ExecuteNonQuery()
dbCon.Close()
EnterNewTransInDb()
'Dim URL As String = Request.QueryString("url").ToString()
'Response.Redirect(URL + "?aid=854&rid=" + RegID.ToString())
End Sub
Assuming you only want this code to run if there is a valid QueryString, you could put a guard clause at the beginning of the method to simply check if QueryString is null and then perform some other action if this page is called without a QueryString.
Try setting the breakpoints before the call and make sure the variables are assigned values.
Have you tried putting a breakpoint on Dim URL As String = Request.QueryString("url").ToString() line in your code? Maybe you just need to evaluate first the querystring for the 'url' parameter, if it exists; before converting it to a string.

regarding repsone.redirect in asp.net

Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
Dim Uname As String
Dim pwd As String
Dim pName As String
Dim reader As SqlDataReader
Uname = Login1.UserName
pwd = Login1.Password
pName = ""
Dim strConn As String
strConn = WebConfigurationManager.ConnectionStrings("ConnectionASPX").ConnectionString
Dim Conn As New SqlConnection(strConn)
Conn.Open()
Dim sqlUserName As String
sqlUserName = "SELECT UserName,Password FROM Customer"
sqlUserName &= " WHERE (UserName = #Uname"
sqlUserName &= " AND Password = #Pwd)"
Dim com As New SqlCommand(sqlUserName, Conn)
com.Parameters.AddWithValue("#Uname", Uname)
com.Parameters.AddWithValue("#Pwd", pwd)
reader = com.ExecuteReader()
If (reader.Read()) Then
Me.Response.Redirect("Faq.aspx")
Else
MsgBox("Invalid UserName-password")
End If
reader.Close()
Conn.Close()
'If CurrentName <> "" Then
' Session("UserAuthentication") = Uname
' Response.Redirect("Faq.aspx")
'Else
' Session("UserAuthentication") = ""
'End If
End Sub
the code kis working without any errors . It is not redirecting to another page.
Put a breakpoint (press F9) on the line If (reader.Read()) Then and then press F5 to run the app in debug mode and step through that line to see if it is skipping your Response.Redirect call. If it is, you will have to figure out why the Read() method is returning false.

Resources