I am creating an app whose first window is a database configuration window. From this window, a user inputs server details and selects the database they want to use upon which the database connection details and carried over to the login window and the window is opened.
The login and subsequent windows use the database details for their sql connection string.
My question here is this: how can I save these connection details from the configuration window such that the user bypasses this screen if they have already established a previous connection? I have the idea to store these details to a file and set a boolean condition in App.xaml.cs, but I do not know how to go about doing it.
Here is my code:
For the Database Settings Window
DatabaseSettings.xaml.cs
private void btnTest_Click(object sender, RoutedEventArgs e)
{
try
{
connectionString = "Data Source = " + txtServer.Text + "; User Id = " + txtUserID.Text + "; Password = " + txtPassword.Password + "";
conn = new SqlConnection(connectionString);
conn.Open();
string message = "Connection Successful Please Select a Database to Proceed";
string caption = "Success!";
MessageBoxButton buttons = MessageBoxButton.OK;
MessageBoxImage icon = MessageBoxImage.Information;
System.Windows.MessageBox.Show(message, caption, buttons, icon);
txtServer.IsEnabled = false;
txtUserID.IsEnabled = false;
txtPassword.IsEnabled = false;
btnTest.IsEnabled = false;
cmbdatabase.IsEnabled = true;
btnConfigure.IsEnabled = true;
btnConfigure.IsDefault = true;
sql = "EXEC sp_databases";
command = new SqlCommand(sql, conn);
reader = command.ExecuteReader();
cmbdatabase.Items.Clear();
while (reader.Read())
{
cmbdatabase.Items.Add(reader[0].ToString());
}
conn.Close();
}
catch(Exception ex)
{
System.Windows.MessageBox.Show("Error: " + ex);
}
}
static string Encrypt_Password(string value)
{
using (SHA256Managed sha2 = new SHA256Managed())
{
UTF8Encoding uTF8 = new UTF8Encoding();
byte[] data = sha2.ComputeHash(uTF8.GetBytes(value));
return Convert.ToBase64String(data);
}
}
private void btnConfigure_Click(object sender, RoutedEventArgs e)
{
try
{
string selected = cmbdatabase.Text;
txtSelectedDBItem.Text = cmbdatabase.Text;
string EncryptedPassword = Encrypt_Password(txtPassword.Password);
connectionString = "Data Source = " + txtServer.Text + "; Initial Catalog = " + selected + "; User Id = " + txtUserID.Text + "; Password = " + txtPassword.Password + "";
conn = new SqlConnection(connectionString);
sql = "INSERT INTO Proc_Activity_Log ([UserName], [Password], [AccessTime], [MachineSerial]) values(#userId, #password, #accessTime, #machineserial)";
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#userID", txtUserID.Text);
cmd.Parameters.AddWithValue("#password", EncryptedPassword);
cmd.Parameters.AddWithValue("#accessTime", dateTime.Text);
cmd.Parameters.AddWithValue("#machineserial", txtMachineSerialNo.Text);
cmd.ExecuteNonQuery();
}
UserInterface.frmLogin loginScreen = new UserInterface.frmLogin(txtUserID.Text, txtPassword.Password, txtServer.Text, txtSelectedDBItem.Text);
spashScreen.Show();
this.Close();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error Here:" + ex.Message);
}
}
For the login screen
frmLogin.xaml.cs
public frmLogin(string uname, string pwd, string server, string db)
{
InitializeComponent();
txtServerUser.Text = uname;
txtServerPwd.Password = pwd;
txtServer.Text = server;
txtSelectedDBItem.Text = db;
}
private void btnOk_Click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=" + txtServer.Text + "; Initial Catalog=" + txtSelectedDBItem.Text + "; Integrated Security=True;");
try
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
String query = "SELECT COUNT(1) FROM dbo.users WHERE name=#Username and password=#Password";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("#Username", txtLogin.Text);
sqlCmd.Parameters.AddWithValue("#Password", txtPwd.Password);
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
frmMDI yourDesktop = new frmMDI(txtLogin.Text, txtServerUser.Text, txtServerPwd.Password, txtServer.Text, txtSelectedDBItem.Text);
yourDesktop.Show();
this.Close();
}
else
{
txtLogin.Text = "admin";
txtPwd.Password = "admin";
txtLogin.Focus();
}
}
catch (Exception ex)
{
string message = "The Following Error Occurred: " + ex.Message;
string caption = "Invalid Action";
MessageBoxButton buttons = MessageBoxButton.OK;
MessageBoxImage icon = MessageBoxImage.Error;
System.Windows.MessageBox.Show(message, caption, buttons, icon);
}
finally
{
sqlCon.Close();
}
}
From the screenshots I have included below one can infer which buttons represent the click events in the code above
Database Settings Window - Testing Connection
Database Settings Window - Testing Connection
Database Settings Window - Configuring Database
Database Settings Window - Configuring Database
And finally the login window
login window
Related
I am trying to create a login form that will authenticate the user's credentials before letting them proceed to another form. I am getting an error message where it says "invalid attempt to read when reader is closed"
Error Message
Code:
private void btn_Login_Click(object sender, EventArgs e)
{
sqlConnection.ConnectionString = "server=" + server + ";" + "username=" + username + ";" + "password=" + password + ";" + "database=" + database;
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "Select tunapunaboysrc.addregister.Username, tunapunaboysrc.addregister.Password "
+ "from tunapunaboysrc.addregister";
sqlDataReader = sqlCommand.ExecuteReader();
sqlData.Load(sqlDataReader);
dg_Login.DataSource = sqlData;
if (sqlDataReader.Read() == true)
{
new frmDashboard().Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid Username or Password, Please Try Again", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtbx_username.Text = "";
txtbx_password.Text = "";
txtbx_username.Focus();
}
sqlDataReader.Close();
sqlConnection.Close();
new frmDashboard().Show();
this.Hide();
}
I also use this at the beginning also, incase if its needed.
public partial class frmLogin : Form
{
MySqlConnection sqlConnection = new MySqlConnection();
MySqlCommand sqlCommand = new MySqlCommand();
DataTable sqlData = new DataTable();
MySqlDataAdapter SqlAdapter = new MySqlDataAdapter();
DataSet sqlSet = new DataSet();
MySqlDataReader sqlDataReader;
String server = "localhost";
String username = "root";
String password = "cybers";
String database = "tunapunaboysrc";
Can someone help me figure out why my reader is closing, and how i can solve it?
i tried pasting the authentication code
if (sqlDataReader.Read() == true)
{
new frmDashboard().Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid Username or Password, Please Try Again", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtbx_username.Text = "";
txtbx_password.Text = "";
txtbx_username.Focus();
}
I have two Web forms. One is LoginForm and Second is StudentStatus Form by Login with id and password in LoginForm i want to show Student Status record from StatusTable in StudentStatus Form...
Is there any way to fetch data from squal server from one form to another?
This is my LoginForm Code...
protected void LoginBtn_Click(object sender, EventArgs e)
{
string cs = "Data Source = SAAD_EBAD\\SQLEXPRESS; Database = Custom Test; Trusted_Connection = Yes";
SqlConnection con = new SqlConnection(cs);
con.Open();
string _sqlQuery = "Select count(*) from Student_Status where User_Name='" + Usertxt.Text + "'";
SqlCommand cmd = new SqlCommand(_sqlQuery, con);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
con.Close();
if (temp == 1)
{
con.Open();
string _checkPasswordQuery = "Select Student_Password From Student_Status Where User_Name='" + Usertxt.Text + "'";
SqlCommand command = new SqlCommand(_checkPasswordQuery, con);
string _password = command.ExecuteScalar().ToString().Replace(" ", "");
**if (_password == PasswordTxt.Text)
{
Session["New"] = Usertxt.Text;
Response.Redirect("~/Student Status.aspx");
if (_password.Equals(PasswordTxt.Text))
{
Student_Status.CreateHtmlTextWriterFromType(,"select Student_Degree_Status from Student_Status" );
}**
}
else
{
string str = "Sorry,Password is not correct";
ClientScript.RegisterStartupScript(this.GetType(), "My alert", "alert('" + str + "');", true);
}
}
else
{
string str2 = "User Name is not correct";
ClientScript.RegisterStartupScript(this.GetType(), "My alert", "alert('" + str2 + "');", true);
}
}
The code in bold (quoted) form i am having concern and issue it is not working. ihust want to show data from sql server from one form to another by login
Im very new to C#, im working on a login system. The program can verify the user information but I dont get how your suppose to log the user in. Beacuse now you get a success message and thats it.
And how do you redirect the user to the rest of the application. This is a native app and all I could find was information about how to redirect in asp.net instad of c#.net.
private void button1_Click(object sender, EventArgs e)
{
string user = textBox1.Text;
string pwd = textBox2.Text;
MySqlConnection conn = new MySqlConnection("server = localhost; user id = root; database = bot");
MySqlDataAdapter sda = new MySqlDataAdapter("select count(*) from license where user = '" + textBox1.Text + "' and pwd = '" + textBox2.Text + "'", conn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
MessageBox.Show("Successful login!", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Info is not valid", "alter", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You just need to define an object of the class and the use Show(); after you use this.Hide(); for ASP.NET use Response.Redirect("Dashboard.aspx")
For increasing the security of your login form you should read this to preventing SQL injection attacks: https://www.codeproject.com/Articles/9378/%2FArticles%2F9378%2FSQL-Injection-Attacks-and-Some-Tips-on-How-to-Prev
https://www.mikesdotnetting.com/article/113/preventing-sql-injection-in-asp-net
For the session setting
How to set security on Login Page in asp.net
For encryption :
C# encrypted Login
private void button1_Click(object sender, EventArgs e)
{
string user = textBox1.Text;
string pwd = textBox2.Text;
MySqlConnection conn = new MySqlConnection("server = localhost; user id = root; database = bot");
string query = "Select * from license Where user = '" + textBox1.Text.Trim() + "' and pwd = '" + textBox2.Text.Trim() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, conn );
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{ //change the name of the form depend on the form that you need to show.
frmMain objFrmMain = new frmMain();
this.Hide();
objFrmMain.Show();
}
else
{
MessageBox.Show("Check your username and password");
}
}
For ASP.NET
protected void btnLogin_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection("server = localhost; user id = root; database = bot");
{
sqlCon.Open();
string query = "Select * from license Where user = '" + textBox1.Text.Trim() + "' and pwd = '" + textBox2.Text.Trim() + "'";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#user",textBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#pwd", textBox2.Text.Trim());
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
Session["user"] = textBox1.Text.Trim();
Response.Redirect("Dashboard.aspx");
}
else { lblErrorMessage.Visible = true; }
}
}
Download the code from here:https://drive.google.com/drive/folders/17KvHSTJvvD5jmcufr35-V8TV67pHL7D8
I have a database to manage a school (students and classes).
I have a class with the code to connect to the DataBase and then I call the functions in the main program.
When I try to interact with the DataBase, it warns me that it could not connect to the DataBase or it exceeded the connection time.
I tried to add an ssslmode but it didn't work. I also tried to add a port but it didn't work.
Code for the class:
public class ligacao
{
public MySqlConnection connection;
string server;
public string data_base;
string user_id;
string password;
public void inicializa()
{
server = "localhost";
data_base = "escola";
user_id = "root";
password = "usbw";
string connection_string;
string sslmode = "none";
connection_string = "SERVER=" + server + ";" + "DATABASE=" + data_base + ";" + "UID=" + user_id + "PASSWORD=" + password + ";" + "SslMode=" + sslmode + ";";
connection = new MySqlConnection(connection_string);
}
public bool open_connection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0: MessageBox.Show("Couldn't connect t DataBase."); break; // couldn't connect to database
case 1042: MessageBox.Show("Exceded the connection time"); break; // exceeded the connection time
case 1045: MessageBox.Show("Username/password are incorrect"); break;
}
return false;
}
}
public bool close_connection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
Code for the Main Program:
public partial class consultas : Form
{
ligacao x = new ligacao();
public consultas()
{
InitializeComponent();
x.inicializa();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void consultas_Load(object sender, EventArgs e)
{
//define query
string query = "SELECT designacao FROM disciplinas";
//open connection
if (x.open_connection())
{
//create the comand and associates the query with the connection through the connector
MySqlCommand cmd = new MySqlCommand(query, x.connection);
//create datareader and execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//show data in combobox1
if (dataReader.Read())
{
comboBox1.Items.Add(dataReader["designacao"]);
}
//close dataReader
dataReader.Close();
//close connection
x.close_connection();
}
//define query
string queryBI = "SELECT bi FROM alunos";
//open connection
if (x.open_connection())
{
//create the commando and associate the query with the connection through the constructor
MySqlCommand cmd = new MySqlCommand(queryBI, x.connection);
//create datareader and execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//show data in combobox1
if (dataReader.Read())
{
comboBox1.Items.Add(dataReader["bi"]);
}
//close dataReader
dataReader.Close();
//close connection
x.close_connection();
}
}
}
I think there is something wrong with your connection string. Try using the MySqlConnectionStringBuilder:
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
builder.Host = "localhost";
builder.UserId = "root";
builder.Database = "escola";
builder.Password = "usbw";
connection = new MySqlConnection(builder.ConnectionString);
Try This :
connection_string = #"Data Source = " + server + "; Initial Catalog = " + data_base + "; Integrated Security=True;uid=myUser;password=myPass;";
I am trying to make a windows Form Application with a login screen,Form3 Will open Form1 if the username and password are correct.
The code is linked to a database
The code is as follows:
private void button1_Click(object sender, EventArgs e)
{
string u_id = textBox1.Text;
string u_pwd = textBox2.Text;
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXXX.ac.uk;Initial Catalog=mmt12-186;User ID=XXXXXX;Password=XXXXXX");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = ("SELECT * FROM UsersData WHERE User = '" + textBox1.Text + "'");
cmd.Parameters.AddWithValue("un", u_id);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() == false)
{
label3.Text = "Invalid Username or Password !";
return;
}
string realpwd = reader.GetString(0);
if (u_pwd == realpwd)
{
Form1 formload = new Form1();
formload.Show();
}
}
Every time I run this code, I get an exception on with the line:
string realpwd = reader.GetString(0);
The exception is:
Invalid attempt to read when no data is present.
The UsersData table has 3 columns, Id, User, Password
Thanks goes to "Alfred Sanz" who answered the question, the problem now is that no error is present but no data is shown, as if the button1_click has no method, the current code is:
private void button1_Click(object sender, EventArgs e)
{
string u_id = textBox1.Text;
string u_pwd = textBox2.Text;
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XX.XXX.ac.uk;Initial Catalog=XXXXXXX ;User ID=XXXX;Password=XXXXX");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = ("SELECT * FROM UsersData WHERE User = #un");
cmd.Parameters.AddWithValue("#un", u_id);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
if (reader["Password"].ToString() == u_pwd)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}
you already set the value of USER as '" + textBox1.Text + "'" but you are also setting a value cmd.Parameters.AddWithValue("un", u_id); which really does not exist, change your code into
cmd.CommandText = "SELECT * FROM UsersData WHERE User = #un";
cmd.Parameters.AddWithValue("#un", u_id);
and also you can change the reader part to:
while (reader.Read())
{
if (reader["Password"].ToString() == u_pwd.Text
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}