0

How can I get the data from the a table and convert it into string. I'm trying to make [User Level] into a string variable or get it to a label.

My current code is

private void btnLogin_Click(object sender, EventArgs e)
{
    if (attempt == 0)
    {
        lblMsg.Text = ("ALL 3 ATTEMPTS HAVE FAILED - CONTACT ADMIN");
        return;
    }

    scn.ConnectionString = @"Data Source=DESKTOP-39SPLT0;Initial Catalog=SalesandInventory;Integrated Security=True";            
    SqlCommand scmd = new SqlCommand("select count ([User Level]) as count from tblUsers where [User Name]=@usr and Password=@pwd", scn);            
    scmd.Parameters.Clear();
    scmd.Parameters.AddWithValue("@usr", txtUser.Text);
    scmd.Parameters.AddWithValue("@pwd", txtPass.Text);            
    scn.Open();

    if (scmd.ExecuteScalar().ToString() == "1")                
    {

        MessageBox.Show("You are granted with access.");
        this.Hide();
        frmMain frmmain = new frmMain();
        frmmain.Closed += (s, args) => this.Close();
        frmmain.Show();

    }
    else
    {
        MessageBox.Show("Invalid Username or Password.");
        lblMsg.Text = ("You have only " + Convert.ToString(attempt) + " attempt left to try.");
        --attempt;
        txtUser.Clear();
        txtPass.Clear();
    }
}
giokoguashvili
  • 2,013
  • 3
  • 18
  • 37
