Login application

  • (2 Pages)
  • +
  • 1
  • 2

21 Replies - 1235 Views - Last Post: 20 December 2011 - 09:28 AM Rate Topic: -----

#1 opticaltim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-December 11

Login application

Posted 19 December 2011 - 01:55 PM

Hi,

I'm making a login application but i have the following problem.
When an user clicks the button "Login" it is allways correct. I would like to check in my sql database if the user and password match. Does anyone have an idea?

Database.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace Monopoly.Data
{
    public class Database
    {
        private static String ConnectionString
        {
            get
            {
                return @"Data Source=PC-TIM; Initial Catalog=Monopoly; Integrated Security=True";
               
            }
        }

        // Connectie maken en openen
        private static SqlConnection GetConnection()
        {
            try
            {
                SqlConnection oCon = new SqlConnection(ConnectionString);
                oCon.Open();
                return oCon;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
            


        }

        // De connectie sluiten en vrijgeven
        private static void ReleaseConnection(SqlConnection oCon)
        {
            if (oCon != null)
            {
                oCon.Close();
                oCon.Dispose();
            }
        }


        private static SqlCommand BuildCommandParameters(String sStoredProcedureNaam, params SqlParameter[] dbParams)
        {
            SqlConnection oCon = GetConnection();
            SqlCommand oCommand = oCon.CreateCommand();
            oCommand.CommandType = CommandType.StoredProcedure;
            oCommand.CommandText = sStoredProcedureNaam;

            if (dbParams != null)
            {
                foreach (SqlParameter oPar in dbParams)
                {
                    oCommand.Parameters.Add(oPar);
                }
            }
            return oCommand;
        }


        // Een DataTable ophalen
        public static DataTable GetDT(String sStoredProcedureNaam, params SqlParameter[] dbParams)
        {
            SqlCommand oCommand = null;
            try
            {

                oCommand = BuildCommandParameters(sStoredProcedureNaam, dbParams);

                SqlDataAdapter oDA = new SqlDataAdapter();
                oDA.SelectCommand = oCommand;

                DataTable oDT = new DataTable();
                oDA.Fill(oDT);

                return oDT;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }

            finally
            {
                if (oCommand != null)
                {
                    ReleaseConnection(oCommand.Connection);
                }
            }
        }



        // DataReader ophalen
        public static SqlDataReader GetDR(String sStoredProcedureNaam, params SqlParameter[] dbParams)
        {
            SqlCommand oCommand = null;
            SqlDataReader oDR = null;

            try
            {
                oCommand = BuildCommandParameters(sStoredProcedureNaam, dbParams);
                oDR = oCommand.ExecuteReader(Commandbehavior.CloseConnection);

                return oDR;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }

            finally
            {
                if (oCommand != null)
                {
                    ReleaseConnection(oCommand.Connection);
                }
            }
        }

        // Slechts 1 resultaat teruggeven
        public static Object ExecuteScalar(String sStoredProcedureNaam, params SqlParameter[] dbParams)
        {
            SqlCommand oCommand = null;

            try
            {
                oCommand = BuildCommandParameters(sStoredProcedureNaam, dbParams);
                Object oObject = oCommand.ExecuteScalar();

                return oObject;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }

            finally
            {
                if (oCommand != null)
                {
                    ReleaseConnection(oCommand.Connection);
                }
            }
        }


        // SQL zonder terugkeer resultaat uitvoeren
        public static void ExcecuteSQL(String sStoredProcedureNaam, params SqlParameter[] dbParams)
        {
            SqlCommand oCommand = null;

            try
            {
                oCommand = BuildCommandParameters(sStoredProcedureNaam, dbParams);
                oCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            finally
            {
                if (oCommand != null)
                {
                    ReleaseConnection(oCommand.Connection);
                }
            }
        }

    }
}
    


Loginwindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using Monopoly.Connector;
using Monopoly.Library;

namespace Monopoly.UI
{
    /// <summary>
    /// Interaction logic for Loginwindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        Gateway connector = Gateway.Instance;

        public LoginWindow()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            if (ValidateLogin())
            {
                try
                {
                    Player validPlayer = connector.Proxy.VerifyUserInput(txtUserName.Text, txtPaswoord.Password);
                    if (validPlayer != null)
                    {


                        Start(validPlayer);
                    }
                    else
                    {
                        MessageBox.Show("Of uw naam is niet goed, of uw paswoord is verkeerd");
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Oops, something went wrong: " + ex.Message);
                }
                
            }         
        }

        private void Start(Player p)
        {
            MainWindow m = new MainWindow(p);
            m.Show();
            this.Close();
        }

        private bool ValidateLogin()
        {
            bool isLoginValid = true;
            StringBuilder messageBuilder = new StringBuilder(2);

            if (string.IsNullOrEmpty(txtUserName.Text))
            {
                isLoginValid = false;
                messageBuilder.AppendLine("Username is required.");
            }
            if (string.IsNullOrEmpty(txtPaswoord.Password))
            {
                isLoginValid = false;
                messageBuilder.AppendLine("Password is required.");
            }
            if (!isLoginValid)
            {
               MessageBox.Show(messageBuilder.ToString(), "Please fill in the required fields", MessageBoxButton.OK, MessageBoxImage.Information );
            }
            return isLoginValid;
        }


    }
}





PlayerData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using Monopoly.Library;
using System.Data;
using System.Data.SqlClient;

namespace Monopoly.Data
{
  //  [DataContract]
    public class PlayerData
    {

        public static Player VerifyUserInput(string naam, string paswoord)
        {

            //ParameterList aanmaken
            List<SqlParameter> parameters = new List<SqlParameter>();

            //Parameter(s) aanmaken
            SqlParameter parA = new SqlParameter("PlayerName", naam);
            SqlParameter parB = new SqlParameter("PlayerPaswoord", paswoord);
            //Parameter(s) toevoegen
            parameters.Add(parA);
            parameters.Add(parB);

            DataTable dt = Database.GetDT("dbo.Player", parameters.ToArray());
            SqlCommand command = new SqlCommand("SELECT * FROM [Player] WHERE [PlayerName]='" + naam + "' AND [PlayerPaswoord]='" + paswoord + "'");

            if (dt.Rows.Count == 1)
            {

                return new Player(naam, paswoord);
            }
            return new Player(naam, paswoord);

        }
  }
}




Thanks in advance!

Is This A Good Question/Topic? 0
  • +

Replies To: Login application

#2 RexGrammer  Icon User is offline

  • Coding Dynamo
  • member icon

Reputation: 182
  • View blog
  • Posts: 783
  • Joined: 27-October 11

Re: Login application

Posted 19 December 2011 - 02:03 PM

Some good references:

SQL Basics in C# (DIC Tutorial)
Retrieve populated DataTable from SQL Server (DIC Snippet)

Ahhh, I found the error. It's in your PlayerData.cs.

See this:
if (dt.Rows.Count == 1)
	            {
	 
	                return new Player(naam, paswoord);
	            }
return new Player(naam, paswoord);



First you check if something has been returned, if it's true then you return a new player. But non the less even if nothing returned you will return a new player.

The solution:

Replace this line of code (the one out of the if):
return new Player(naam, paswoord);



with:

return null;



Good Luck on your WPF Monopoly!

P.S. Please format your code before posting, and if you're going to comment it please comment it in English (this way it just confuses us).

This post has been edited by RexGrammer: 19 December 2011 - 02:15 PM

Was This Post Helpful? 1
  • +
  • -

#3 opticaltim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-December 11

Re: Login application

Posted 19 December 2011 - 02:19 PM

Thanks ;) stupid mistake :)

