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
{
public struct ClientData
{
public Socket structSocket;
public Thread structThread;
}
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";
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 "
public void WaitingForClient()
{
ClientData CData = default(ClientData);
while (true)
{
CData.structSocket = tcpLsn.AcceptSocket();
Interlocked.Increment(ref connectId);
CData.structThread = new Thread(ReadSocket);
lock (this)
{
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 "
public void ReadSocket()
{
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
{
ret = s.Receive(receive, receive.Length, 0);
if (ret > 0)
{
foreach (ClientData clntData in ht.Values)
{
if (clntData.structSocket.Connected)
{
clntData.structSocket.Send(receive, ret, SocketFlags.None);
}
}
}
else
{
break;
}
}
catch (Exception e)
{
updateDataGrid(e.ToString());
if (!s.Connected)
{
break;
}
}
}
}
CloseTheThread(realId);
}
#endregion
#region " Server Closing 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 "
public void updateDataGrid(string displayString)
{
txtServerConnection.AppendText((displayString));
}
#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();
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();
}
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.Input;
using System.Windows.Threading;
using System.Data.Common;
namespace DtposClient
{
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;";
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("Error Masseage = " + ex.Message);
}
if (connection.State != ConnectionState.Open)
{
MessageBox.Show("Database Connection Failed to Open");
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 + "';";
dataReader = dtadapter.SelectCommand.ExecuteReader();
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.Start();
dataReader.Close();
}
catch (Exception ex)
{
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 (txtLoginWindow.Text.Length > txtLoginWindow.MaxLength)
{
txtLoginWindow.Select(0, 300);
txtLoginWindow.SelectedText = "";
}
txtLoginWindow.AppendText((System.Text.Encoding.ASCII.GetString(readBuffer)));
}
catch (Exception)
{
break;
}
}
}
#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.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);
txtLoginWindow.AppendText(("User: " + dataReader["Name"].ToString() + " as " + dataReader["Access Level"].ToString() + " Has Logged Out... "));
this.btnLogout.IsEnabled = false;
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.Input;
using System.Windows.Threading;
using System.Data.Common;
namespace DtposClient
{
public partial class ClientLogin : Window
{
TCPClient tcpclient;
DataSet DtposMenuDS = new DataSet();
public OleDbConnection connection = new OleDbConnection();
public ClientLogin()
{
InitializeComponent();
connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\AP_AE\\Desktop\\DTPOS_ClientServer\\DataBase\\DtposMenu.accdb;";
}
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();
this.tcpclient.startServer(txtIpAddress.Text.ToString().Trim(), Convert.ToInt32(txtPortNumber.Text.ToString().Trim()), Convert.ToInt32(txtPassword.Text.ToString().Trim()));
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!");
}
}
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
{
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();
public static string UserName;
public static string UserAccessLevel;
public static int UserPassword = 0;
public static UserClient CurrUserClient = null;
}
}
thanks in advance
kind regards
roni