Click here to Skip to main content
15,907,875 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hello Everyone

I have created a Client / Server Login application in WPF. When I execute the server application it waits for the client to connect, then when I execute the Client application and I try to enter the password and I click the login button it gives me an error saying...

System.NullReferenceException..

I'm stuck and im very new to this WPF, If someone can help me on this I would appritiated a lot

This is the Code for Server class...

<pre lang="msil">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.Navigation;
using System.Windows.Shapes;
using System.Timers;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using System.Windows.Threading;
using System.Collections;
using System.ComponentModel;
using System.Windows.Controls.Primitives;

namespace DtposServer
{
  // This stores data about each client ClientData
  public struct ClientData
  {
    public Socket structSocket;
    public Thread structThread;
  }
  /// <summary>
  /// Interaction logic for TCPServer.xaml
  /// </summary>
  public partial class TCPServer : Window
  {
    private System.Timers.Timer clockTimer;
    //===================================\\
    private StatusBar statusBar1 = new StatusBar();
    private TcpListener tcpLsn;
    private Hashtable ht = new Hashtable();
    private static Int32 connectId = 0;
    private Thread tcpThd;
    private string ipAddress = "0.0.0.0";
    //private System.ComponentModel.IContainer components;
    public TCPServer()
    {
      InitializeComponent();
      clockTimer = new System.Timers.Timer(1000);
      clockTimer.Elapsed += new ElapsedEventHandler(clockTimer_Elapsed);
      clockTimer.Start();
      DataContext = this;
      // ============================================================ \\
      tcpLsn = new TcpListener(System.Net.IPAddress.Parse(ipAddress), 8000);
      tcpLsn.Start();
      txtBlock1.Text = "IP Address listen at: " + "   " + tcpLsn.LocalEndpoint.ToString();
      tcpThd = new Thread(WaitingForClient);
      tcpThd.Start();
    }
    void clockTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
      Dispatcher.BeginInvoke(new Action(UpdateCurrentDateTime));
    }
    #region " Server Waiting For Client To Connect "
    // Waiting For Client
    public void WaitingForClient()
    {
      ClientData CData = default(ClientData);
      while (true)
      {
        // Accept will block until someone connects
        CData.structSocket = tcpLsn.AcceptSocket();
        Interlocked.Increment(ref connectId);
        CData.structThread = new Thread(ReadSocket);
        lock (this)
        {
          //It is used to keep connected Sockets and active thread
          ht.Add(connectId, CData);
          updateDataGrid(("Connection accepted."));
          updateDataGrid(("Connected User: > " + connectId + " Time: " + DateTime.Now.ToLongTimeString()));
          updateDataGrid(("---------------------------------------------"));
        }
        CData.structThread.Start();
      }
    }
    #endregion
    #region " Server Read Socket When Client Connects "
    //Read Socket
    public void ReadSocket()
    {
        //Real-Id will not be changed for each thread, but connectId is
        //changed. It can not be used to delete object from Hashtable
        Int32 realId = connectId;
        Byte[] receive = null;
        ClientData cd = (ClientData)dataHolder(realId);
        Socket s = cd.structSocket;
        int ret = 0;
        while (true)
      {
            if (s.Connected)
        {
                receive = new Byte[100];
                try
          {
                    //Receive will block until data coming ret is 0 or Exception
                    //will happen when Socket connection is broken
                    ret = s.Receive(receive, receive.Length, 0);
                    if (ret > 0)
            {
                        //ClientData clntData = new ClientData();
                        foreach (ClientData clntData in ht.Values)
              {
                            if (clntData.structSocket.Connected)
                {
                                clntData.structSocket.Send(receive, ret, SocketFlags.None);
                            }
                        }
            }
                    else
            {
                        break; // TODO: might not be correct. Was : Exit While
                    }
                }
          catch (Exception e)
          {
                    updateDataGrid(e.ToString());
                    if (!s.Connected)
            {
                        break; // TODO: might not be correct. Was : Exit While
                    }
                }
            }
        }
        CloseTheThread(realId);
    }
    #endregion
    #region " Server Closing The Thread "
    // Close The Thread
    private void CloseTheThread(long realId)
    {
      try
      {
        ClientData cd = (ClientData)dataHolder(realId);
        cd.structThread.Abort();
      }
      catch (Exception)
      {
        lock (this)
        {
          ht.Remove(realId);
          updateDataGrid(("Disconnected User: > " + realId + " Time: " + DateTime.Now.ToLongTimeString()));
        }
      }
    }
    private ClientData dataHolder(long realId)
    {
      throw new NotImplementedException();
    }
    #endregion
    #region " Server Updating The Data Grid "
    // Update Data Grid
    public void updateDataGrid(string displayString)
    {
      txtServerConnection.AppendText((displayString)); // + ControlChars.Cr + ControlChars.Lf));
    }
    #endregion
    [BrowsableAttribute(false)]
    public static bool CheckForIllegalCrossThreadCalls { get; set; }
    private void TCPSerever_Loaded(object sender, RoutedEventArgs e)
    {
      CanvasBorder.BorderThickness = new Thickness(1);
      lblDate.Content += DateTime.Today.DayOfWeek + ", " + DateTime.Now.ToLongDateString();
      //This is a snippet to hold the control of the illegal Cross-Thread call operation
      CheckForIllegalCrossThreadCalls = false;
      //===============================================
      txtServerConnection.Text = "Wating for connection... ";
    }
    public string CurrentDateTime
    {
      get { return (string)GetValue(CurrentDateTimeProperty); }
      set { SetValue(CurrentDateTimeProperty, value); }
    }
    public static readonly DependencyProperty CurrentDateTimeProperty =
      DependencyProperty.Register("CurrentDateTime", typeof(string), typeof(TCPServer), new UIPropertyMetadata(string.Empty));
    private void UpdateCurrentDateTime()
    {
      CurrentDateTime = DateTime.Now.ToShortTimeString();
    }
    private void btnExit_Click(object sender, RoutedEventArgs e)
    {
      if ((tcpLsn != null))
      {
            tcpLsn.Stop();
        }
        //ClientData cd = default(ClientData);
      foreach (ClientData cd in ht.Values)
      {
            if (cd.structSocket.Connected)
        {
                cd.structSocket.Close();
            }
            if (cd.structThread.IsAlive)
        {
                cd.structThread.Abort();
            }
        }
        if (tcpThd.IsAlive)
      {
            tcpThd.Abort();
        }
        this.Close();
    }
  }
}





