Registration allows duplicate user name in Access - c#

I do have a problem in checking username and password in my registration form. When I tend to register the same username and password that's is already in my database(Access), still it allows to register. I just wanna trap it however, I don't know how to that.
What I want to output is that, I want a trap that says "Account Exists, Try Again!" or "Username Exists!"
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using System.Text.RegularExpressions;
namespace Login { public partial class Register : Form {
private OleDbConnection personalConn;
private OleDbCommand oleDbCmd = new OleDbCommand();
private String connParam = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public Register()
{
personalConn = new OleDbConnection(connParam);
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
personalConn.Open();
oleDbCmd.Connection = personalConn;
if (textBox1.Text != "" && textBox2.Text != "")
{
int temp;
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
personalConn.Close();
}
}
catch (Exception)
{
MessageBox.Show("Invalid!, Duplicate Data.");
}
}
Notes: textBox1= username
textBox2= password Your attention is much highly appreciated. Thank you so much in advance.

Here is code which uses oledbcommand parameters using ? placeholder as mentioned in MSDN Reference. Also I have added using block which should Close opened connection implicitly.
using(OleDbConnection con = new OleDbConnection(connParam))
using(OleDbCommand cmd = new OleDbCommand("select count(*) from data where Users = ?"))
{
con.Open();
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UserName", textBox1.Text);
object objRes = cmd.ExecuteScalar();
if (objRes == null || (int)objRes == 0)
{
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO data (Users,Pass) values(?, ?);";
cmd.Parameters.AddWithValue("#Users", textBox1.Text);
cmd.Parameters.AddWithValue("#Pass", textBox2.Text);
int iRes = cmd.ExecuteNonQuery();
if(iRes > 0)
MessageBox.Show("Registration Success!");
}
else
errorProvider2.SetError(textBox1, "This username has been using by another user.");
}

You almost never use data (in this case, a username) as the primary key for a record in a database. Chance are, your access database is set up the same way.
This means that there is nothing at the DBMS layer that will stop this from occurring, short of making the username the primary key (not recommended).
The solution is to perform a SELECT query to get the count of records with that username, and only allow the insert if the count is 0. You might be able to write a trigger to do this for you, and make the DBMS "reject" the insert, but given your (apparent) level with databases, I wouldn't try that at this point.
To get the count:
SELECT Count(*) FROM Users WHERE userName=#userName
A paramaterized query here is crucial to protect against SQL injection.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Text.RegularExpressions;
namespace Login
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if(text1Box1.Text == "" || textBox2.Text == "")
{
MessageBox.Show("Mandatory fields password or user is empty");
retrun; //I'm not sure if this return is need. Remove it if MessageBox "breaks" the execution of the code below.
}
OleDbCommand cmd = new OleDbCommand(#"Select * from Data where User=#User");
cmd.Parameters.AddWithValue("#User", textBox1.Text);
DataSet dst = SqlManager.GetDataSet(cmd, "Data");
if(dst.Tables[0].Rows > 0)
{
MessageBox.Show("User already exist");
return; //again i'm not sure that this return is needed.
}
Insert("Data", "User", textBox1.Text, "Pass", textBox2.Text);
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You need 1 class make it SqlManager.
public class SqlManager
{
private String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public static GetOleDbConnection(OleDbCommand cmd)
{
if(cmd.Connection == null)
{
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
cmd.Connection = conn;
return conn;
}
return cmd.Connection;
}
public static int ExecuteNonQuery(SqlCommand cmd)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
Here is another method you can put in the form class:
public virtual void Insert(string TableName, params object[] colValues)
{
if (colValues == null || colValues.Length % 2 != 0)
throw new ArgumentException("Invalid column values passed in. Expects pairs (ColumnName, ColumnValue).");
OleDbCommand cmd = new OleDbCommand("INSERT INTO " + TableName + " ( {0} ) VALUES ( {1} )");
string insertCols = string.Empty;
string insertParams = string.Empty;
for (int i = 0; i < colValues.Length; i += 2)
{
string separator = ", ";
if (i == colValues.Length - 2)
separator = "";
string param = "#P" + i;
insertCols += colValues[i] + separator;
insertParams += param + separator;
cmd.Parameters.AddWithValue(param, colValues[i + 1]);
}
cmd.CommandText = string.Format(cmd.CommandText, insertCols, insertParams);
DA.SqlManager.ExecuteNonQuery(cmd);
}
Like other guys tell you use parameters in this case you will avoid sql injection. Read in wikipedia about it. Also I add some structure for your program, it is not perfect but I should write a lot for more. It is possible to have some typos here, because I wrote the code here. How you make the check, you fetch the data from database for the user which you write in textbox1.Text. If the dataSet have rows that means at the moment there is existing user with this name. If you don't know what is data set read System.Data.
You should learn to write data access in other classes !

Try this with your Existing Code :
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "') SELECT '" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "' WHERE NOT EXISTS(SELECT Users,Pass FROM data WHERE Users='" + this.textBox1.Text.ToString() +"');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
else
{
MessageBox.Show("Username is already Present !!!");
}
It returns 0 if the username is already present in data.

Related

Setting up a chart that displays the number of times a dataset record appears in C#

I am trying to create a chart that when, at the push of a button displays a chart that shows the user the number of times a record has appeared in the dataset/table that it is linked to. Please bare in mind that I have little experience with using Charts in Visual Studios/C#.
Currently I am getting this error: Error
This is all the code I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
public formRRAS()
{
InitializeComponent();
}
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Select = "SELECT * FROM tblReject_test";
string DataConnection;
string Department = txtDepartment.Text;
string Start_Date = txtStart.Text;
string End_Date = txtEnd.Text;
string Anatomy = txtAnatomy.Text;
string RFR = cmbRFR.Text;
string Comment = txtComment.Text;
//Select defines what should be loaded on to the dataset.
if (Department != "")
{
Select = Select + " WHERE department_id =" + "'" + Department + "'";
if (Anatomy != "")
{
Select = Select + "AND body_part_examined =" + "'" + Anatomy + "'";
if (Start_Date != "")
{
Select = Select + " AND study_date =" + "'" + Start_Date + "'";
if (End_Date != "")
{
Select = Select + " AND study_date =" + "'" + End_Date + "'";
if (RFR != "")
{
Select = Select + " AND reject_category =" + "'" + RFR + "'";
if(Comment != "")
{
Select = Select + " AND reject_comment =" + "'" + Comment + "'";
}
}
}
}
}
}
else
{
Select = "SELECT * FROM tblReject_test";
}
//DataConnection connects to the database.
string connectiontring= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
}
private void btnLoadChart_Click(object sender, EventArgs e)
{
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT * FROM tblReject_test";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}
}
Your code wouldn't compile as you are assigning a string to DataConnection (instance of OleDbConnection).
The correct usage should be as following.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring));
Also, your code doesn't close Database connection in case of exception.
It would be recommended to use the code as shown below. This is taken from MSDN
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("DataSource: {0} \nDatabase: {1}",
connection.DataSource, connection.Database);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}