Forgot to mention that i get a NullReferenceException on
if (dt.Rows.Count == 1)

Was This Post Helpful? 0
  • +
  • -

#4 RexGrammer  Icon User is offline

  • Coding Dynamo
  • member icon

Reputation: 182
  • View blog
  • Posts: 783
  • Joined: 27-October 11

Re: Login application

Posted 19 December 2011 - 02:30 PM

No problem, just make sure that next time you describe your problems in detail and that you do a check of your code before asking for help.

I'm really curious about your project (since I tried to make a monopoly, and it spectacularly failed! :(). So if you want to upload the source to GitHub or something I would be grateful (also I would try to contribute what I can). I understand if you don't want to share (I don't share everything, so how could I expect that of someone else? :)).

Oh and:

View Postopticaltim, on 19 December 2011 - 09:19 PM, said:

Forgot to mention that i get a NullReferenceException on
if (dt.Rows.Count == 1)


is this another problem you need help or just a note?

This post has been edited by RexGrammer: 19 December 2011 - 02:31 PM

Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5627
  • View blog
  • Posts: 12,071
  • Joined: 02-June 10

Re: Login application

Posted 19 December 2011 - 02:50 PM

View Postopticaltim, on 19 December 2011 - 03:19 PM, said:

i get a NullReferenceException on
if (dt.Rows.Count == 1)


What does this error mean?
Was This Post Helpful? 1
  • +
  • -

#6 opticaltim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-December 11

Re: Login application

Posted 19 December 2011 - 03:00 PM

I just started with the monopoly, when i have some more i will upload it ;)
What i'm trying to accomplish:

