how to check existed username when signUp - asp.net

I want to check if the username is already exist or not. this what I've reached but it's not working.
Dim cmdstr As String = "Select count(*) from Registration where username = '" & txtName.Text & "'"
Dim userExist As SqlCommand = New SqlCommand(cmdstr, con)
Dim temp As Integer = Convert.ToInt32(userExist.ExecuteScalar().ToString())
If (temp = 1) Then
Response.Write("user name is already Exist!!")
End If

Your open for SQL-Injection. Don't concatenate strings to a sql-query but use SqlParameters
You haven't opened the connection (i assume)
Here's a full sample:
Public Shared Function GetUserCount(userName As String) As Int32
Const sql = "SELECT COUNT(*) FROM Registration where username = #UserName"
Using con As New SqlConnection(connectionString)
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#UserName", userName)
con.Open()
Using reader = cmd.ExecuteReader()
If reader.HasRows
reader.Read()
Dim count As Int32 = reader.GetInt32(0)
Return count
End If
End Using
End Using
End Using
End Function
and use the method in this way:
Dim userCount As Int32 = GetUserCount(txtName.Text.Trim())
If userCount > 0
LblWarning.Text = "User-name already exists!"
End If

Related

Forgot Password asp.net

This is about forgot password. The error facing is index out of range for this statement " If ds.Tables(0).Rows.Count > 0 Then"
Dim com As New MySqlCommand
Dim dr As MySqlDataReader
conn.Open()
Dim query As String
query = "select Password, CustomerName from userdetail where Email = #Email"
com = New MySqlCommand(query, conn)
com.Parameters.AddWithValue("#Email", Email.Text)
dr = com.ExecuteReader
If dr(0).ToString > 0 Then
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("xxx", "xxx")
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress("xxx")
e_mail.To.Add(Email.Text)
e_mail.Subject = "Your Password Details"
e_mail.IsBodyHtml = True
e_mail.Body = "Hi, <br/>Please check your Login Detailss<br/><br/>Your Username: " &
Convert.ToString(ds.Tables(0).Rows(0)("CustomerName")) & "<br/><br/>Your Password: " &
Convert.ToString(ds.Tables(0).Rows(0)("Password")) & "<br/><br/>"
Smtp_Server.Send(e_mail)
Else
Label7.Text = "The Email you entered not exists"
End
conn.Close()
My database design:
UserId, Password, CustomerName, Contact, Email, Status
Ok you have changed the question and now you are mixed up between MySqlDataReaders and DataSet
the MySqlDataReader solution should look more like
Using cn As New MySqlConnection("YOURCONNECTIONSTRING")
cn.Open()
Using cmd As New MySqlCommand("select Password, CustomerName from userdetail where Email = #Email", conn)
cmd.Parameters.AddWithValue("#Email", Email.Text)
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.Read() Then
'Did find a record to access the fields use = dr("FieldName").ToString()
Else
'didnt find a record
End If
dr.Close()
dr = Nothing
End Using
End Using
Using will take care of disposing the command and connection for you.
However I haven't tested this so emphasis the "look more like" and all this said David's comment is totally correct. Sending passwords in emails is never good.
You need to populate the ds, which I am assuming is a Dataset?..
Dim queryString As String =
"select Password, CustomerName from userdetail where Email = #Email"
Dim cmd As SqlCommand = conn.CreateCommand()
Dim da As New SqlDataAdapter()
cmd.Parameters.AddWithValue("#Email", Email.Text)
cmd.CommandText = queryString
da.SelectCommand = cmd
Dim ds As New DataSet()
conn.Open()
da.Fill(ds)
Then you can check your DataSet for the record. You also need to make sure the following apply:
The Email field is unique
A link sent to the user to enable them to reset the password, and not send clear text.

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.

Inserting new values in database Asp .Net

