Inserting new values in database Asp .Net - 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

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.

"Incorrect syntax near 'admin'

this programm when i enter username and password go to data base and compare from table,but when i enter username admin ,password admin(exist in table)
compalier show error "Incorrect syntax near 'admin'" in line
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "select Password from Users where Password'" + TextBoxPassword.Text + "'";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
string password = passComm.ExecuteScalar().ToString();
if (password == TextBoxPassword.Text)
{
//Session["NEW"] = TextBoxUserName.Text;
Response.Redirect("Welcome.aspx");
}
else
{
Response.Redirect("Error.aspx");
}
}
The error is simply caused by the missing equals before the values concatenated in the sql command text.
But also fixing it, your code is wrong for other reasons.
You should ALWAYS use a parameterized query to avoid Sql Injection and parsing problems,
You could remove the COUNT function that causes an unnecessary load of all records just to confirm the existence of your searched data
You need to identify your user searching for both password and
username on the SAME record, as it is now, the code above search first the username
and then a password, but I can type an existing user name (first if passed) and use
a password of a different user (second if passed) and then gain access to
your site.
.
string checkuser = "IF EXISTS(select 1 from [Users] where Username = #usr AND Password=#pwd)
SELECT 1 ELSE SELECT 0";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand com = new SqlCommand(checkuser,conn))
{
conn.Open();
com.Parameters.AddWithValue("#usr", TextBoxUserName.Text);
com.Parameters.AddWithValue("#pwd", TextBoxPassword.Text);
int temp = Convert.ToInt32(com.ExecuteScalar());
if (temp == 1)
Response.Redirect("Welcome.aspx");
else
Response.Redirect("Error.aspx");
}
Other things changed in the example above are the USING STATEMENT to be sure that your connection and command are disposed at the end of the operation also in case of exceptions
Try changing this line
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
to this
string checkuser = "select count(*) from [Users] where Username = '" + TextBoxUserName.Text + "'";
you are missing an = sign
you'll need to do the same to your password select as well, you also missed the = sign there.
string checkpassword = "select Password from Users where Password = '" + TextBoxPassword.Text + "'";
When checking the Password, you should also include the UserName:
string checkpassword = "select Password from Users where UserName = '" + TexBoxUserName.Text + "' AND Password = '" + TextBoxPassword.Text + "'";
If you do not include the UserName the it is only validating that some user has that password.
The following code will prevent SQL injection by paramterizing the command text
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "SELECT Count(UserName) FROM USERS WHERE UserName = #UserName";
SqlCommand com = new SqlCommand(checkuser,conn);
SqlParameter parmUserName = new SqlParameter("UserName", TextBoxUserName.Text);
com.Parameters.Add(parmUserName);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "SELECT Password FROM USERS WHERE UserName = #UserName AND Password = #Password";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
SqlParameter parmPassword = new SqlParameter("Password", TextBoxPAssword.Text);
com.Parameters.Add(parmUserName);
com.Parameters.Add(parmPassword);
string password = passComm.ExecuteScalar().ToString();

how to check existed username when signUp

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

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 = ?)"

CRUD with Access Database using ASP.NET

How can I use Microsoft Access as a database in ASP.NET website? Is it possible?
Yes it possible. You will have to use OLEDB to Access the MS Access Database.
Dim con As New System.Data.OleDb.OleDbConnection
Dim myPath As String
myPath = Server.MapPath("Database1.mdb")
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath & ";"
Dim myCommand As New System.Data.OleDb.OleDbCommand
myCommand.CommandText = "insert into Students(Firstname,Lastname,Address) values('" & txtFirstname.Text & "','" & txtLastname.Text & "','" & txtAddress.Text & "')"
myCommand.Connection = con
con.Open()
myCommand.ExecuteNonQuery()
con.Close()
Taken from: http://www.beansoftware.com/ASP.NET-Tutorials/Connecting-Access-Sql-Server.aspx
It would be the same as SQL Server but you will be using OleDbConnection, OleDbCommand etc
Sure, Access has an oledb connection
Now I would not recommend it unless its a toy app. But yes it can be done.
Yes, It is possible.
Checkout this tutorial.
http://aspalliance.com/429
This isn't online anymore:
http://www.aspfree.com/c/a/Microsoft-Access/Connecting-to-a-Microsoft-Access-database-with-ASPNET/
Yes it's possible, but NOT advisable!
Access was never meant to be used in a highly concurrent environment like the web.
I don't know what type of site you are trying to create, but you're better
of with a real database like SQL Express (Free download on Microsoft)
string strConn ="PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|referendum-abrogrativo.mdb";
OleDbConnection conn = new OleDbConnection(strConn);
try
{
conn.Open();
string query = "SELECT * FROM User WHERE Email = '" + email + "' AND Password = '" + password + "'";
OleDbCommand cmdE = new OleDbCommand();
cmdE.Connection = conn;
cmdE.CommandText = query;
OleDbDataReader dr;
dr = cmdE.ExecuteReader();
if (dr.Read())
{
_IDUte = dr.GetValue(0).ToString();
_Email = dr.GetValue(3).ToString();
_Password = dr.GetValue(4).ToString();
}
else
{
_Email = "";
_Password = "";
}
dr.Close();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}

Resources