C# how to insert data to mysql using C#?

Im very new on C#
I Only create 1 Form that Can insert Data to Mysql Database. My code not have Error, but data cant enter the Database. I m so confused.
this my code
Koneksi.cs
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Drawing;
using System.Windows.Forms;
namespace timbangan
{
public class Koneksi
{
public MySqlConnection konek;
//string konfigKoneksi = "server=localhost; database=timbangan; uid=root; pwd=";
string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public void bukaKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
var temp = konek.State.ToString();
if (temp == "Open")
{
MessageBox.Show(#"Connection working.");
}
else {
MessageBox.Show(#"Please check connection string");
}
}
public void tutupKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Close();
}
}//end of koneksi
}//end namespace
Isidata.cs File
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace timbangan
{
public class Isidata
{
MySqlDataAdapter adapter;
MySqlCommand komand;
Koneksi classKoneksi;
DataTable tabel;
string sql = "";
public DataTable tambahData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
classKoneksi = new Koneksi();
sql = "insert into tb_timbang(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT) values (" + berat_filter + ",'" + qty + "','" + nama_barang + "','" + dari + "','" + shift + "')";
//MessageBox.Show(sql);
tabel = new DataTable();
try
{
classKoneksi.bukaKoneksi();
komand = new MySqlCommand(sql);
adapter = new MySqlDataAdapter(sql, classKoneksi.konek);
adapter.Fill(tabel);
}
catch (Exception)
{
MessageBox.Show("error");
}
return tabel;
}
}//end of issdata
}//end of timbangan
Form1.cs File
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
namespace timbangan
{
public partial class Form1 : Form
{
public DataTable tabel;
public string status = "";
public string berat_filter, qty, nama_barang, dari, shift;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Isidata isi = new Isidata();
tabel = isi.tambahData(tbBerat.Text, tbQty.Text, tbNama.Text, tbDari.Text, tbShift.Text);
MessageBox.Show("Berhasil");
}
}
}
Can Anyone Help me to Fix this? or Advice me to have more short code to Insert data?
Thanks in advance
You could redesign your classes to something like this
namespace timbangan
{
public static class Koneksi
{
public static MySqlConnection konek;
private static string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public static MySqlConnection GetConnection()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
}
}//end of koneksi
public class Isidata
{
public int InsertData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
sql = #"insert into tb_timbang
(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT)
values (#berat_filter,#qty,#nama_barang,#dari,#shift)";
try
{
using(MySqlConnection cnn = Koneksi.GetConnection())
using(MySqlCommand cmd = new MySqlCommand(sql, cnn))
{
cmd.Parameters.Add("#berat_filter", MySqlDbType.VarChar).Value = berat_filter;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = qty;
cmd.Parameters.Add("#name_barang", MySqlDbType.VarChar).Value = nama_barang;
cmd.Parameters.Add("#dari", MySqlDbType.VarChar).Value = dari;
cmd.Parameters.Add("#shift", MySqlDbType.VarChar).Value = shift;
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("error " + ex.Message);
return -1;
}
}
}
}//end of issdata
}//end of timbangan
In this design there are no more global variables around. The same Koneski class could be totally removed and your MySqlConnection could be created on the spot (reading the connectionstring from an external source like your config file). Don't think this is less efficient than keeping a global connection object already created and always open. There is an ADO.NET Connection Pooling infrastructure (link is for Sql Server but it is the same for MySql) that runs very efficiently to handle your connections
The important thing is the Using Statement (that closes and dispose the command and the connection when no more needed freeing valuable resources) and the parameters used to fill the command sent to the server. If you need to use an Adapter for other aspect of your work you could add other methods like this to your Isidata class
As a last note, notice that all parameters are of string type. This could work but it is best to have parameters of the same type of the field type on the database (and of course your variables should be of the correct datatype). This is particularly important with datetime fields that when are treated as strings could give a good headache to let them work correctly) See MySqlDbType enum
Make a class named DBClass.cs and write the below code-
class DBClass
{
MySqlCommand odcmd = new MySqlCommand();
MySqlConnection odcon = new MySqlConnection();
MySqlDataAdapter oda = new MySqlDataAdapter();
public DBClass()
{
}
public void OpenConnection()
{
odcon.ConnectionString = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
if (odcon.State == ConnectionState.Closed)
odcon.Open();
oda.SelectCommand = odcmd;
odcmd.Connection = odcon;
}
public void CloseConnection()
{
if (odcon.State == ConnectionState.Open)
odcon.Close();
}
public DataTable Select(string sql)
{
DataTable dt = new DataTable();
odcmd.CommandText = sql;
oda.Fill(dt);
return dt;
}
public int ModiFy(string sql)
{
odcmd.CommandText = sql;
return odcmd.ExecuteNonQuery();
}
}
On your form, Now you can fire your query like-
DbclassObject.Modify(Your_Insert_Update_Delete_Query);
DataTable dt= DbclassObject.Select(Your_Select_Query);