I have a code for inserting values in ASP.net using vb. I'm having problem with my code says login failed, cannot open database.
Dim struser, strpass, stremail As String
struser = TextBox1.Text
strpass = TextBox2.Text
stremail = TextBox4.Text
'declaring sql connection.
Dim thisConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("DatabaseConnection").ConnectionString)
'Create Command object
Dim nonqueryCommand As SqlCommand = thisConnection.CreateCommand()
Try
' Open Connection
thisConnection.Open()
Dim strcommand As String
strcommand = "Insert into Account (Username,Password, Email) values ('" + struser + "','" + strpass + "','" + stremail + "')"
Dim sqlcomm As New SqlCommand(strcommand, thisConnection)
Dim o As String = sqlcomm.ExecuteNonQuery()
Catch ex As SqlException
' Display error
MsgBox(ex.ToString())
Finally
' Close Connection
MsgBox("Success")
thisConnection.Close()
End Try
connection string:
<add name="DatabaseConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=o2database.mdf;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>
1) Initial catalog must be name of the schema you are accessing
2) You may use 'Server Explorer' & try to just connect to the database
from there. Once succeeded just copy the connection string from
properties & replace your current connection string.
I think your Initial Catalog is wrong. your pointing at a file you should use here the database-name. I guess o2database.
if this is not the case - you are using SSPI to login - maybe your user does not have the permission to do so.
another thing is that your web-application is not configured in the iis to pass on your domain-user credentials - so it cannot work using SSPI to login.
your code is right, the problem is with your sql server configuration, you cannot access sql server with integrated security, so, you need to configure it to work fine, take a look at this post:
http://support.microsoft.com/kb/914277
if you're in IIS, you should able the remote access on sql server too.
Look how to access using SSI:
http://msdn.microsoft.com/en-us/library/aa984236(v=vs.71).aspx
http://msdn.microsoft.com/pt-br/library/bsz5788z.aspx
Warning : You are giving rise to SQL Injection in your code.
Sample Stored Procedure
Create Proc ProcedureName
#UserName Varchar(50),
#Password Varchar(50),
#Email Varchar(50)
As
SET NOCOUNT ON
SET XACT_ABORT ON
Begin Try
Begin Tran
Insert into Account (Username,Password, Email)
Values(#UserName, #Password, #Email)
Commit Tran
End Try
Begin Catch
Rollback Tran
End Catch
Sample code in C Sharp
private void InsertRecord()
{
String struser = string.Empty, strpass = string.Empty, stremail = string.Empty;
using (SqlConnection con = new SqlConnection("Your Connection String"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure name";
SqlParameter[] param = new SqlParameter[3];
param[0].Direction = System.Data.ParameterDirection.Input;
param[0].ParameterName = "UserName";
param[0].Value = struser;
cmd.Parameters.Add(param[0]);
param[1].Direction = System.Data.ParameterDirection.Input;
param[1].ParameterName = "Password";
param[1].Value = strpass;
cmd.Parameters.Add(param[1]);
param[2].Direction = System.Data.ParameterDirection.Input;
param[2].ParameterName = "Email";
param[2].Value = stremail;
cmd.Parameters.Add(param[2]);
cmd.ExecuteNonQuery();
}
}
}
Sample Code in VB.Net
Private Sub InsertRecord()
Dim struser As [String] = String.Empty, strpass As [String] = String.Empty, stremail As [String] = String.Empty
Using con As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = System.Data.CommandType.StoredProcedure
cmd.CommandText = "Your Stored Procedure name"
Dim param As SqlParameter() = New SqlParameter(2) {}
param(0).Direction = System.Data.ParameterDirection.Input
param(0).ParameterName = "UserName"
param(0).Value = struser
cmd.Parameters.Add(param(0))
param(1).Direction = System.Data.ParameterDirection.Input
param(1).ParameterName = "Password"
param(1).Value = strpass
cmd.Parameters.Add(param(1))
param(2).Direction = System.Data.ParameterDirection.Input
param(2).ParameterName = "Email"
param(2).Value = stremail
cmd.Parameters.Add(param(2))
cmd.ExecuteNonQuery()
End Using
End Using
End Sub

getting the result of a sql statement in vs2010 vb.net

I am doing a sql statement to get all the data that starts with "A" in the database.
Sub searchMap()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("WeddingPerfectionConnectionString").ConnectionString
Dim connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "SELECT LocationName FROM MapSearch WHERE LocationName=" Like ("1%")
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim customerId As Integer
If (reader.Read()) Then
customerId = reader.GetValue(0)
End If
reader.Close()
End Sub
And i would like to get the result and display it in a lable.
How can i go about doing it?
In SQL-Server:
Dim sql As String = "SELECT LocationID, LocationName FROM MapSearch WHERE LocationName LIKE 'A%'"
LIKE (Transact-SQL)

Resources