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.
Related
I have this code working as is but no matter what I try, if you enter an invalid address I get a PingException and the program crashes. What is the best way to capture the exception and just update the textblock to "Device not found"?
private void actionPing_Click(object sender, RoutedEventArgs e)
{
Ping myPing = new Ping();
PingReply reply = myPing.Send(HostNameTyped.Text.ToString(), 1000);
if (reply != null)
{
string tripTime = reply.RoundtripTime.ToString();
if (tripTime == "0")
{
PingStatus1.Text = "Device not found";
}
else
{
PingStatus1.Text = "Ping Successful, " + reply.RoundtripTime.ToString() + "ms roundtrip";
}
}
https://learn.microsoft.com/en-sg/dotnet/csharp/language-reference/keywords/try-catch
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send(HostNameTyped.Text.ToString(), 1000);
if (reply != null)
{
string tripTime = reply.RoundtripTime.ToString();
if (tripTime == "0")
{
PingStatus1.Text = "Device not found";
}
else
{
PingStatus1.Text = "Ping Successful, " + reply.RoundtripTime.ToString() + "ms roundtrip";
}
}
}
catch
{
PingStatus1.Text = "Device not found";
}
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
On my windows phone 7 Mango app I use the Microsoft.Live and Microsoft.Live.Controls references to download and upload on Skydrive. Logging in and uploading files works fine but whenever I call the "client.GetAsync("/me/skydrive/files");" on the LiveConnectClient the Callback result is empty just containing the error: "An error occurred while retrieving the resource. Try again later."
I try to retrieve the list of files with this method.
This error suddenly occured without any change on the source code of the app (I think..) which worked perfectly fine for quite a while until recently. At least I didn't change the code section for up- or downloading.
I tried out the "two-step verification" of Skydrive, still the same: can log in but not download.
Also updating the Live refercences to 5.5 didn't change anything.
Here is the code I use. The error occurs in the "getDir_Callback" in the "e" variable.
Scopes (wl.skydrive wl.skydrive_update) and clientId are specified in the SignInButton which triggers "btnSignin_SessionChanged".
private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
processing = true;
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(UploadCompleted);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
client.DownloadProgressChanged += new EventHandler<LiveDownloadProgressChangedEventArgs>(client_DownloadProgressChanged);
infoTextBlock.Text = "Signed in. Retrieving file IDs...";
client.GetAsync("me");
}
else
{
connected = false;
infoTextBlock.Text = "Not signed into Skydrive.";
client = null;
}
}
private void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
if (e.Error == null)
{
client.GetCompleted -= new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetCompleted += getDir_Callback;
client.GetAsync("/me/skydrive/files");
client_id = (string)e.Result["id"];
if (e.Result.ContainsKey("first_name") && e.Result.ContainsKey("last_name"))
{
if (e.Result["first_name"] != null && e.Result["last_name"] != null)
{
infoTextBlock.Text = "Hello, " +
e.Result["first_name"].ToString() + " " +
e.Result["last_name"].ToString() + "!";
}
}
else
{
infoTextBlock.Text = "Hello, signed-in user!";
}
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
processing = false;
}
public void getDir_Callback(object s, LiveOperationCompletedEventArgs e)
{
client.GetCompleted -= getDir_Callback;
//filling Dictionary with IDs of every file on SkyDrive
if (e.Result != null)
ParseDir(e);
if (!String.IsNullOrEmpty(e.Error.Message))
infoTextBlock.Text = e.Error.Message;
else
infoTextBlock.Text = "File-IDs loaded";
}
Yo shall use client.GetAsync("me/SkyDrive/files", null) in place of client.GetAsync("me");
This is my code and it works fine.
private void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
try
{
if (e.Session != null && e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_GetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_UploadCompleted);
client.GetAsync("me/SkyDrive/files", null);
client.DownloadAsync("me/SkyDrive", null);
canUpload = true;
ls = e.Session;
}
else
{
if (client != null)
{
MessageBox.Show("Signed out successfully!");
client.GetCompleted -= client_GetCompleted;
client.UploadCompleted -= client_UploadCompleted;
canUpload = false;
}
else
{
canUpload = false;
}
client = null;
canUpload = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void client_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
try
{
List<System.Object> listItems = new List<object>();
if (e.Result != null)
{
listItems = e.Result["data"] as List<object>;
for (int x = 0; x < listItems.Count(); x++)
{
Dictionary<string, object> file1 = listItems[x] as Dictionary<string, object>;
string fileName = file1["name"].ToString();
if (fileName == lstmeasu[0].Title)
{
folderID = file1["id"].ToString();
folderAlredyPresent = true;
}
}
}
}
catch (Exception)
{
MessageBox.Show("An error occured in getting skydrive folders, please try again later.");
}
}
It miraculously works again without me changing any code. It seems to be resolved on the other end. I have no clue what was wrong.
I've created a simple tool that can find Sign up option in websites (200 website list is in arraylist).
I was using webbrowser but it has a problem of cache and cookie so i switched to webclient. It works fine when i put breakpoints and debug but when i run it normally, it also include those websites which doesn't have signup option.
Here is my code
private void btnSearch_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
}
Timer1 code
string st;
private void timer1_Tick(object sender, EventArgs e)
{
st = "";
Application.DoEvents();
try
{
st = lst[dataindex2].ToString();
using (WebClient asyncWebRequest = new WebClient())
{
asyncWebRequest.DownloadDataCompleted += asyncWebRequest_DownloadDataCompleted;
Uri urlToRequest = new Uri(st);
asyncWebRequest.DownloadDataAsync(urlToRequest);
asyncWebRequest.Dispose();
}
dataindex2++;
if (dataindex2 == lst.Count)
{
timer1.Stop();
lblStatus.Text = "Stopped";
lblStatus.ForeColor = Color.DarkRed;
MessageBox.Show("Search Completed");
}
}
catch (Exception ex)
{
timer1.Stop();
lblStatus.Text = "Stopped";
lblStatus.ForeColor = Color.DarkRed;
timer1.Dispose();
MessageBox.Show(ex.Message);
return;
}
asyncWebRequest_DownloadDataCompleted code:
private void asyncWebRequest_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (e.Error != null)
{
timer1.Stop();
ena();
lblStatus.Text = "Stopped";
lblStatus.ForeColor = Color.DarkRed;
timer1.Dispose();
MessageBox.Show(e.Error.Message);
}
if (e.Result != null && e.Result.Length > 0)
{
string browsetext = "";
int = iSuccess = 0;
browsetext = Encoding.Default.GetString(e.Result);
iSuccess = browsetext.IndexOf("Sign up") + 1;
if (iSuccess == 0)
{
}
else
{
listBox1.Items.Add(st);
domaincount++;
lblDomainCount.ForeColor = Color.DarkGreen;
lblDomainCount.Text = domaincount.ToString();
}
}
else
{
}
}
}
else
{
MessageBox.Show("No data found.");
}
}
Please help and if there is any alternate of webclient that doesn't hang gui then please suggest. ty.
You dispose WebClient as soon as you start the download.
asyncWebRequest.DownloadDataAsync(urlToRequest);
asyncWebRequest.Dispose();
Please help and if there is any alternate of webclient that doesn't hang gui
see my other answer which creates a wrapper for WebClient to be able to use async/await. HttpClient can be an alternative too.
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);
}