1. Multiple users can connect and play different games.
2. Users can create their own board and save them. (choose how many stations, with how much many they start, prices, etc..)
3. Play the entire game (buy,sell,chat,throw dices,...)
4. Users can chat with each other
5. Everything needs to be logged and put in database
6. Users can connect through IP (database is on my computer)
(And probably much more :P)



If you know the solution for the NullReferecenException, go ahead :)
Was This Post Helpful? 0
  • +
  • -

#7 RexGrammer  Icon User is offline

  • Coding Dynamo
  • member icon

Reputation: 182
  • View blog
  • Posts: 783
  • Joined: 27-October 11

Re: Login application

Posted 19 December 2011 - 03:02 PM

You created a SqlCommand but never executed it, thus never got the row for the dataTable.

DataTable dt = Database.GetDT("dbo.Player", parameters.ToArray());
//Ok but where did you execute it?
SqlCommand command = new SqlCommand("SELECT * FROM [Player] WHERE [PlayerName]='" + naam + "' AND [PlayerPaswoord]='" + paswoord + "'");

//And then checking for an unresisting row, because the SqlCommand never got executed
if (dt.Rows.Count == 1)



Also you might want to first start off with a more easier project, like just playing monopoly (offline with two-players and a default table), then move onto extra features. It's probably more complicated then you think! :D

This post has been edited by RexGrammer: 19 December 2011 - 03:08 PM

Was This Post Helpful? 1
  • +
  • -

#8 opticaltim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-December 11

Re: Login application

Posted 19 December 2011 - 03:53 PM

I should probably work with stored procedures? (Never done it before)

CREATE PROCEDURE dbo.StoredProcedure2
	/*
	(
	@parameter1 int = 5,
	@parameter2 datatype OUTPUT
	)
	*/
AS
	/* SET NOCOUNT ON */
	RETURN



What should i put here? Connectionstring?
Was This Post Helpful? 0
  • +
  • -

#9 RexGrammer  Icon User is offline

  • Coding Dynamo
  • member icon

Reputation: 182
  • View blog
  • Posts: 783
  • Joined: 27-October 11

Re: Login application

Posted 20 December 2011 - 06:29 AM

I'm just going to reference you to here:

Stored Procedures (MSDN Article)

Read it then read the ones that are bellow it in the list in the left.

Then you judge should you work with them or what you need to put there! :D
Was This Post Helpful? 0
  • +
  • -

#10 opticaltim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-December 11

Re: Login application

Posted 20 December 2011 - 07:13 AM

I've created a stored procedure

ALTER PROCEDURE ValidateUser

	@UserName varchar(50),
	@Password varchar(50)

AS
	
	Begin
	if exists (select * from Player where PlayerName = @UserName and PlayerPaswoord = @Password)
	select 1;
	else
	select 0;
	end

	