This is the code for Client class...

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
//using System.Windows.Documents;
using System.Windows.Input;
//using System.Windows.Media;
//using System.Windows.Media.Imaging;
//using System.Windows.Navigation;
//using System.Windows.Shapes;
using System.Windows.Threading;
using System.Data.Common;

namespace DtposClient
{
  /// <summary>
  /// Interaction logic for TCPClient.xaml
  /// </summary>
  public partial class TCPClient : Window
  {
    public Thread tcpThd;
    public byte[] readBuffer;
    public byte[] writeBuffer;
    public Stream stream;
    public Socket socket;
    public TcpClient tcpclnt;
    public int password;
    //===============================\\

    public OleDbConnection connection = new OleDbConnection();
    
    DataSet DtposMenuDS = new DataSet();
    OleDbCommand command = new OleDbCommand();
    OleDbDataAdapter dtadapter = new OleDbDataAdapter();
    public OleDbDataReader dataReader;
    
    private ClientLogin loginForm = new ClientLogin();

    public TCPClient()
    {
      InitializeComponent();
      connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\AP_AE\\Desktop\\DTPOS_ClientServer\\DataBase\\DtposMenu.accdb;";
      //connection = new OleDbConnection(connectionString);

      try
      {
        connection.Open();
      }
      catch (Exception ex)
      {
        MessageBox.Show("Error Masseage = " + ex.Message);
      }
      if (connection.State != ConnectionState.Open)
      {
        MessageBox.Show("Database Connection Failed to Open");
        //Application.Exit();
        this.Close();
      }
    }

    #region " Client, Start Server - (Client User is Connecting To Server) "

    public void startServer(string ipAddress, int portNumber, int password)
    {
      try
      {
        connection.Open();
        dtadapter.SelectCommand.CommandText = "SELECT * FROM Users WHERE Password = '" + password + "';";
        //string commandString = "SELECT Password FROM [Users]";
        //commandString += "WHERE(Password=@Param1)";
        //OleDbDataAdapter dtadapter = new OleDbDataAdapter();
        //DataTable myDataTable = new DataTable();
        //OleDbCommand comm = new OleDbCommand();
        dataReader = dtadapter.SelectCommand.ExecuteReader();
        //comm.Connection = connection;
        //comm.CommandType = CommandType.Text;
        //comm.CommandText = commandString;
        //comm.Parameters.Add("@Param1", OleDbType.Integer, 4).Value = txtPassword.Text;
        //dtadapter.SelectCommand = comm;
        //dtadapter.Fill(myDataTable);
        dataReader.Read();

        this.password = password;
        tcpclnt = new TcpClient();
        tcpclnt.Connect(ipAddress.Trim(), portNumber);

        txtLoginWindow.AppendText("Connecting to server... " + "\n" + "======================================== " + "\n");
        stream = tcpclnt.GetStream();
        Thread.Sleep(4000);
        txtLoginWindow.AppendText((" Hello " + dataReader["Name"].ToString() + ", " + " You have logged in as " + "'" + dataReader["Access Level"].ToString() + "'" + " Welcome to DTPOS System"));
        tcpThd = new Thread(ReadSocket);
        //tcpThd.Name = loginName
        tcpThd.Start();
        
        dataReader.Close();
      }
      catch (Exception ex)
      {
        //MessageBox.Show(ex.StackTrace);
        MessageBox.Show(ex.ToString(), "Unable to open database!");
      }
      connection.Close();

    }
    
