Display a logged in users info - c#

I have a program where the user has to login, so they have a id and password. The database with the user login details are stored in a local .mdf file.
I would like to set it up so that whilst the user is logged in, the rest of the program shows their details in the top right corner, so for example their name and their id.
I unfortunately have no idea how to do this and all I have seen whilst I browsed around is people using the actual System login, which is not what I want.
Code for login form:
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.SqlClient;
namespace InventoryManager
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void frmLogin_Load(object sender, EventArgs e)
{
this.AcceptButton = btnSubmit;
}
string cs = #"Data Source= (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Users.mdf;Integrated Security = True;";
private void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUserID.Text == "" || txtPassword.Text == "")
{
MessageBox.Show("Please enter a User ID and Password");
return;
}
try
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_Login WHERE UserID = #userid AND Password = #password", con);
cmd.Parameters.AddWithValue("#userid", txtUserID.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Text);
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
con.Close();
int count = ds.Tables[0].Rows.Count;
if (count == 1)
{
MessageBox.Show("Login Successful!");
this.Hide();
frmOverview fo = new frmOverview();
fo.Show();
}
else
{
MessageBox.Show("Login Failed");
txtPassword.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

You can make some static class like this one
public static class LoggedUser
{
public static string Name { get; set; }
public static string Username { get; set; }
}
after successful login, populate that class with data (in example):
if (count == 1)
{
MessageBox.Show("Login Successful!");
LoggedUser.Name = ds.Tables[0].Rows[1].ToString();
LoggedUser.Username = ds.Tables[0].Rows[2].ToString();
this.Hide();
frmOverview fo = new frmOverview();
fo.Show();
}
later, you can use data stored in LoggedUser class on every form in your project...

Related

Explanation on subroutines in C#

I have started to code in C# winforms . One problem I'm finding is learning about subroutines. In visual basic it was really easy but I'm not sure how it works in C# with public and static and void. If when a user presses a button I want to pull up a subroutine from a class would I have the subroutine as static void or public? Also would you use public or static for variables in a class that would be used throughout multiple forms?
An example is this:
private void button1_Click(object sender, EventArgs e)
{
using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\RAV21001310\\OneDrive\\Database1.accdb;"))
{
connection.Open();
using (OleDbCommand command = new OleDbCommand("SELECT * FROM tblUser WHERE Username=#Username AND Password=#Password", connection))
{
command.Parameters.AddWithValue("#Username", username.Text);
command.Parameters.AddWithValue("#Password", password.Text);
using (OleDbDataReader reader = command.ExecuteReader())
{
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username and password is correct");
}
if (count > 1)
{
MessageBox.Show("Duplicate username and password");
}
if (count == 0)
{
MessageBox.Show("Username or password incorrect");
}
}
}
connection.Close();
}
}
}
public class User
{
public string Username;
public string Password;
public string FirstName;
public string LastName;
public string Gender;
public int Age;
public int TotalPoints;
}
The first block of code is a login form. If I wanted to call it UserLogin() and put it in the user class would I use static or public for it or would I just rename the private void for button click and put that in the user class instead.