And change the PlayerData code to:

        public static Player VerifyUserInput(string naam, string paswoord)
        {

            try
            {
                bool rv = false;

                string ConnectionString = "Data Source=PC-TIM; Initial Catalog=Monopoly; Integrated Security=True";
                SqlConnection oCon = new SqlConnection(ConnectionString);
                SqlCommand command = new SqlCommand();
                oCon.Open();

                command.Connection = oCon;
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "ValidateUser";

                command.Parameters.Add("@UserName", SqlDbType.VarChar , 50).Value = naam;
                command.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = paswoord;

                rv = Convert.ToBoolean(command.ExecuteScalar());
                oCon.Close();

                //return new Player(naam, paswoord);
            }
            catch (Exception ex)
            {

            }
            return null;
           
            
        }




Now my validPlayer = null, so i allways get the message "Incorrect user or password"
Any idea on this?

P.S Meanwhile i've managed to fix the dicing and chat.
P.S I can't find how to edit a post :P
Was This Post Helpful? 0
  • +
  • -

#11 RexGrammer  Icon User is offline

  • Coding Dynamo
  • member icon

Reputation: 182
  • View blog
  • Posts: 783
  • Joined: 27-October 11

Re: Login application

Posted 20 December 2011 - 07:30 AM

There are two possible reasons:
1. You didn't execute the query properly
2. Or didn't write it well

Come on... This is easy, you should be able to figure this one out. Since we discussed that in the previous posts.


I think that new members can't edit posts.

New Members = Members that have a low post count (I'm not sure what amount of posts is needed so that you can edit your posts)
Was This Post Helpful? 0
  • +
  • -

#12 opticaltim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-December 11

Re: Login application

Posted 20 December 2011 - 07:44 AM

I know that the validPlayer = null because I return null
Have absolutely no idea how fix this. If you the solution please help
Was This Post Helpful? 0
  • +
  • -

#13 RexGrammer  Icon User is offline

  • Coding Dynamo
  • member icon

Reputation: 182
  • View blog
  • Posts: 783
  • Joined: 27-October 11

Re: Login application

Posted 20 December 2011 - 07:50 AM

Scratch what I said. It was wrong I see it now.

You never return a valid player:

 //return new Player(naam, paswoord);



You commented out the line that should return the player.

You should check if the query has results, and if it does then execute that line:

if (/*insert_logic_here*/)
{
return new Player(naam, paswoord);
}



The /*insert_logic_here*/ states that you should insert some checking logic there (as in checking if the player has inputted valid parameters).

Leave everything else intact.

This post has been edited by RexGrammer: 20 December 2011 - 07:52 AM

Was This Post Helpful? 0
  • +
  • -

#14 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

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

Re: Login application

Posted 20 December 2011 - 07:50 AM

You are wondering why your validPlayer is null? What are you returning from the VerifyUserInput method?

I would also use a different SQL query. Why not just COUNT the number of records in the Player table where the PlayerName and PlayerPaswoord is the same as the parameters?
Was This Post Helpful? 0
  • +
  • -

#15 Curtis Rutland  Icon User is offline

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


Reputation: 4559
  • View blog
  • Posts: 7,972
  • Joined: 08-June 10

Re: Login application

Posted 20 December 2011 - 08:27 AM

OK, some SQL advice here: first, never use SELECT * ... in a program (or even a stored procedure). It's OK for doing quick queries in SSMS, but don't put that query in your code. Write out the columns you are actually looking to return. It'll save bandwidth, and if you index your DB properly, it can easily increase performance. Also, six months from now when you decide you need a new column in your DB, you're not changing the query along with the table without realizing it.

Second, absolutely, under no circumstances, do you want to store plain-text passwords in a Database, or anywhere else for that matter. Hash them. Look up "C# Password Hashing" for more information. It's never too early to learn this lesson.

Third, learn about scalar queries. There's no need to select all the rows and then count them, when you can just use a COUNT query.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2