    #endregion

    #region " Client Read Socket "

    public void ReadSocket()
    {
      while (true)
      {
        try
        {
          readBuffer = new Byte[101];
          stream.Read(readBuffer, 0, 100);

          // If the text box exceeds the maximum lenght, then get
          // remove the top part of the text
          if (txtLoginWindow.Text.Length > txtLoginWindow.MaxLength)
          {
            txtLoginWindow.Select(0, 300);
            txtLoginWindow.SelectedText = "";
          }
          txtLoginWindow.AppendText((System.Text.Encoding.ASCII.GetString(readBuffer)));
        }
        catch (Exception)
        {
          break; // TODO: might not be correct. Was : Exit While
        }
      }
    }
    
    #endregion

    #region " User Client Write To Server "

    public void writeToServer(string strn)
    {
      System.Text.ASCIIEncoding encord = new System.Text.ASCIIEncoding();
      writeBuffer = encord.GetBytes(strn);
      if ((stream != null))
      {
        stream.Write(writeBuffer, 0, writeBuffer.Length);
      }
    }
    
    #endregion

    private void menuItemStart_Click(object sender, RoutedEventArgs e)
    {
      loginForm = new ClientLogin();
      //loginForm.ShowDialog();
      loginForm.infoChecker(this);
    }

    private void menuItemExit_Click(object sender, RoutedEventArgs e)
    {
      this.Close();
    }

    private void btnLogout_Click(object sender, EventArgs e)
    {
      txtLoginWindow.AppendText(("Logging out from the server!!!"));
      Thread.Sleep(3000);
      //dataReader = new System.Data.OleDb.OleDbDataReader();
      txtLoginWindow.AppendText(("User: " + dataReader["Name"].ToString() + " as " + dataReader["Access Level"].ToString() + " Has Logged Out... "));
      this.btnLogout.IsEnabled = false;
      //writeToServer((loginName & " has logged out... "));
      if ((tcpThd != null) & tcpThd.IsAlive) 
      {
	      tcpThd.Abort();
      }
      if ((stream != null)) 
      {
	      stream.Close();
      }
      if ((tcpclnt != null))
      {
	      tcpclnt.Close();
      }
    }
  }
}


This is the code for Client Login class....

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
//using System.Windows.Documents;
using System.Windows.Input;
//using System.Windows.Media;
//using System.Windows.Media.Imaging;
//using System.Windows.Navigation;
//using System.Windows.Shapes;
using System.Windows.Threading;
using System.Data.Common;

namespace DtposClient
{
  /// <summary>
  /// Interaction logic for ClientLogin.xaml
  /// </summary>
  public partial class ClientLogin : Window
  {
    TCPClient tcpclient;// = new TCPClient();
    //==================================\\
    DataSet DtposMenuDS = new DataSet();
    
    public OleDbConnection connection = new OleDbConnection();
    
    //public TextBox txtIPaddress = new System.Windows.Controls.TextBox();
    //public TextBox txtPortNumber = new System.Windows.Controls.TextBox();
    
    public ClientLogin()
    {
      InitializeComponent();
      connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\AP_AE\\Desktop\\DTPOS_ClientServer\\DataBase\\DtposMenu.accdb;";
      //connection = new OleDbConnection(connectionString);

      /*try
      {
        connection.Open();
      }
      catch (Exception ex)
      {
        MessageBox.Show("DataBase Access Error");
        MessageBox.Show("Error Masseage = " + ex.Message);
      }
      
      if (connection.State != ConnectionState.Open)
      {
        MessageBox.Show("Database Connection Failed to Open");
        //Application.Exit();
        this.Close();
      }*/
    }

    public void infoChecker(TCPClient formOne)
    {
      this.tcpclient = formOne;
      this.ShowDialog();
    }