How to fill a combobox from a MS Access text field then insert combobox selection into another table

I am trying to insert an Access table record with information from a combobox. I am using a winform and C#. I have simplified my project to just include the problem area. I am showing three methods with 4 controls (2 buttons and 2 comboboxes. The first method is connecting to an Access database and then showing a list of the tables and views in the first combobox. this method will also call the last method, SelectName() and fill the second combobox with field contents from a predetermined table from the selected database. The second method (buttonInsert_Click()) is where my problem lies. I would like the method to insert into one of the selected tables from combobox1 the selected item from combobox2 when the insert button is clicked. The only content I can get to insert into the selected table is
System.Data.DataRowView
The C# section of my project is below. Any suggestions are appreciated. Thank You.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace DbApp
{
public partial class Form1 : Form
{
private char ch = '"';
private OleDbConnection dbConn;
private string sql = "";
public Form1()
{
InitializeComponent();
}
private void buttonConnect_Click(object sender, EventArgs e)
{
string connectionString = "";
string stringData = "";
openFileDialog1.Filter = "";
openFileDialog1.ShowDialog();
Text = openFileDialog1.FileName;
stringData = openFileDialog1.FileName;
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + Text + ch;
if (dbConn != null)
dbConn.Close();
dbConn = new OleDbConnection(connectionString);
dbConn.Open();
comboBox1.Items.Clear();
DataTable info = dbConn.GetSchema("Tables");
for (int x = 0; x < info.Rows.Count; ++x)
{
if ((info.Rows[x][3].ToString() == "TABLE") || (info.Rows[x][3].ToString() == "VIEW"))
{
comboBox1.Items.Add((object)info.Rows[x][2].ToString());
}
}
SelectName();
}
private void buttonInsert_Click(object sender, EventArgs e)
{
string name = this.comboBox2.SelectedItem.ToString();
try
{
dbConn = new OleDbConnection();
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + ch + openFileDialog1.FileName + ch;
dbConn.Open();
sql = "INSERT INTO " + this.comboBox1.SelectedItem.ToString() + " (Names)" +
"Values (#name)";
OleDbCommand myCommand = new OleDbCommand(sql, dbConn);
myCommand.Parameters.Add("#name", OleDbType.VarChar).Value = name;
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
catch (Exception err)
{
MessageBox.Show("Error: " + err.Message.ToString());
}
}
private void SelectName()
{
string strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + ch + openFileDialog1.FileName + ch;
try
{
using (dbConn = new OleDbConnection(strCon))
{
dbConn.Open();
sql = "SELECT Name FROM Names";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(sql, dbConn));
DataSet ds = new DataSet();
adapter.Fill(ds, "Names");
comboBox2.Items.Clear();
this.comboBox2.DataSource = ds.Tables["Names"];
this.comboBox2.DisplayMember = "Name";
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString());
}
}
}
}
Try this:
string name = this.comboBox2.Text;

