Add simple quote into an if statement - c#

I would like to compare UserName and Pass entered by an user with me Local Database.
When I Tried to request on my database, I saw I had to put simple quotes into my request, such as
SELECT * FROM Administrator
WHERE UserName = 'FSelva';
The problem is, when I check the database, I do it like that:
if((username == admin.UserName) && (password == admin.Pass))
{
this.Close();
MainPage retourpageprincipale = new MainPage();
retourpageprincipale.Show();
}
else
{
Admin.**** is the database ones and username & password are variables which catch what the user entered.
When I'm doing step by step, admin.UserName is Null, such as admin.Pass.
I think adding simple quotes like:
if((username == "'" && admin.UserName && "'") && (password == "'" && admin.Pass && "'"))
could fix my problem. But I can't do like this.
Is anybody knows what's the syntax please?
edit:
This is the entire code:
namespace WpfApplication3
{
public partial class Window1 : Window
{
private Database1Entities1 conn = new Database1Entities1();
public Window1()
{
InitializeComponent();
}
private void ConnectionClick(object sender, RoutedEventArgs e)
{
var username = UserNameBox.Text;
var password = PasswordBox.Text;
con.Database.Connection.Open();
Administrator admin = new Administrator();
if((username == admin.UserName) && (password == admin.Pass))
{
this.Close();
MainPage retourpageprincipale = new MainPage();
retourpageprincipale.Show();
}
else
{
MessageBox.Show("Combo Admin/Password non valide!
}
Where Administrator is my admin table:
public partial class Administrator
{
public int Id { get; set; }
public string UserName { get; set; }
public string Pass { get; set; }
public bool IsSuperAdmin { get; set; }
}
When I Step by Step this code, at line:
if((username == admin.UserName) && (password == admin.Pass))
username value is RSans (what I wrote into the IHM)
password valus is 1234abcd (What I wrote into the IHM)
admin.UserName valus is Null
admin.Pass is Null.
Moreover,
admin value is WpfApplication3.Administrator
conn value is WpfApplication3.Database1Entities1
If you need some others informations, i'll edit my post again.
Edit2:
This is my Database1Entities1 full code:
namespace WpfApplication3
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class Database1Entities1 : DbContext
{
public Database1Entities1()
: base("name=Database1Entities1")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DBSet<Administrator> Administrator { get; set; }
}

The problem in your code lies by reading the Information from the database. If both admin.* properties are null, it means that they are either null in the database or you don't set them properly.
Furtermore, you do not need simple quotes. They are used in SQL to show that the cell is of type string. Once you read the information to an object in C#, you will see that the quotes are gone. It is easiest to debug your code and step from line to line to see what is wrong.
Update
Since you are using Entity Framework, here is how you can retrieve information from the Database:
Your Database1Entities1 is the so called DbContext. You can use it to query the database. It should have a property Administrators. If it doesn't, you can add the following part to the Database1Entities1 class:
public DbSet<Administrator> Administrators { get; set; }
You can then use the your conn object to query the database, e.g.
var admin = conn.Administrators.SingleOrDefault(a => a.UserName == "FSelva");
Since you are already querying the database, you could add the whole check (including the password) in one step:
var admin = conn.Administrators.SingleOrDefault(a => a.UserName == "FSelva" && a.Password == "...");
// if there is no match, the admin object will be NULL here
Update 2
You do not need to open the connection manually. Entity Framework will do that for you. So you can delete the line:
con.Database.Connection.Open();

Related

Null value on SQL statement include the result of a SELECT query on the row (show the SQL query you sent and the result from that query)

I am working on a project , in order to use the Identity features in the last steps, I had to make some changes on database and add Identity to it. Also, inherit DatabaContext from IdentityDbContext. In my previous method I used to make a new object of DatabaseContext and work on it :
private DatabaseContext db = new DatabaseContext();
But with the new changes, when I pass the model to View or apply a conditional input, it returns a null value, for example, the following code:
public JsonResult CheckUserNameAvailability(Int32 UserCode)
{
var SearchData = db.Persons.Where(p => p.Pcode == UserCode).FirstOrDefault();////this line
if (SearchData != null)
{
TempData["code"] = 0;
return Json(1);
}
else
{
TempData["code"] = UserCode;
return Json(0);
}
}
On the line
var SearchData = db.Persons.Where (p => p.Pcode == UserCode) .FirstOrDefault();
return Error
System.Data.SqlTypes.SqlNullValueException: 'Data is Null. This method or property cannot be called on Null values.
even though the database is not empty and this code used to work properly. If someone could provide some assistance, it would be terrific!
and This is Model:
namespace LeaveSheet.Models
{
public class Person
{
[Key]
public Int32 Id { get; set; }
public Int32 Pcode { get; set; }
public string Name { get; set; }
public string Family { get; set; }
}
}
codes in startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DatabaseContext>(p => p.UseSqlServer(#"Data Source =. ; Initial Catalog = LeaveSheet; Integrated Security=True;MultipleActiveResultSets=true "));
services.AddControllersWithViews();
services.AddIdentity<User, Role>().AddEntityFrameworkStores<DatabaseContext>().AddDefaultTokenProviders();
}
Check whether the ID column in person table has always a value.
Even though it is the key column in model, check whether it is same in DB as well.

How do I access variables from an object list?

I created a class User, which contain simple variables as shown below:
public class User
{
public string username; //Unique usernames
public string password;
}
I then instantiate a list of an object in another class:
List<User> user = new List<User>();
user.Add(new User {username = "admin", password = "123"});
How is it possible for me to retrieve the password's value by searching for the username using a foreach loop? I am probably just confused but this is what I came up with:
foreach(var item in user)
{
if(item.Equals(username_input))
{
//I try to store the password into a string pass_check
pass_check = item.password;
}
}
if (user_input.Equals(pass_check))
{
Console.WriteLine("Login successful");
}
Sorry if this seems like a dense question to anyone out there, still a beginner trying to learn!
You're pretty close..
if(item.username.Equals(username_input))
You need to check the property of the item in this case which is username.
You could even shorten it to:
foreach(var item in user)
{
if(item.username.Equals(username_input)
&& user_input.Equals(item.password))
{
Console.WriteLine("Login successful");
break; // no need to check more.. or is there?
}
}
You can get really fancy using Linq:
if (user.Any(i => i.username.Equals(username_input)
&& user_input.Equals(i.password))
{
Console.WriteLine("Login successful");
}
As juharr noted in the commend, best practices for exposing values from class/objects is to use Properties not Fields..
public class User
{
// not best practices
public string username;
// best practices
public string password { get; set; }
}
Even fancier:
using System.Linq;
public static class Extensions
{
// Extension method that works on List<User> to validate user && PW
// - returns true if user exists and pw is ok, else false
public static bool CheckUserPassword(this List<User> users, string user_name, string pw)
{
// add null checks for users, user_name and pw if you are paranoid of know your customers ;o)
return users.Any(u => u.username == user_name && u.password == pw);
}
}
public class User
{
public string password;
public string username; //Unique usernames
}
internal class Program
{
private static List<User> users = new List<User> { new User { username = "admin", password = "123" } };
static void Main(string[] args)
{
// use extension method like this:
var isValid = users.CheckUserPassword("Hello","Jeha");
Console.WriteLine($"user 'admin' with pw '8888' => {users.CheckUserPassword("admin", "8888")}");
Console.WriteLine($"user 'admin' with pw '123' => {users.CheckUserPassword("admin", "123")}");
Console.ReadLine();
}
}
Extension Methods can be executed on the this-part - in this case only on List<User>s. The Extensionmethod uses Linq to find if Any (at least 1) user of this name and pw exists.

disabling a button using database entities users C#

I am new to C# and I am working on a project for my studies and I have multiple logins an Administrator and Teacher. This project has multiple winforms the 2 I am needing help with is my Login and the Main form after the user logs in.
I have already created the logins and they work but I need to disable a button called btnMarks int he Main form the Administrator cannot have access to this button.
I have tried if statements but I can't seem to make it work. I am using radio buttons for logins as well as the Administrator and Teachers logins have their own tables in the database. I can only use Entities not SQLconnections it is part of the project for my studies.
Please help
Below is my user login form code.
private void btnLogin_Click(object sender, EventArgs e)
{
//A check to make sure both fields have an entry
if(txtUsername.Text == "" || txtPassword.Text == "")
{
MessageBox.Show("Please provide a Username and Password!");
return;
}
//This is to call the boolean radiobuttons are checked
radioButtons();
//Teachers login
if (rbTeachers.Checked)
{
int Username = Convert.ToInt32(txtUsername.Text);
SchoolDBEntities db = new SchoolDBEntities();
var tid = from t in db.Teachers
where t.TID == Username
&& t.Password == txtPassword.Text
select t;
if (tid.Any())
{
MessageBox.Show("You are now logged in as a Teacher!");
this.Hide();
Main tss = new Main();
tss.Show();
}
else
{
MessageBox.Show("Incorrect Username or Password!");
}
}
//Administrator login
if (rbAdmin.Checked)
{
int Username = Convert.ToInt32(txtUsername.Text);
SchoolDBEntities db = new SchoolDBEntities();
var aid = from a in db.Administrators
where a.AID == Username
&& a.Password == txtPassword.Text
select a;
if (aid.Any())
{
MessageBox.Show("You are now logged in as Administrator");
this.Hide();
Main tss = new Main();
tss.Show();
}
else
{
MessageBox.Show("Incorrect Username or Password");
}
}
}
Below is my Main form, I need the btnMarks button disabled for Administrators.
I am unsure where to put the code to disable this button as well. If I could be able to call the radio button from the login form please show me how.
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
}
private void btnMarks_Click(object sender, EventArgs e)
{
frmStudentMarks marks = new frmStudentMarks();
marks.ShowDialog();
}
Thanks
I would recommend you making something like SessionManagement object to manage current session ( logged user, user rights etc. ).
public static class SessionManagement
{
static UserEntity sessionUser = null;
public static void LoggedAs(UserEntity user)
{
sessionUser = user;
}
// other methods/fields to manage session
}
After doing this you can just set session for currently logged user :
var tid = from t in db.Teachers
where t.TID == Username
&& t.Password == txtPassword.Text
select t;
SessionManagement.LoggedAs((UserEntity)tid); // make some explicit operators or something.
Now you have full control over who is logged in and you can check it's rights so all you have to do is to check it after InitializeComponent() method call :
public Main()
{
InitializeComponent();
btnMarks.Enabled = !SessionManagement.CurrentUser.IsAdministrator;
}
EDIT:
You've asked if there's something else you should do for this code to make it works. Answer is yes. This answer is basically a scheme for you to work something out. But since it's not an easy thing to do I'll explain it in somewhat more details.
Firstly, you have 2 types of Entity: Teacher and Administrator and you need to make one "unified" entity ( I named it UserEntity ). This unified entity should be convertible from both Teacher and Administrator entity.
My recommendation in code :
public class UserEntity
{
string _username;
public string Username
{
get { return _username; }
}
bool _isAdministrator;
public bool IsAdministrator
{
get { return _isAdministrator; }
}
public UserEntity(Administrator entity)
{
_isAdministrator = true;
_username = entity.AID;
}
public UserEntity(Teacher entity)
{
_isAdministrator = false;
_username = entity.TID;
}
public static explicit operator UserEntity(Administrator entity)
{
return new UserEntity(entity);
}
public static explicit operator UserEntity(Teacher entity)
{
return new UserEntity(entity);
}
}
Now you can do somehting like UserEntity userEntity = (UserEntity)teacher;
Next thing to do is to update SessionManagement by adding new method into it :
public static void LoggedAs(UserEntity entity)
{
if(sessionUser != null)
throw new InvalidOperationException("Cannot be logged 2 times with the same session");
sessionUser = entity;
}
And a property :
public static UserEntity CurrentUser
{
get { return sessionUser; }
}
Now all you have to do is to combine all of these into one huge chunk of code :
private void btnLogin_Click(object sender, EventArgs e)
// parts of your code till this line :
SchoolDBEntities db = new SchoolDBEntities();
var tid = from t in db.Teachers
where t.TID == Username
&& t.Password == txtPassword.Text
select t;
Teacher teacher = tid.FirstOrDefault();
if(teacher != null)
{
SessionManagement.LoggedAs((UserEntity)teacher);
}
// do the same with Administrator
Now since SessionManagement is static object you can use it everywhere inside your application and it will persist with all stored data meaning you can use :
public Main()
{
InitializeComponent();
btnMarks.Enabled = !SessionManagement.CurrentUser.IsAdministrator;
}
You need to maintain a static class for that in which you can add that the current user's type.
Kindly go through the following url
https://stackoverflow.com/a/14599474/1526972
The command button, by default, has a public access level so you can access and disable it from login form before to call the Show() method in this way:
tss.yourButtonName.Enabled = false;
Hope this help.
Christian

the sequence does not have elements executing linq query

Having this model class
public class Usuario
{
#region Atributos
private int _intID = 0;
private Perfil _Perfil_FK = null;
private String _strNombre = "";
private String _strPassword = "";
#endregion
#region Propiedades
public int ID
{
get { return _intID; }
set { _intID = value; }
}
public virtual Perfil Perfil_FK
{
get { return _Perfil_FK; }
set { _Perfil_FK = value; }
}
public int PerfilID { get; set; }
public String Nombre
{
get { return _strNombre; }
set { _strNombre = value; }
}
public String Password
{
get { return _strPassword; }
set { _strPassword = value; }
}
#endregion
}
I'm trying to use this query, the data base table have data, so i can't see the problem?
Usuario user = (from U in _db.Usuario
where ((U.Nombre == model.UserName) && (U.Password == encripPassword))
select U).First();
If you need more info about the data base let me know to update my question
Does the table actually have a row with that name and password?
When you run the generated SQL statement in SQL Management Studio, do you get a result?
Suggest checking your two values in UserName and encripPassword for valid values.
Usuario user = _db.Usuario
.FirstOrDefault(x=>x.Nombre == model.UserName
&& x.Password == encripPassword);
string sql = (user as ObjectQuery).ToTraceString(); //the SQL query generated.
if(user==null)
{
//doesn't exist.
}
Obviously you're not pointing to the right database, or your don't have a user name with that password (I'm guessing the encrypted password doesn't match what's in the DB. Try using FirstOrDefault(), then you can check for Null if the password is wrong...
Check if your class has the proper attributes that tell Linq to SQL how to match it against a database table.
Your class should have
[Table(Name="Nombres")]
attribute, and properties should have
[Column]
attributes, some should also be primary keys etc.
If you don't already have this, I suggest you generate the class using the Entity Class Generation tool: http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic32

Need a refresher course on property access

I need help with accessing class properties within a given class.
For example, take the below class:
public partial class Account
{
private Profile _profile;
private Email _email;
private HostInfo _hostInfo;
public Profile Profile
{
get { return _profile; }
set { _profile = value; }
}
public Email Email
{
get { return _email; }
set { _email = value; }
}
public HostInfo HostInfo
{
get { return _hostInfo; }
set { _hostInfo = value; }
}
In the class "Account" exists a bunch of class properties such as Email or Profile.
Now, when I want to access those properties at run-time, I do something like this
(for Email):
_accountRepository = ObjectFactory.GetInstance<IAccountRepository>();
string username = Cryptography.Decrypt(_webContext.UserNameToVerify, "verify");
Account account = _accountRepository.GetAccountByUserName(username);
if(account != null)
{
account.Email.IsConfirmed = true;
But, I get "Object reference not set..." for account.Email... Why is that?
How do I access Account such that account.Email, account.Profile, and so on
returns the correct data for a given AccountId or UserName.
Here is a method that returns Account:
public Account GetAccountByUserName(string userName)
{
Account account = null;
using (MyDataContext dc = _conn.GetContext())
{
try
{
account = (from a in dc.Accounts
where a.UserName == userName
select a).FirstOrDefault();
}
catch
{
//oops
}
}
return account;
}
The above works but when I try:
account = (from a in dc.Accounts
join em in dc.Emails on a.AccountId equals em.AccountId
join p in dc.Profiles on em.AccountId equals p.AccountId
where a.UserName == userName
select a).FirstOrDefault();
I am still getting object reference exceptions for my Email and Profile
properties. Is this simply a SQL problem or is there something else I need to be
doing to be able to fully access all the properties within my Account class?
Thanks!
Your getting this because Email is another class which has not been assigned yet. What you can do is in your constructor default the properties that link to other classes as new items. For example in your ctor:
public Account()
{
// Set Defaults
Email = new Email();
Profile = new Profile();
HostInfo = new HostInfo();
}
Then you can set their values as desired.
This looks like a case of handling null values on your properties. You should initialize the Email property to something other than null if you expect to store or query against it, or alter the queries so that they can expect to deal with null values. Also if you get a null value from the database, and your property cannot be set to null, the reverse problem occurs.
Are you declaring these properties yourself, or are you trying to indicate something like auto-generated code from like Linq-to-SQL?
If this is auto-generated where the Account table references the Email table, etc., then you probably just need to specify that you want those objects to load as well in the load options:
using (MyDataContext dc = _conn.GetContext())
{
var options = new DataLoadOptions();
options.LoadWith<Account>(a => a.Email);
options.LoadWith<Account>(a => a.Profile);
options.LoadWith<Account>(a => a.HostInfo);
dc.LoadOptions = options;
try
{
account = (from a in dc.Accounts
where a.UserName == userName
select a).FirstOrDefault();
}
catch
{
//oops
}
}
Just wanted to add: there is now a shorter form for declaring trivial properties:
public Profile Profile { get; set; }
public Email Email { get; set; }
public HostInfo HostInfo { get; set; }

Categories