    private void btnLogin_Click(object sender, RoutedEventArgs e)
    {
      try
      {
        connection.Open();
        if (txtPassword.Text.Length == 0)
        {
          OleDbCommand command = new OleDbCommand();
    
          OleDbDataAdapter dtadapter = new OleDbDataAdapter();
          OleDbDataReader dataReader;
          
          dtadapter.SelectCommand.CommandText = "SELECT * FROM [Users] WHERE Password = '" + txtPassword.Text + "'";
          dataReader = dtadapter.SelectCommand.ExecuteReader();
          dataReader.Read();

          MessageBox.Show(" You have loged as: - " + dataReader["Access Level"].ToString() + " Welcome " + dataReader["Name"].ToString() + " to DTPOS System ", "Login Successful", MessageBoxButton.OK, MessageBoxImage.Information);
          UserLoginModule.UserAccessLevel = dataReader["Access Level"].ToString();
          UserLoginModule.UserName = dataReader["Name"].ToString();

          //ToDo: Error processing original source shown below
          //--^--- Unexpected pre-processor directive
          this.tcpclient.startServer(txtIpAddress.Text.ToString().Trim(), Convert.ToInt32(txtPortNumber.Text.ToString().Trim()), Convert.ToInt32(txtPassword.Text.ToString().Trim()));
          // Always call Close when done reading.
          
          dataReader.Close();
          connection.Close();
          this.Close();
          
        }
        else if (txtPassword.Text.Length < 4)
        {
          MessageBox.Show("You must enter data in order to proceed further. Please try again...", "Error: Non Data Entry", MessageBoxButton.OK, MessageBoxImage.Information);
          txtPassword.Focus();
        }

      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.StackTrace);
        MessageBox.Show(ex.ToString(), "Unable to open database!");
      }
      // Display error if unable to open database
      
      
    }

    private void btnCancel_Click(object sender, RoutedEventArgs e)
    {
      this.Close();
    }

    private void btnReset_Click(object sender, RoutedEventArgs e)
    {
      txtPassword.Clear();
      txtPassword.Focus();
    }

  }
}


This is the code for UserClient property class...

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespace DtposClient
{
  public class UserClient
  {
    // User Client Global variables
      // ====================================
    public string UserName;
    public string UserAccessLevel;
    public int UserPassword;
      public string fullName
    {
          get { return UserName; }
          set { UserName = value; }
      }
    public string accLevel
    {
      get { return UserAccessLevel; }
      set { UserAccessLevel = value; }
    }
      public int userPass
    {
      get { return UserPassword; }
      set { UserPassword = value; }
      }
      public override bool Equals(object obj)
      {
      UserClient temp = obj as UserClient;
      if (temp != null)
      {
        return (userPass == temp.userPass);
      }
      return false;
      }
    public UserClient(string fullNam, string aLevel, int pass)
      {
          fullName = fullNam;
      accLevel = aLevel;
      userPass = pass;
      }
  }
}


And finally this is a static UserLoginModule class...

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespace DtposClient
{
  static class UserLoginModule
  {
    public static ArrayList UserClientList = new ArrayList();
    public static System.Collections.Hashtable ordersMap = new Hashtable();
    // Global variables
    public static string UserName;
    public static string UserAccessLevel;
    public static int UserPassword = 0;
    public static UserClient CurrUserClient = null;
  }
}


thanks in advance

kind regards

roni
Posted
Updated 30-Jan-11 4:31am
v2
Comments
Sergey Alexandrovich Kryukov 29-Jan-11 22:26pm    
You're not even trying to report your problem. This is one of the easiest problems to resolve. Did you ever use debugger? Catch and dump exceptions? In what line of code the exception is thrown?
Abhinav S 30-Jan-11 0:12am    
Post some code here - someone might be able to help you.
Espen Harlinn 30-Jan-11 10:49am    
Run the server under the debugger, and tell the debugger to break on exception. Take a look at the call stack. This will tell you what your code was attempting to do when the exeption was thrown. When the debugger breaks - inspect the variables.

1 solution

Searching Google[^] provides a serious number of options to choose from.

Read through this[^] to get a firmer understanding of what you are asking about.

Regards
Espen Harlinn
 
Share this answer
 
Comments
LAPEC 30-Jan-11 10:03am    
Hello Espen

thanks for your reply to my question...
Do you mind if I show you the code and see where the problem is, (if possible)...

thanks in advance

kind regards
lapeci
Espen Harlinn 30-Jan-11 10:09am    
Update the question using the green "Improve Question" link, paste code into the editor and meke sure it's reasonably formatted between <pre></pre> tags as in:
<pre>
if (i > 0)
{
// do someting
}
</pre>
Sergey Alexandrovich Kryukov 31-Jan-11 16:28pm    
Espen, did you see null exception? I doesn't worth it. OP should be made to dump exception stack, show that line(s), everything else is just waste of time -- requested long ago.
--SA
Sergey Alexandrovich Kryukov 31-Jan-11 16:30pm    
Lapeci, please provide all that. As I say, the problem must be way to easy, but why any guesswork? Perhaps you still don't understand what to do?
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900