Chres Abte
  • 39
  • 1
  • 6
  • 3
    So exactly what is your problem - we cannot be expected to guess what you are having difficulty with. Do you get a compilation error - if so what line & what is the error? Do you get an exception thrown - if so tell us what line & show the exception? – PaulF Mar 07 '18 at 10:45
  • @PaulF I'm sorry I don't have any error. I'm a newbie and just got this code on c-sharpcorner.com and I'm trying to get a kind of authentication where I could differentiate an admin user from a normal user and I don't know where to start or where to change. – Chres Abte Mar 07 '18 at 10:50
  • @ChresAbte the biggest bug here is the entire code - don't try to write your own authentication code. *DON'T* store passwords in the database. ASP.NET, MVC or Webforms have strong authentication **and** authorization mechanisms already. Desktop applications don't need them because they *know* who the current user is and the group he/she belongs to. Even if you can't use the current user's identity, you can use the ASP.NET mechanisms – Panagiotis Kanavos Mar 07 '18 at 11:04
  • You could, eg use [WindowsPrincipal.IsInRole](https://msdn.microsoft.com/en-us/library/system.security.principal.windowsprincipal.isinrole(v=vs.110).aspx) to check whether the current user belongs to a group – Panagiotis Kanavos Mar 07 '18 at 11:11
  • You can get the current user through the [Thread.CurrentPrincipal](https://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal(v=vs.110).aspx) property – Panagiotis Kanavos Mar 07 '18 at 11:15
  • @ChresAbte I found the article you meant. I'd suggest you don't use anything from that site. Too many articles are copied from other sources without even a mention much less permission. Others, like this one, are extremely harmful and go against any security advice. In 2017 it's *very* well known that such code should be avoided at all costs – Panagiotis Kanavos Mar 07 '18 at 11:45
  • 1
    You asked this [question a short while ago in longer form](https://stackoverflow.com/questions/49048926/sql-user-admin-rights-to-windowsform-buttons-c-sharp) & accepted an answer, is there a reason why you are asking again? – PaulF Mar 07 '18 at 11:49
  • @ChresAbte it looks like you are experimenting. Why don't you use *.NET's* actual mechanisms first before trying custom solutions? – Panagiotis Kanavos Mar 07 '18 at 11:54

4 Answers4

0

If you want to read both the count and the user level you can use the SqlDataReader and ExecuteReader instead of ExecuteScalar(). I made a slight change to your SQL query string. Run this and review your variables to see what you're returning.

SqlCommand scmd = new SqlCommand("select count ([User Level]) as UserCount, [User Level] from tblUsers where [User Name]=@usr and Password=@pwd", scn);
scmd.Parameters.Clear();
scmd.Parameters.AddWithValue("@usr", txtUser.Text);
scmd.Parameters.AddWithValue("@pwd", txtPass.Text);            
scn.Open();

string userLabel = "";
int userCount = 0;
try
{
      SqlDataReader reader = cmd.ExecuteReader();
      if (reader.Read())
      {
        userLabel = (string)reader["User Level"];
        userCount = (int)reader["UserCount"];
      }
 }
 catch (Exception ex)
 {
      //do something here if it fails. 
 }

if (userCount == 1) 
{
     MessageBox.Show("You are granted with access.");
     //rest of your code....
}

Maybe your query is just not returning 1 user as you're expecting. Try running the query in your db to see what it's returning. If this is the case then adjust the code as needed.

ismael.
  • 418
  • 2
  • 7
  • Hello password breach and €10M GDPR fine – Panagiotis Kanavos Mar 07 '18 at 11:06
  • 2
    @PanagiotisKanavos I'm assuming this is an exercise for op. User authentication shouldn't be done this way. But we all start somewhere. – ismael. Mar 07 '18 at 11:09
  • 1
    @ismale then the exercise is a huge failure. We *don't* start from this code for any reason. The proper way to do it is documented. The proper way to use *authentication* is part of any .NET course and certification. It's clearly explained in the docs. – Panagiotis Kanavos Mar 07 '18 at 11:12
  • 1
    @PanagiotisKanavos I'm sorry this is only a class project those you advised on comments are currently way above my understanding. – Chres Abte Mar 07 '18 at 11:24
  • @ismael thanks for the clarification of the userCount I'm still trying your suggestions – Chres Abte Mar 07 '18 at 11:25
  • @ChresAbte even more reason to *NOT* use such code. If you showed that to a code interview it would be an instant no-hire. Instead of learing something *completely* wrong, learn how .NET actually works. I'd also suggest looking for a *different* course, if that's the kind of exercises they use. Pluralsight offers excellent courses from well-known authors and MVPs. You can get 3 months free access to them through the Visual Studio Dev Essentials program (also free) – Panagiotis Kanavos Mar 07 '18 at 11:35
  • 1
    Dont worry about @PanagiotisKanavos. If this is only for a project in a class and you need to get it to work. Dont mind about the requirements to GDPR. Sometimes you need to start in the small to understand the bigger. I agree with all the logic Pana writes. But sometimes you just need to get started. And then you can apply all the business requirements afterwards. Not everybody is C# gurus. Im second guessing that he always write the perfect code first time. If this is the answer to your problems go with it – SqlKindaGuy Mar 07 '18 at 13:26
  • @ChresAbte were you able to check this out? I agree with plaidDK here. It's good to learn what to do and what not to do. Either way you're learning. – ismael. Mar 08 '18 at 12:34
  • @ismael. I already sorted out this issue, but for this time for the sake of my project specially my grade this will be okay I think my teacher would not bug me out about security issues this time I don't even know if my teacher knows about theses security essentials in .NET but thanks. I will be posting what I did to resolve my issue. – Chres Abte Mar 09 '18 at 16:00
0

If want to read all data from table then please use this code.

    SqlCommand scmd = new SqlCommand("select * from tblUsers where [User Name]=@usr and Password=@pwd", scn);
    DataTable result = new DataTable();
    using (SqlDataReader reader = scmd.ExecuteReader())
    {
     result.Load(reader);
    }

then you can read data from table column.use this code

    result.Load(reader);          
    var userLevel=result[0]["User Level"]
0

Your problem resides in your SQL query.

select count ([User Level]) as count from tblUsers where [User Name]=@usr and Password=@pwd

You are selecting a COUNT() and not the actual [User Level]. The COUNT() will always return a number, in this case 1 if an user with the supplied username and password exists (if it has a PRIMARY KEY) or 0 if it doesn't. You should try changing the query to:

select [User Level] from tblUsers where [User Name]=@usr and Password=@pwd

Then you can check it's user level with

string userLevel = scmd.ExecuteScalar();

If userLevel == null then the username does not exists (or doesn't have the supplied password). Keep in mind that if the value of [User Level] is NULL in your database, the ExecuteScalar() will return a DBNull which can't be cast into a String and will fail.

EzLo
  • 13,780
  • 10
  • 33
  • 38
0

I changed my code and send a String to the mainform in a label form. I used sqladapter instead of sqlcommand.

if (dt.Rows.Count == 1)
            {
                if (dt.Rows[0][0].ToString() == "Admin")
                {
                    MessageBox.Show("You are granted with access.", "Welcome!");
                    this.Hide();
                    frmMain fma = new frmMain(dt.Rows[0][0].ToString());
                    fma.Closed += (s, args) => this.Close();
                    fma.Show();
                }
                else if (dt.Rows[0][0].ToString() == "User")
                {
                    MessageBox.Show("You are granted with access.", "Welcome!");
                    this.Hide();
                    frmMain fma = new frmMain(dt.Rows[0][0].ToString());
                    fma.Closed += (s, args) => this.Close();
                    fma.Show();
                }
            }
Chres Abte
  • 39
  • 1
  • 6