Handling errors while inside a button - c#

I have a windows form that involes filling out textboxes with information and then clicking connect. I have error messages that pops up if any of the textboxes are empty but when I hit OK the program just continues and I end up getting run-time errors because there's insufficient information, and the program crashes. What I want is for the program to go back to the point before I hit "Connect" whenever any textbox is not filled out correctly.
This is the code:
private void cmdConnect_Click(object sender, EventArgs e)
{
if (cmdConnect.Text == "Connect")
{
if (txtGroup.Text == "")
{
txtGroup.Text = "_Group01";
}
if (txtItemID.Text == "")
{
MessageBox.Show("Please enter ItemID.", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
switch (cboServer.Text)
{
case "":
MessageBox.Show("Please select and OPC server", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case "RSLinx Remote OPC Server":
if (txtMachine.Text == "")
{
MessageBox.Show("Please enter a machine name for remote connection", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
else
{
oOpcServer.Connect(cboServer.Text, txtMachine.Text);
}
break;
case "RSLinx OPC Server":
oOpcServer.Connect(cboServer.Text);
break;
default:
if (txtMachine.Text == "")
{
oOpcServer.Connect(cboServer.Text);
}
else
{
oOpcServer.Connect(cboServer.Text, txtMachine.Text);
}
break;
}
oOpcGroup = oOpcServer.OPCGroups.Add(txtGroup.Text);
oOpcGroup.IsSubscribed = true;
oOpcGroup.IsActive = false;
oOpcGroup.UpdateRate = 1000;
ClHandle = 1;
oOpcGroup.OPCItems.DefaultAccessPath = txtAccessPath.Text;
oOpcGroup.OPCItems.AddItem(txtItemID.Text, ClHandle);
cmdItemWrite.Enabled = true;
cmdItemRead.Enabled = true;
cmdSyncWrite.Enabled = true;
cmdSyncRead.Enabled = true;
cmdAsyncWrite.Enabled = true;
cmdAsyncRead.Enabled = true;
cmdAdvise.Enabled = true;
txtSubValue.Enabled = true;
cboServer.Enabled = false;
txtMachine.Enabled = false;
txtGroup.Enabled = false;
txtAccessPath.Enabled = false;
txtItemID.Enabled = false;
cmdConnect.Text = "Disconnect";
}
else
{
oOpcServer.OPCGroups.RemoveAll();
oOpcGroup = null;
oOpcServer.Disconnect();
cmdConnect.Text = "Connect";
cmdItemWrite.Enabled = false;
cmdItemRead.Enabled = false;
cmdSyncWrite.Enabled = false;
cmdSyncRead.Enabled = false;
cmdAsyncWrite.Enabled = false;
cmdAsyncRead.Enabled = false;
cmdAdvise.Enabled = false;
txtSubValue.Enabled = false;
cboServer.Enabled = true;
txtMachine.Enabled = true;
txtGroup.Enabled = true;
txtAccessPath.Enabled = true;
txtItemID.Enabled = true;
}
oOpcGroup.DataChange += new RsiOPCAuto.DIOPCGroupEvent_DataChangeEventHandler(oOpcGroup_DataChange);
}

Adding a return statment after each message box would do the trick and cause the method to exit without doing the work at end.

Simplest solution, as Dervall mentioned is adding return statements after each MessageBox.Show call. But more elegant solution is using validation and error provider to highlight incorrect input data prior to executing connect logic.
Anyway, here is some thoughts on refactoring your code.
private void cmdConnect_Click(object sender, EventArgs e)
{
if (cmdConnect.Text == "Disconnect")
{
Disconnect();
SetControlsToDisconnectedState();
return;
}
if (String.IsNullOrWhiteSpace(txtGroup.Text))
txtGroup.Text = "_Group01";
if (String.IsNullOrWhiteSpace(txtItemID.Text))
{
ShowErrorMessage("Connect Error", "Please enter ItemID.");
return;
}
if (String.IsNullOrWhiteSpace(cboServer.Text))
{
ShowErrorMessage("Connect Error", "Please select and OPC server");
return;
}
Connect(cboServer.Text, txtMachine.Text);
DoSomethingWithGroup(txtGroup.Text, txtAccessPath.Text, txtItemID.Text);
SetControlsToConnectedState();
}
What changed:
It's more readable, when you verify which text on button, then which it don't have
Method ShowErrorMessage does exactly what it says
Verify text with IsNullOrWhiteSpace because it could be full of white spaces
Control state changing moved to separate code
Connecting/Disconnecting now separated from UI
Here other methods:
private void ShowErrorMessage(string title, string message)
{
MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void SetControlsToConnectedState()
{
UpdateControls(true);
}
private void SetControlsToDisconnectedState()
{
UpdateControls(false);
}
private void UpdateControls(bool isConnected)
{
cmdConnect.Text = isConnected ? "Disconnect" : "Connect";
cmdItemWrite.Enabled = isConnected;
cmdItemRead.Enabled = isConnected;
cmdSyncWrite.Enabled = isConnected;
cmdSyncRead.Enabled = isConnected;
cmdAsyncWrite.Enabled = isConnected;
cmdAsyncRead.Enabled = isConnected;
cmdAdvise.Enabled = isConnected;
txtSubValue.Enabled = isConnected;
cboServer.Enabled = !isConnected;
txtMachine.Enabled = !isConnected;
txtGroup.Enabled = !isConnected;
txtAccessPath.Enabled = !isConnected;
txtItemID.Enabled = !isConnected;
}
private void Disconnect()
{
oOpcServer.OPCGroups.RemoveAll();
oOpcGroup = null;
oOpcServer.Disconnect();
}
private void Connect(string serverName, string machineName)
{
switch (serverName)
{
case "RSLinx Remote OPC Server":
if (String.IsNullOrWhiteSpace(machineName))
{
ShowErrorMessage("Connect Error", "Please enter a machine name for remote connection");
return;
}
oOpcServer.Connect(serverName, machineName);
break;
case "RSLinx OPC Server":
oOpcServer.Connect(serverName);
break;
default:
if (String.IsNullOrWhiteSpace(machineName))
oOpcServer.Connect(serverName);
else
oOpcServer.Connect(serverName, machineName);
break;
}
}
private void DoSomethingWithGroup(string groupName, string accessPath, string itemID)
{
oOpcGroup = oOpcServer.OPCGroups.Add(groupName);
oOpcGroup.IsSubscribed = true;
oOpcGroup.IsActive = false;
oOpcGroup.UpdateRate = 1000;
ClHandle = 1;
oOpcGroup.OPCItems.DefaultAccessPath = accessPath;
oOpcGroup.OPCItems.AddItem(itemID, ClHandle);
oOpcGroup.DataChange += new RsiOPCAuto.DIOPCGroupEvent_DataChangeEventHandler(oOpcGroup_DataChange);
}

Related

Serial Communication Port will get Closed after clicking on Close button in C#

I am working on project in C# windows form application.
In this project main Form contain subform for communication of serial port. SubForm "Connect" have two buttons Connect and Close. Also 5 comboboxes to select baudrate, Com name,parity, stopbits and databits.
When I click on Connect button after selecting all settings from comboboxes. port gets connected and connect button becomes Disconnect. And I will close the Connect form
Now my problem is that when I reopen the form, without clicking on Disconnect button when i Close the form , the Comport will disconnected. I don't want that ComPort close.
Please help me to solve this bug. I don't know where I did mistake. Thanks in advance.
Connect Class Code
public partial class Connect : Form
{
public bool Connect_Status = false;
public Connect()
{
InitializeComponent();
COM_List();
}
private void COM_List()
{
for (int i = 0; i < CommPortManager.Instance.GetCommList().Count; i++)
{
cb_CommPort.Items.Add(CommPortManager.Instance.GetCommList()[i]);
}
}
private void btn_Connect_Click(object sender, EventArgs e)
{
if (btn_Connect.Text == "Connect")
{
CommPortManager.Instance.PortName = cb_CommPort.Text;
CommPortManager.Instance.BaudRate = cb_BaudRate.Text;
CommPortManager.Instance.Parity = cb_Parity.Text;
CommPortManager.Instance.StopBits = cb_StopBits.Text;
CommPortManager.Instance.DataBits = cb_DataBits.Text;
if ((cb_CommPort.Text == "") || (cb_BaudRate.Text == "") || (cb_Parity.Text == "") || (cb_DataBits.Text == "") || (cb_StopBits.Text == ""))
{
if (cb_CommPort.Text == "")
{
MessageBox.Show("Please select COM Port and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (cb_BaudRate.Text == "")
{
MessageBox.Show("Please select BaudRate and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (cb_Parity.Text == "")
{
MessageBox.Show("Please select Parity and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (cb_DataBits.Text == "")
{
MessageBox.Show("Please select DataBits and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if(cb_StopBits.Text == "")
{
MessageBox.Show("Please select StopBits and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Connect_Status = false;
}
else
{
if (CommPortManager.Instance.COM_Open() == false)
{
MessageBox.Show("Could not open the COM port. Most likely it is already in use, has been removed, or is unavailable.", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
Connect_Status = false;
}
else
{
//CommPortManager.Instance.COM_Close();
Connect_Status = true;
btn_Connect.Text = "Disconnect";
cb_CommPort.Enabled = false;
cb_BaudRate.Enabled = false;
cb_DataBits.Enabled = false;
cb_Parity.Enabled = false;
cb_StopBits.Enabled = false;
btn_Connect.BackColor = System.Drawing.Color.Salmon;
}
}
}
else
{
CommPortManager.Instance.COM_Close();
btn_Connect.Text = "Connect";
Connect_Status = false;
cb_CommPort.Enabled = true;
cb_BaudRate.Enabled = true;
cb_DataBits.Enabled = true;
cb_Parity.Enabled = true;
cb_StopBits.Enabled = true;
btn_Connect.BackColor = System.Drawing.Color.DarkTurquoise;
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
this.Close();
}
private void Connect_Load(object sender, EventArgs e)
{
//code here to setup the value;
cb_CommPort.Text = CommPortManager.Instance.PortName;
cb_BaudRate.Text = CommPortManager.Instance.BaudRate;
cb_Parity.Text = CommPortManager.Instance.Parity;
cb_StopBits.Text = CommPortManager.Instance.StopBits;
cb_DataBits.Text = CommPortManager.Instance.DataBits;
if (CommPortManager.Instance.IsOpen == true)
{
btn_Connect.Text = "Disconnect";
btn_Connect.BackColor = System.Drawing.Color.Salmon;
cb_CommPort.Enabled = false;
cb_BaudRate.Enabled = false;
cb_DataBits.Enabled = false;
cb_Parity.Enabled = false;
cb_StopBits.Enabled = false;
}
else
{
btn_Connect.Text = "Connect";
Connect_Status = false;
cb_CommPort.Enabled = true;
cb_BaudRate.Enabled = true;
cb_DataBits.Enabled = true;
cb_Parity.Enabled = true;
cb_StopBits.Enabled = true;
btn_Connect.BackColor = System.Drawing.Color.DarkTurquoise;
}
}
}
I suspect that the form load event. you need to set the connection status true when its open
private void Connect_Load(object sender, EventArgs e)
{
//code here to setup the value;
cb_CommPort.Text = CommPortManager.Instance.PortName;
cb_BaudRate.Text = CommPortManager.Instance.BaudRate;
cb_Parity.Text = CommPortManager.Instance.Parity;
cb_StopBits.Text = CommPortManager.Instance.StopBits;
cb_DataBits.Text = CommPortManager.Instance.DataBits;
if (CommPortManager.Instance.IsOpen == true)
{
Connect_Status = true;
btn_Connect.Text = "Disconnect";
btn_Connect.BackColor = System.Drawing.Color.Salmon;
cb_CommPort.Enabled = false;
cb_BaudRate.Enabled = false;
cb_DataBits.Enabled = false;
cb_Parity.Enabled = false;
cb_StopBits.Enabled = false;
}
else
{
btn_Connect.Text = "Connect";
Connect_Status = false;
cb_CommPort.Enabled = true;
cb_BaudRate.Enabled = true;
cb_DataBits.Enabled = true;
cb_Parity.Enabled = true;
cb_StopBits.Enabled = true;
btn_Connect.BackColor = System.Drawing.Color.DarkTurquoise;
}
}
It looks like that if you press Connect it changes your btn_Connect.Text to
Disconnect (if the port is open)
now the button text is "Disconnect" and if (btn_Connect.Text == "Connect") is now false and the else is called which does CommPortManager.Instance.COM_Close();

How to call Code Behind from server side

I have a checkbox with event like this:
protected void cbRating1WithoutExceptionP1_CheckedChanged(object sender, EventArgs e)
{
if (cbRating1WithoutExceptionP1.Checked == true)
{
cbRating1WithExceptionP1.Checked = false;
cbRating1WithExceptionP1.Enabled = false;
}
else
{
cbRating1WithExceptionP1.Enabled = true;
}
}
How to call that event from server side?
foreach (string oWithException in oWithExceptions)
{
switch (oWithException.Trim())
{
case "P1":
cbRating2WithExceptionP1.Checked = true;
cbRating1WithoutExceptionP1_CheckedChanged(new object, new EventArgs);
break;
case "P2":
cbRating2WithExceptionP2.Checked = true;
break;
case "P3":
cbRating2WithExceptionP3.Checked = true;
break;
case "P4":
cbRating2WithExceptionP4.Checked = true;
break;
case "P5":
cbRating2WithExceptionP5.Checked = true;
break;
case "NOT_ALLOWED":
cbRating2WithExceptionNotAllowed.Checked = true;
cbRating2WithExceptionP1.Checked = false;
cbRating2WithExceptionP1.Enabled = false;
cbRating2WithExceptionP2.Checked = false;
cbRating2WithExceptionP2.Enabled = false;
cbRating2WithExceptionP3.Checked = false;
cbRating2WithExceptionP3.Enabled = false;
cbRating2WithExceptionP4.Checked = false;
cbRating2WithExceptionP4.Enabled = false;
cbRating2WithExceptionP5.Checked = false;
cbRating2WithExceptionP5.Enabled = false;
break;
}
}
}
Like this:
cbRating1WithoutExceptionP1_CheckedChanged(new object, new EventArgs);
Is that possible to call the event from server side without create a function?
You Like This if You wants to Only Call Your method:
cbRating1WithoutExceptionP1_CheckedChanged(null, EventArgs.Empty);

Serializing Aysnchronous SQLCommand

I have the code below which works fine when the Session state is InProc. However when the Session state is Sql Server, HandleCallback never gets called. How do I change the code so HandleCallBack gets called?
private void TAdata(object sender, EventArgs e)
{
if (((Form)sender).DialogResult == DialogResult.No)
{
return;
}
if (Changed)
{
MessageBox.Show(this.ParentForm, "Save Payroll Changes First", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
SqlConnection dbconnAS = new SqlConnection(strDBconnAS);
{
try
{
AsyncCallback callback = new AsyncCallback(HandleCallback);
using (SqlCommand SQLcmd = new SqlCommand("dbo.KronosTaData", dbconnAS))
{
SQLcmd.CommandType = CommandType.StoredProcedure;
dbconnAS.Open();
Changed = true;
SQLcmd.BeginExecuteNonQuery(callback, SQLcmd);
strResult = "";
ExportProgress.Visible = true;
ExportProgress.Value = 0;
ExportProgress.Maximum = 120;
ExportTimer.Start();
}
}
catch (Exception ex)
{
Changed = false;
strResult = ex.Message;
if (dbconnAS != null)
{
dbconnAS.Close();
}
}
}
}
}
private void HandleCallback(IAsyncResult result)
{
try
{
using (SqlCommand SQLcmd = (SqlCommand)result.AsyncState)
{
int rowCount = SQLcmd.EndExecuteNonQuery(result);
strResult = "OK";
SQLcmd.Connection.Close();
}
}
catch (Exception ex)
{
strResult = ex.Message;
}
}
private void ExportTimer_Tick(object sender, EventArgs e)
{
//Timer Exists on UI thread
if (strResult == "")
{
if (cmdKronos.Enabled) cmdKronos.Enabled = false;
if (ExportProgress.Value > ExportProgress.Maximum - 10) ExportProgress.Maximum += 10;
ExportProgress.Value += 1;
}
else if (strResult == "OK")
{
Changed = false;
cmdKronos.Enabled = true;
ExportProgress.Visible = false;
ExportTimer.Stop();
MessageBox.Show(ParentForm, "Kronos data succesfully imported", "Data Import", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
Changed = false;
cmdKronos.Enabled = true;
ExportProgress.Visible = false;
ExportTimer.Stop();
MessageBox.Show(ParentForm, Text, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
You are disposing the command as soon as you've finished starting it:
using (SqlCommand SQLcmd = new SqlCommand("dbo.KronosTaData", dbconnAS))
{
//...
SQLcmd.BeginExecuteNonQuery(callback, SQLcmd);
//...
}
that will abort everything - so indeed: it will never complete. Basically; using doesn't play nicely with Begin*/End*, so don't do that. You might find it much easier to do this using async/await, by the way (via ExecuteNonQueryAsync).
You also probably want to close and dispose the connection somewhere; again, async/await would make this much easier to get right.
The solution is to declare the variable strResult as static.
See Visual Webgui Variable Scope

App Crashes Every Time on an unsuccessfull ping C#

I was developing my first app called Minecraft Wiglet. It pings important minecraft sites and it can start in starup. When I am testing my app it succesfully pinged sites while
I was online but when I was offline the app crashed at the fourth line it said "unhandled pingExpection" I am new in coding so go easy on me :)
private void button1_Click(object sender, EventArgs e)
{
Ping ping = new Ping();
PingReply pingresult = ping.Send("minecraftturk.com"); //Crashed here
if (pingresult.Status.ToString() == "Success")
{
label5.Text = "Online";
}
else if (pingresult.Status.ToString() == "Failure")
{
label5.Text = "Offline";
}
Ping ping1 = new Ping();
PingReply pingresult1 = ping.Send("minecraft.net");
if (pingresult.Status.ToString() == "Success")
{
label3.Text = "Online";
}
else if (pingresult.Status.ToString() == "Failure")
{
label3.Text = "Offline";
}
Ping ping2 = new Ping();
PingReply pingresult2 = ping.Send("www.planetminecraft.com");
if (pingresult.Status.ToString() == "Success")
{
label10.Text = "Online";
}
else if (pingresult.Status.ToString() == "Failure")
{
label10.Text = "Offline";
}
MessageBox.Show("Durum başarıyla güncellendi.");
}
You need to catch and handle your exceptions. I'd recommend wrapping your pinging into another method like this:
private bool CanPing(string url)
{
try
{
return new Ping().Send(url).Status == IPStatus.Success;
}
catch (PingException)
{
return false;
}
}
Then you can call CanPing for each site and it will return true or false while handling the case where the user is offline in just one line, like so:
private void button1_Click(object sender, EventArgs e)
{
label10.Text = CanPing("www.planetminecraft.com") ? "Online" : "Offline";
// ...
}
You could further encapsulate the above into another method, but that might be overkill.

Progressbar Thread doesn't abort after execution, application crashing -WPF

I am trying to show progressbar when user is trying to login into system. Durin the operation I am showing the progressbar window to the user. I did this using a backgroundworker and it works. But sometime the system crashes. It seems windows 8 is creating the problem. Because it's running in Windows 7 without any error.Here is my loadingview.xaml.cs code which contains the progressbar related code
public partial class LoadingViewControl : Window
{
System.ComponentModel.BackgroundWorker mWorker;
public LoadingViewControl()
{
InitializeComponent();
Load();
}
public LoadingViewControl(bool Close)
{
this.Close();
}
public void Load()
{
mWorker = new System.ComponentModel.BackgroundWorker();
mWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(worker_DoWork);
mWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(worker_ProgressChanged);
mWorker.WorkerReportsProgress = true;
mWorker.WorkerSupportsCancellation = true;
mWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
mWorker.RunWorkerAsync();
while (pbProcessing.Value < 99)
{
if (!mWorker.CancellationPending)
{
try
{
if (pbProcessing.Value > 95)
{
mWorker.CancelAsync();
//Uri uri = new Uri("/View/LoginchildView.xaml", UriKind.Relative);
break;
}
else
{
pbProcessing.Value = (pbProcessing.Value + 0.005) % 100;
}
}
catch (System.Exception ex)
{
// No action required
}
}
else
{
break;
}
System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background,
new System.Threading.ThreadStart(delegate { }));
}
}
private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
// Do your work here, its on seperate thread
}
private void worker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
pbProcessing.Value = e.ProgressPercentage;
}
private void worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
// Stop Progressbar updatation
}
private void LoadingViewControl_Load(object sender, EventArgs e)
{
SetFocus();
}
public void SetFocus()
{
this.Focus();
this.Activate();
}
}
Now I am showing you my Loginviewform.xaml.cs code which implements the progressbar.
if (txtUserName.Text != "")
{
if (txtPassword.Password != "")
{
if (STAThread == null)
{
STAThread = new Thread(() => { new LoadingViewControl().ShowDialog(); });
STAThread.SetApartmentState(ApartmentState.STA);
STAThread.IsBackground = true;
STAThread.Start();
}
else
{
STAThread.SetApartmentState(ApartmentState.STA);
STAThread.IsBackground = true;
STAThread.Start();
}
result = User.Instance.Authenticicate(txtUserName.Text, txtPassword.Password);
if (result == true)
{
pbProcessing.Value = 100;
ServiceLocator.Current.GetInstance<ContainerViewModel>().ExecuteLobbyBasicViewCommand();
//redirect on specific page.
if (STAThread.IsAlive)
{
Thread.CurrentThread.Interrupt();
STAThread.Interrupt();
STAThread.Abort();
STAThread = null;
}
PopUp objpopup = new PopUp();
objpopup.txtNotice.Text = "sign in";
objpopup.txtMessage.Text = "successfully sign in.";
objpopup.ShowDialog();
Global.GetUserName = txtUserName.Text;
}
else
{
//MessageBox.Show("Sign In was unsuccessful. Please correct the errors and try again.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
STAThread.Abort();
STAThread = null;
PopUp objPopUp = new PopUp();
objPopUp.txtNotice.Text = "Error";
objPopUp.txtMessage.Text = "Sign In was unsuccessful. Please correct the errors and try again.";
objPopUp.ShowDialog();
txtUserName.Focus();
//pbProcessing.Value = 0;
stackpanelLoading.Visibility = System.Windows.Visibility.Hidden;
}
}
else
{
//MessageBox.Show("Please enter the valid Password.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
PopUp objPopUp = new PopUp();
objPopUp.txtNotice.Text = "Error";
objPopUp.txtMessage.Text = "Please enter the valid Password.";
objPopUp.ShowDialog();
txtPassword.Focus();
stackpanelLoading.Visibility = System.Windows.Visibility.Hidden;
}
}
else
{
//MessageBox.Show("Please enter the valid Player ID.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
PopUp objPopUp = new PopUp();
objPopUp.txtNotice.Text = "Error";
objPopUp.txtMessage.Text = "Please enter the valid Player ID.";
objPopUp.ShowDialog();
txtUserName.Focus();
stackpanelLoading.Visibility = System.Windows.Visibility.Hidden;
}
Any idea what is going wrong? Any help would be appreciated.Thanks
It's very strange code. Try refactor it like this:
public partial class LoadingViewControl : Window
{
public LoadingViewControl(string userName, string password)
{
InitializeComponent();
Initialize(userName, password);
}
private void Initialize(string userName, string password)
{
pbProcessing.IsIndeterminate = true;
var thread = new Thread(() =>
{
DialogResult = User.Instance.Authenticicate(userName, password);
Close();
});
thread.IsBackground = true;
thread.Start();
}
}
And some method :
public void Do()
{
if (string.IsNullOrEmpty(txtUserName.Text))
{
if (string.IsNullOrEmpty(txtPassword.Password))
{
var view = new LoadingViewControl(txtUserName.Text, txtPassword.Password);
result = view.ShowDialog();
if (result == true)
{
ServiceLocator.Current.GetInstance<ContainerViewModel>().ExecuteLobbyBasicViewCommand();
PopUp objpopup = new PopUp();
objpopup.txtNotice.Text = "sign in";
objpopup.txtMessage.Text = "successfully sign in.";
objpopup.ShowDialog();
Global.GetUserName = txtUserName.Text;
}
else
{
//MessageBox.Show("Sign In was unsuccessful. Please correct the errors and try again.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
PopUp objPopUp = new PopUp();
objPopUp.txtNotice.Text = "Error";
objPopUp.txtMessage.Text = "Sign In was unsuccessful. Please correct the errors and try again.";
objPopUp.ShowDialog();
txtUserName.Focus();
stackpanelLoading.Visibility = Visibility.Hidden;
}
}
else
{
PopUp objPopUp = new PopUp();
objPopUp.txtNotice.Text = "Error";
objPopUp.txtMessage.Text = "Please enter the valid Password.";
objPopUp.ShowDialog();
txtPassword.Focus();
stackpanelLoading.Visibility = Visibility.Hidden;
}
}
else
{
PopUp objPopUp = new PopUp();
objPopUp.txtNotice.Text = "Error";
objPopUp.txtMessage.Text = "Please enter the valid Player ID.";
objPopUp.ShowDialog();
txtUserName.Focus();
stackpanelLoading.Visibility = Visibility.Hidden;
}
}
That's method looks ugly and you must refactor it to. But i just want to show main idea

Categories

Resources