How to get a value from a query and compare it with a string?

Here is the schema of my Society Table:
Society(SocietyName, Email, Password, Status)
So basically I'm creating a login page in which user enters Email and password. If there is an email which matches the one in database then it checks that whether status is equal to president or faculty member or Student Affairs Office. Based on that , it redirects to different pages.
Following is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3 {
public partial class WebForm1 : System.Web.UI.Page {
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String QueryStr;
String name;
protected void Page_Load(object sender, EventArgs e) { }
protected void clicked(object sender, EventArgs e) {
String ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Webappconstring"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(ConnString);
conn.Open();
String QueryStr2 = "";
QueryStr = "";
QueryStr = "Select * from the_society_circle.society WHERE Email= '" + Emailtxt.Text + "' And Psswd=' " + passwordtxt.Text + "'";
cmd = new MySql.Data.MySqlClient.MySqlCommand(QueryStr, conn);
reader = cmd.ExecuteReader();
QueryStr2 = "Select Status from the_society_circle.society where Email = '" + QueryStr + "'";
name = "";
while (reader.HasRows && reader.Read()) {
name = reader["Email"].ToString();
}
if ((QueryStr2== "president" || QueryStr2 == "faculty member") && reader.HasRows ) {
Session["Email"] = name;
Response.BufferOutput = true;
Response.Redirect("WebForm2.aspx", true);
} else {
Emailtxt.Text = "invalid user";
}
conn.Close();
}
}
}
The problem is that if statement is never executed and it always prints invalid user.
PS: Im new to web development :D
You set QueryString2 to this value
QueryStr2 = "Select Status from the_society_circle.society where Email = '" + QueryStr + "'";
It can never be one of the values you check for.
As codemonkey already wrote, your condition will never come true.
You do the following: if ((QueryStr2== "president" || Quer... which evaluates to if (("Select Status from the_society_circle.society where Email = '" + QueryStr + "'"== "president" || Quer.... So you're comparing two different strings, which will never succeed.
I tried to refactor your code and came up with this (not tested, wrote from scratch):
First put your database-related code into a separate class (MySqlAccess) and dispose the database objects (put them into using-blocks which invokes Dispose() on leaving the block).
Don't use the user-inputs in your sql query directly. Remember "all input is evil". So better use parameterized-queries.
The reason your comparison failed was that you didn't execute your second query. Now the code executes just one query and returns the status of the user.
So to sum up:
Have SQL Injection and other malicious actions in mind. For example have a look at this article: http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx
And never store passwords as clear text in your database. That's the next thing you should care about. Edit your database to store the passwords as salted password hashes and just compare the hashes. For a starting point, have look at this article: http://www.codeproject.com/Articles/704865/Salted-Password-Hashing-Doing-it-Right
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
private string _connectionString;
protected void Page_Load(object sender, EventArgs e)
{
_connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Webappconstring"].ToString();
}
protected void Clicked(object sender, EventArgs e)
{
string email = Emailtxt.Text;
string password = passwordtxt.Text;
var mysqlAccess = new MySqlAccess(_connectionString);
string status = mysqlAccess.GetStatus(email, password);
if (status == Constants.Status.PRESIDENT || status == Constants.Status.FACULTY_MEMBER)
{
Session["Email"] = email;
Response.Redirect("WebForm2.aspx", true);
}
else
{
Emailtxt.Text = "invalid user";
}
}
}
internal class MySqlAccess
{
private readonly string _connectionString;
public MySqlAccess(string connectionString)
{
_connectionString = connectionString;
}
public string GetStatus(string email, string password)
{
using (var conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "SELECT Status FROM the_society_circle.society WHERE Email=#Email AND Psswd=#Password;";
using (var cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", password);
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows && reader.Read())
{
return reader["Status"].ToString();
}
}
}
}
return string.Empty;
}
}
internal class Constants
{
internal class Status
{
public const string PRESIDENT = "president";
public const string FACULTY_MEMBER = "faculty member";
}
}
}

