13 Replies - 5427 Views - Last Post: 10 March 2011 - 11:11 AM Rate Topic: -----

#1 DarkForm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 09-March 11

c# WindowsForm SQL problem

Posted 09 March 2011 - 11:45 AM

Hey guys, this is my first post on this forum. I was lurking about and thought that this would be a perfect place to ask for help. I am building a Windows LoginForm application. That will connect to a SQL databse using Microsoft SQL server 2008 R2. Me and a friend have been trying to get this to work for 5 months straight by using other peoples example code and our own. So far no luck. I will describe my problem in full, and provide the forum the code we are using.

This is the problem we are running into. With SQL server set up. We created a database, we also have SQL server set up at programming class in school. Every time we run the program, and type the user name and password, NOTHING happens when we click the button. We tried putting everything in a try/catch loop and output the exception. Nothing works, nothing happens. Nothing is being done. We just want the application to check if the username and password exists on the database, then show a different form. So thinking maybe it was just the school computers, I took the program home and installed Microsoft SQL server 2008 R2 on my local machine. The SAME thing happens. We have tried making new databases, played with the connection properties, fiddled with the security and permissions in the database. Added a data source connection in Visual Studio. We have tried almost everything. We really need help trying to understand why this wont work. Writing a simple counsel application to pull data from the North wind Database (Microsoft's example DB) it read data perfectly. Below, will be the code we are using in the Form itself. Any and all help will greatly be appreciated.

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.Sql;
using System.Data.SqlClient;
using System.Configuration;

namespace LoginForm
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Demonstrates how to work with SqlCommand objects
        /// </summary>
        private bool CompareStrings(string string1, string string2)
        {
            return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                SqlConnection UGIcon = new SqlConnection();  
	            UGIcon.ConnectionString = "Server=prog-2ua0210rw0\\programming; Database=myDB; User Id=sa; password=**************"; 
                UGIcon.Open();

                SqlCommand cmd = new SqlCommand("SELECT ISNULL(stUsername, '') AS stUsername, ISNULL(stPassword,'') AS stPassword, ISNULL(stRole,'') AS stRole FROM Users WHERE stUsername='" + textBoxUsername.Text + "' and stPassword='" + textBoxPassword.Text + "'", UGIcon);

                SqlDataReader dr = cmd.ExecuteReader();

                string userText = textBoxUsername.Text;
                string passText = textBoxPassword.Text;
                string stRole = "admin";

                while (dr.Read())
                {
                    if (this.CompareStrings(dr["stUsername"].ToString(), userText) &&
                        this.CompareStrings(dr["stPassword"].ToString(), passText) &&
                        this.CompareStrings(dr["stRole"].ToString(), stRole))
                    {
                        MessageBox.Show("OK");
                    }
                    else
                    {
                        MessageBox.Show("Error");
                    }

                }

                dr.Close();

                UGIcon.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}


If it helps, we were trying to make a system kind of like what Valve does for steam where the little login form pops up. When we type the data into the text boxes, and press login. NOTHING AT ALL happens. Thank you again!

Is This A Good Question/Topic? 0
  • +

Replies To: c# WindowsForm SQL problem

#2 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: c# WindowsForm SQL problem

Posted 09 March 2011 - 11:53 AM

If you've been working on this for five months I highly suggest going to your teacher and ask him for help. Wow. This should take you at most 2 days if you're a beginner.

Having said that, let's dissect your code. First it's bad. Please don't be offended, we're here to help new programmers and you're here to learn, correct? Great. :)

1. You're doing everything in your event handler, tightly coupling your UI with the underlying data access logic.
2. You're using try-catch as a safety net, but not really doing anything with it.

So, tackling the first problem of many. How can we separate the data access logic from the UI?

Why don't you create a class called DataAccess and have a method:

bool AuthenticateUser(string username, string password)


So all of your data access logic and comparison of an existing user will be in this data access class? So far so good?
Was This Post Helpful? 1
  • +
  • -

#3 DarkForm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 09-March 11

Re: c# WindowsForm SQL problem

Posted 09 March 2011 - 11:59 AM

I have asked my teacher, who I am believing now is C# illiterate. She only seems to ever want to do Java. And frankly, I hate java.

No offence taken, please be harsh, honestly, I really am here to learn. So, your saying create a class by going up to the top and adding a new item "class" and write a method for Authenticating a user? I suppose this would clear up the clutter in the button, but I didn't think that would matter all that much. It isn't good programming practice yes, but we just want the stupid thing to authenticate a user.
Was This Post Helpful? 0
  • +
  • -

#4 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: c# WindowsForm SQL problem

Posted 09 March 2011 - 12:05 PM

You're an engineer! Take pride in your work and show some professionalism by writing good code. Make it a habit now, rather than later. It pays off big time with time.

So to answer your question, yes. Create a class and in that class, that method. Encapsulate the whole, 'Database, is this user valid?' so you can call if cleanly from the button.
Was This Post Helpful? 0
  • +
  • -

#5 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5932
  • View blog
  • Posts: 12,855
  • Joined: 16-October 07

Re: c# WindowsForm SQL problem

Posted 09 March 2011 - 12:29 PM

If I ever saw this code, I'd immediately enter my username as "'; DROP TABLE Users; select 'have a nice day';". Just saying...

Perhaps:

namespace LoginForm {
	public partial class Form2 : Form {
		public Form2() {
			InitializeComponent();
		}
		
		private SqlConnection getConnection() {
			return new SqlConnection("Server=prog-2ua0210rw0\\programming; Database=myDB; User Id=sa; password=**************");
		}

		private bool validateLogin(string user, string pass, string role) {
			bool valid = false;
			SqlCommand cmd = getConnection().CreateCommand(
				"SELECT stPassword, stRole"
				+ " FROM Users"
				+ " WHERE stUsername=@stUsername" // if stUsername isn't a primary key or unique, it should be
			);
			cmd.Parameters.AddWithValue("@stUsername", user);
			try {
				cmd.Connection.Open();
				using (SqlDataReader dr = cmd.ExecuteReader()) {
					if(dr.Read()) {
						if (!dr.IsDBNull(0) && !dr.IsDBNull(1)) {
							valid = pass.Equals(dr[0]) && role.Equals(dr[1]);
						}
					}
				}
			} finally {
				cmd.Connection.Close();
			}
			return valid;
		}
		

		private void button1_Click(object sender, System.EventArgs e) {
			try {
				if (validateLogin(textBoxUsername.Text, textBoxPassword.Text, "admin")) {
					MessageBox.Show("OK");
				} else {
					MessageBox.Show("Error");
				}
			} catch (Exception ex) {
				MessageBox.Show(ex.Message);
			}
		}
	}
}


This post has been edited by baavgai: 09 March 2011 - 12:31 PM

Was This Post Helpful? 0
  • +
  • -

#6 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1526
  • View blog
  • Posts: 5,961
  • Joined: 21-March 08

Re: c# WindowsForm SQL problem

Posted 09 March 2011 - 12:41 PM

Also, your query and your code are redundant. Your query is going to return the record for the user with that username and that password. So why are you checking if they are correct? If something is returned, then the login is successful. If nothing is returned, then the login failed.
Was This Post Helpful? 0
  • +
  • -

#7 DarkForm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 09-March 11

Re: c# WindowsForm SQL problem

Posted 10 March 2011 - 09:37 AM

Hmm. SQL injection. Yes, something to be worried about. But really this program was just to see if it would even be used for authenticating a user. I see now though it isn't. Is there possibly any good tutorial on login programs in c# using SQL I can look at? or maybe example code I could look at? Thank you guys again :)
Was This Post Helpful? 0
  • +
  • -

#8 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4577
  • View blog
  • Posts: 8,019
  • Joined: 08-June 10

Re: c# WindowsForm SQL problem

Posted 10 March 2011 - 09:48 AM

Honestly, if you're going to do much database work, I highly recommend Entity Framework 4, or at least Linq to Sql. ORMs are just so much easier to deal with than raw SQL and data sets. At least, it feels that way to me, since I know how to write LINQ queries.
Was This Post Helpful? 0
  • +
  • -

#9 DarkForm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 09-March 11

Re: c# WindowsForm SQL problem

Posted 10 March 2011 - 09:56 AM

Well I may try experimenting with other things. When I look for tutorials on this matter, I only get ASP stuff in c# for web sites. I don't want anything to do with a web site. I just want it to be a standalone program like Steam is. Login form sign in and your good. But you guys are helping a bunch.
Was This Post Helpful? 0
  • +
  • -

#10 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4577
  • View blog
  • Posts: 8,019
  • Joined: 08-June 10

Re: c# WindowsForm SQL problem

Posted 10 March 2011 - 10:01 AM

Well, the problem is you're looking for a specific solution to a generic question. Your question isn't really how to make a login form, it's how to query a database using some provided values. If you shift your thinking, you'll probably find some more tutorials that are helpful, even if they don't solve your exact issue. They'll teach you the skills you need to do that solution.

Also, a big suggestion here if you're going to have anyone actually use an application like this: hash your passwords. Nobody should ever store passwords in clear text, even in a password protected database. You shouldn't be able to reconstruct the original text from a stored password. That's why most websites can't send you your password, but they can reset it for you.
Was This Post Helpful? 0
  • +
  • -

#11 DarkForm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 09-March 11

Re: c# WindowsForm SQL problem

Posted 10 March 2011 - 10:48 AM

But thats just the thing, I have done this, and used loads of example problems/code. It keeps doing the same thing over and over. Nothing happens on button click ever. I don't even know if its even connecting. Both at home or school.
Was This Post Helpful? 0
  • +
  • -

#12 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: c# WindowsForm SQL problem

Posted 10 March 2011 - 10:52 AM

So you're saying you put a breakpoint on the event and it never even enters the event?

Are you sure the control is hooked to the event? You know when you double click a button, it generates this code:

this.button1.Click += new System.EventHandler(this.button1_Click);

Was This Post Helpful? 1
  • +
  • -

#13 DarkForm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 09-March 11

Re: c# WindowsForm SQL problem

Posted 10 March 2011 - 10:57 AM

Yea. I even used code from the c# books here at school. I don't even know if anything is connecting. I have been on youtube as well to watch tutorials. It's becoming annoying that its taking this long. Thats why I thought if I took it home it would work. Sadly it has the same result with all the code we have used. No error is being thrown. That makes it harder to try and understand whats going on.
Was This Post Helpful? 0
  • +
  • -

#14 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: c# WindowsForm SQL problem

Posted 10 March 2011 - 11:11 AM

Quote

Yea.


Ok, so the control IS hooked to the event. You've entered the appropriate designer class and triple-checked correct?

If so, then I'm stuck. I don't know why it wouldn't work. Are you referencing the correct control? Maybe your event is hooking to button2 instead of button1.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1