Unable to access functions from another class (C# Windows Form, SQL Server Management Studio)

I'm learning database connectivity using C# Windows Form Application in Visual Studio and SQL Server Management Studio.
The problem I'm having is I'm unable to access the AddParams() and sqlQueryCmd() functions from the SQLConn.cs Class.
I've tried changing the access modifiers from private to public but it didn't work. Can anyone guide me here? I don't know what I'm doing wrong.
SQLConn.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Microsoft.Data.SqlClient;
namespace dbConnectivityTest1
{
public class SQLConn
{
public static void Main1(string[] args)
{
using (SqlConnection connString = new SqlConnection("Server=ServerName;Database=DatabaseName;User Id=UserID;\r\nPassword=Password;"))
{
List<SqlParameter> paramList = new List<SqlParameter>();
string AddParams(string tableName, object insVal)
{
SqlParameter sqlparams = new SqlParameter(tableName, insVal);
paramList.Add(sqlparams);
}
SqlCommand sqlCmd = new SqlCommand();
string sqlQueryCmd(string sqlQuery)
{
int recordCount = 0;
string excptnShow = "";
try
{
connString.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, connString);
paramList.ForEach(p => { sqlCmd.Parameters.Add(p); });
paramList.Clear();
DataTable sqlDT = new DataTable();
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
recordCount = sqlDA.Fill(sqlDT);
}
catch(Exception ex)
{
excptnShow = "Error: \r\n" + ex.Message;
}
finally
{
if (connString.State == ConnectionState.Open)
{
connString.Close();
}
}
}
}
}
}
}
Form1.cs
namespace dbConnectivityTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SQLConn sqlDB = new SQLConn();
private void enterNametextBox_Click(object sender, EventArgs e)
{
enterNametextBox.Clear();
}
private void submitButton_Click(object sender, EventArgs e)
{
while(fullNameTextBox.Text.Length <= 0)
{
MessageBox.Show("Please enter your Full Name!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
while(contactTextBox.Text.Length <= 0)
{
MessageBox.Show("Please enter your Contact Number!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
while(ageTextBox.Text.Length <= 0)
{
MessageBox.Show("Please enter your Age!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
while(emailTextBox.Text.Length <= 0)
{
MessageBox.Show("Please enter your E-mail!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
System.Text.RegularExpressions.Regex emailRegex = new System.Text.RegularExpressions.Regex(#"^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+$");
while(!emailRegex.IsMatch(emailTextBox.Text))
{
MessageBox.Show("Please enter a valid E-mail!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
InsVal();
}
public void InsVal()
{
**I am trying to call the SQLConn.cs Functions here**
}
}
}
Movint addParam method/function would not solve the problem since the SqlParam variable is not available in sqlConn class.
the better approach for your goal is to to this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace dbConnectivityTest1
{
public class SQLConn
{
private readonly string _connectionString;
private List<SqlParameter> _paramList;
public SQLConn()
{
_connectionString="Server=ServerName;Database=DatabaseName;User Id=UserID;\r\nPassword=Password;";
_paramList = new List<SqlParameter>();
}
public void AddParams(string tableName, object insVal)
{
SqlParameter sqlparams = new SqlParameter(tableName, insVal);
_paramList.Add(sqlparams);
}
public void sqlQueryCmd(string sqlQuery)
{
using (var sqlConn = new SqlConnection(_connectionString))
{
int recordCount = 0;
string excptnShow = "";
try
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
_paramList.ForEach(p => { sqlCmd.Parameters.Add(p); });
_paramList.Clear();
DataTable sqlDT = new DataTable();
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
recordCount = sqlDA.Fill(sqlDT);
}
catch (Exception ex)
{
excptnShow = "Error: \r\n" + ex.Message;
}
finally
{
if (sqlConn.State == ConnectionState.Open)
{
sqlConn.Close();
}
}
}
}
}
}
in this scenario there is no need for Main method since every application can have only one Main method and winForms by default already have one Main method.
secondly, the SQLConn class can have private field of type List,
and a public method called AddParam which its responsibility is to add new params to it.
Lastly, a public SqlQueryCmd method is added to do the rest of the job.
you can now use this class to execute your query like this:
private void button1_Click(object sender, EventArgs e)
{
var sqlConn = new SQLConn();
sqlConn.AddParams("tableName","your Object");
sqlConn.AddParams("tableName","your Object");
sqlConn.AddParams("tableName","your Object");
sqlConn.sqlQueryCmd("Query");
}

System.DllNotFoundException: SQLite.Interop.dll while reading a data from Sql server in Xamarin.Forms

I would like to connect to my local db on Sql Server using System.Data.SQLite in Xamarin.Forms. I ve written a code to read data but all the time I got exception: System.DllNotFoundException: SQLite.Interop.dll. I attach code from MainPage. (User is a model class contains auto-properties).
Target platform is set to Any CPU but change it to x86 or x64 doesnt work.
using SimpleDb.Models;
using System;
using System.Collections.ObjectModel;
using System.Data.SQLite;
using Xamarin.Forms;
namespace SimpleDb
{
public partial class MainPage : ContentPage
{
ObservableCollection<User> usersCollection = new ObservableCollection<User>();
private string connString;
public MainPage()
{
InitializeComponent();
connString = #"Data Source=TOM-PC\SQLEXPRESS;Initial Catalog=TracksDatabase;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;
MultiSubnetFailover=False";
usersView.ItemsSource = usersCollection;
}
private void Button_OnClicked(object sender, EventArgs e)
{
using (SQLiteConnection conn = new SQLiteConnection(connString))
{
conn.Open();
string select = "SELECT Username,Password FROM Users";
using (SQLiteCommand cmd = new SQLiteCommand(select,conn))
{
using(SQLiteDataReader rd = cmd.ExecuteReader())
{
while (rd.Read())
{
usersCollection.Add(new User()
{
Username = rd.GetString(0),
Password = rd.GetString(1)
});
}
}
}
}
}
}
}

System.Data.OracleClient.OracleConnection does not contain a definition

I got this error CS1061: 'System.Data.OracleClient.OracleConnection' does not contain a definition for 'searchDBSet' and no extension method 'searchDBSet' accepting a first argument of type 'System.Data.OracleClient.OracleConnection' could be found (are you missing a using directive or an assembly reference?). I'm sure I have the reference which System.Data;and I think I have the issue with the inheritance because my code is not recognized.Can anyone please help solve this issue.Thank you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Data.OracleClient;
public partial class users_Login : System.Web.UI.Page
{
OracleConnection oc = new OracleConnection("Data Source=**;Persist Security Info=True;User ID=****;Password=****;Unicode=false");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
int flag = 0;
string user_name = loginUserName.Text;
string password = loginPassword.Text;
string qry = "select user_name,password from users where user_name='" + user_name + "' and password='" + password + "'";
DataSet set = oc.searchDBSet(qry);
foreach (DataRow dr in set.Tables[0].Rows)
{
flag = 1;
}
if (flag == 1)
{
FormsAuthentication.RedirectFromLoginPage(user_name, true);
}
else
{
lblMessage.Visible = true;
}
}
}
my class1 code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.OracleClient;
public class Oracleconection
{
string connectionString;
private System.Data.OracleClient.OracleConnection connection;
private System.Data.OracleClient.OracleDataAdapter adapter;
private System.Data.OracleClient.OracleCommand command;
public Oracleconection(string host, string dbname, string username, String password)
{
try
{
//this.connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST="+host+")(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME="+dbname+")));User Id="+username+";Password="+password+";";
this.connectionString = "Data Source=****;Persist Security Info=True;User ID=****;Password=****;Unicode=false";
this.connection = new System.Data.OracleClient.OracleConnection(this.connectionString);
this.connection.Open();
this.command = connection.CreateCommand();
Console.WriteLine("Connected");
}
catch (Exception e)
{
Console.WriteLine("Error while connecting:" + e.Message);
}
}
public DataTable searchDB(string query)
{
DataTable table = new DataTable();
try
{
this.command.CommandText = query;
this.adapter = new System.Data.OracleClient.OracleDataAdapter(command);
this.adapter.Fill(table);
}
catch (Exception e)
{
Console.Write("Error:" + e);
}
return table;
}
public DataSet searchDBSet(string query)
{
DataSet ds = new DataSet();
try
{
this.command.CommandText = query;
this.adapter = new System.Data.OracleClient.OracleDataAdapter(command);
this.adapter.Fill(ds);
}
catch (Exception e)
{
Console.Write("Error:" + e);
}
return ds;
}
public int updateDB(string query)
{
try
{
this.command.CommandText = query;
return this.command.ExecuteNonQuery();
}
catch (Exception e)
{
Console.Write("Error:" + e);
return -1;
}
}
public void close()
{
connection.Close();
}
}
The class name is wrong.
You are doing this:
OracleConnection oc = new OracleConnection(...);
Change to your class:
Oracleconnection oc = new Oracleconnection(...);

Disable certain buttons depending on which user has logged in

In login form, When I login as Jack which exist in the DOCTOR table, it will go to page_two. I want to disable nurse button 1, and nurse button 2 since Jack is not a nurse but a doctor. Then for the opposite, if I login as Mary, which exist in the NURSE table, it will go to page_two. I want to disable doctor button 1, and doctor button 2 since Mary is not a doctor but a nurse.
The button names for Page_two is btnDoctor1, btnDoctor2, btnNurse1 and btnNurse2
//login Form codes
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.SqlClient;
using System.Configuration;
namespace GRP_02_03_SACP
{
public partial class page_one : Form
{
public page_one()
{
InitializeComponent();
}
private void page_one_Load(object sender, EventArgs e)
{
}
private void btnLogin_Click(object sender, EventArgs e)
{
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandtext = "SELECT dUsername, dPassword from DOCTOR";
// Add a WHERE Clause to SQL statement
strCommandtext += " WHERE dUsername=#dname AND dPassword=#dpwd;";
strCommandtext += "SELECT nUsername, nPassword from NURSE WHERE nUsername=#nname AND nPassword=#npwd;";
SqlCommand cmd = new SqlCommand(strCommandtext, myConnect);
cmd.Parameters.AddWithValue("#dname", textUsername.Text);
cmd.Parameters.AddWithValue("#dpwd", txtPassword.Text);
cmd.Parameters.AddWithValue("#nname", textUsername.Text);
cmd.Parameters.AddWithValue("#npwd", txtPassword.Text);
try
{
// STEP 3: open connection and retrieve data by calling ExecuteReader
myConnect.Open();
// STEP 4: Access Data
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) //For Doctor
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
page_two form = new page_two();
form.Show();
return;
}
}
reader.NextResult();
while (reader.Read()) //For Nurse
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
page_two form = new page_two();
form.Show();
return;
}
}
//STEP 5: close connection
reader.Close();
MessageBox.Show("Invalid username or password");
}
catch (SqlException ex)
{
}
finally
{
//STEP 5: close connection
myConnect.Close();
}
}
}
}
I suggest you to create some Person class to hold person data:
public class Person
{
public string Name { get; set; }
public JobPosition Position { get; set; }
// etc
}
Where Position is a enum for job positions available for your persons:
public enum JobPosition
{
Doctor,
Nurse
}
Next step will be separating data access logic from presentation code by moving database queries to some repository class:
public class PersonRepository
{
public Person GetPerson(string userName, string password)
{
// execute query and create Person instance
}
}
Also I'd create separate login form which should be shown before your main form starts. It should use PersonRepository to get Person instance which should be passed to MainForm constructor:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LoginForm loginForm = new LoginForm();
if (loginForm.ShowDialog() != DialogResult.OK)
return;
Application.Run(new MainForm(loginForm.Person));
On main form use position of logged in person to enable or disable controls:
public partial class MainForm : Form
{
private Person _person;
public MainForm(Person person)
{
InitializeComponent();
_person = person;
}
private void MainForm_Load(object sender, EventArgs e)
{
fooButton.Enabled = (_person.Position == JobPosition.Doctor);
// etc
}
}

Categories