NullReferenceException i am familiar with them, but cannot solve on this occasion

im fairly new to ASP.net but i am familiar with Null reference exceptions however i cant solve this one. Im trying to collect data from a webform and pass it to my database through a connection string, this is when the exception occurs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
SqlConnection studConnA = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnection"].ConnectionString);
studConnA.Open();
string checkuser = "select count(*) from StudTable where Name='" + TextBoxName.Text + "'";
SqlCommand studComA = new SqlCommand(checkuser, studConnA);
int temp = Convert.ToInt32(studComA.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already Exists");
}
studConnA.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
protected void Button1_Click(object sender, System.EventArgs e)
{
try
{
SqlConnection studConn = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnectionString"].ConnectionString);
studConn.Open();
string insertQuery = "insert into StudTable (Name,Email,Age,Continent,School,Password) values (#name,#email,#age,#cont,#school,#pass)";
SqlCommand studCom = new SqlCommand(insertQuery, studConn);
studCom.Parameters.AddWithValue("#name", TextBoxName.Text);
studCom.Parameters.AddWithValue("#email", TextBoxEmail.Text);
studCom.Parameters.AddWithValue("#age", TextBoxAge.Text);
studCom.Parameters.AddWithValue("#cont",DropDownCont.SelectedItem.ToString());
studCom.Parameters.AddWithValue("#school", TextBoxSchool.Text);
studCom.Parameters.AddWithValue("#pas", TextBoxPass.Text);
studCom.ExecuteNonQuery();
Response.Redirect("Backend.aspx");
Response.Write("Your Registration is Sucessful");
studConn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" +ex.ToString());
}
}
}
The null reference occurs at line 19
Line 17: if (IsPostBack)
Line 18: {
Line 19: SqlConnection studConnA = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnection"].ConnectionString);
Line 20: studConnA.Open();
Line 21: string checkuser = "select count(*) from StudTable where Name='" + TextBoxName.Text + "'";
I believe the issue is in the syntax of my connection string but im not sure,
Can anyone help me to solve this?
Check your configuration file for the following key:
<connectionStrings>
<add name="StudConnection" connectionString="YOUR DETAILS" />
</connectionStrings>
If it doesn't exist, add the right key and retry.
You can also check the issue with the following code:
if (IsPostBack)
{
// if this line fails, then you don't have the proper connection string
// element in the config file.
Debug.Assert(ConfigurationManager.ConnectionStrings["StudConnection"] != null);
SqlConnection studConnA = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnection"].ConnectionString);
studConnA.Open();
string checkuser = "select count(*) from StudTable where Name='" + TextBoxName.Text + "'";
SqlCommand studComA = new SqlCommand(checkuser, studConnA);
int temp = Convert.ToInt32(studComA.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already Exists");
}
studConnA.Close();
}
It would appear that there is no connection string named StudConnection configured.

Categories

Resources