Thread was being aborted when we use - c#

I'm getting the following exception:
System.Threading.ThreadAbortException: Thread was being aborted.
at System.Threading.Thread.AbortInternal() at
System.Threading.Thread.Abort(Object stateInfo) at
System.Web.HttpResponse.End() at
System.Web.HttpResponse.Redirect(String url, Boolean endResponse)
at System.Web.HttpResponse.Redirect(String url) at
taxi_selection.lnkbtnconfirm_Click(Object sender, EventArgs e)
I found that the solution for this is to use:
Response.Redirect("home.aspx",false);
but again this error is occurring.
What is a good solution for this?
my code snippets :
try
{
Decimal Amount = 0;
Int64 CabId = 0;
String CabName = "";
String CarImage = "";
foreach (DataListItem gr in dtlstcars.Items)
{
RadioButton objcheck = (RadioButton)gr.FindControl("rdbtncarchecked");
if (objcheck.Checked == true)
{
Literal ltrid = new Literal();
ltrid = (Literal)gr.FindControl("ltrid");
Label lbtaxiname = (Label)gr.FindControl("lbtaxiname");
Label lbonewaycarprice = (Label)gr.FindControl("lbonewaycarprice");
Label lbtwowaycarprice = (Label)gr.FindControl("lbtwowaycarprice");
Image imgcar = (Image)gr.FindControl("imgcar");
if (ltrid != null && lbtaxiname != null && imgcar != null && lbonewaycarprice != null && lbtwowaycarprice != null)
{
if (lbrootype.Text == "One")
{
Amount = Convert.ToDecimal(lbonewaycarprice.Text);
}
else
{
Amount = Convert.ToDecimal(lbtwowaycarprice.Text);
}
}
CabId = Convert.ToInt64(ltrid.Text);
CabName = lbtaxiname.Text;
CarImage = imgcar.ImageUrl;
}
}
if (lbroottype.Text != String.Empty && lbrouteid.Text != String.Empty && lbfrom.Text != String.Empty && lbpickupdate.Text != String.Empty && lbto.Text != String.Empty && lbpickupdate.Text != String.Empty && lbpickuptime.Text != String.Empty)
{
Session.Add("BookingDetail", BookingDetail(lbroottype.Text, Convert.ToInt64(lbrouteid.Text), lbfrom.Text, lbto.Text, Convert.ToDateTime(lbpickupdate.Text), lbpickuptime.Text, Convert.ToDateTime(lbreturndate.Text), String.Empty, CabId, CabName, CarImage, Amount, txtPickupaddress.Text, txtDropaddress.Text, txtlandmark.Text, txtname.Text, ddmobilestdcode.SelectedValue, txtmobileno.Text, ddalternatestdcode.SelectedValue, txtalternateno.Text, txtemail.Text, lbdays.Text));//3
Session.Remove("cart");
Session.Remove("editcart");
Response.Redirect("confirm");
}
else
{
Response.Redirect("home");
}
}
catch (Exception ext)
{
String msg = ext.Message;
da.InsertRecordWithQuery("insert error_tbl values('" + msg + "')");
}

http://support.microsoft.com/kb/312629
as you can see here the problem is that you are attempting to use response.redirect in a try/catch block. It thrown an exception.
Your solution of changing the call to be Response.Redirect(url, false) should work. You need to make sure to do it on every Response.Redirect call.
Also note that this will continue execution, so you will have to handle that (prevent it from continuing in some other way).

This is the way the Redirect works when you do not let the rest of the page continue to run. Its stop the thread and throw that abort exception. You can simple ignore it as:
try
{
Response.Redirect("newpage.aspx", true);
}
catch (System.Threading.ThreadAbortException)
{
// ignore it
}
catch (Exception x)
{
}
Attention
If you call the redirect with out stopping the rest of the processing, a hack that can stop the redirect process using a plugin like the NoRedirect can see your rest of the page .!
To prove my point here I make a question about : Redirect to a page with endResponse to true VS CompleteRequest and security thread

Response.Redirect without specifying the endResponse parameter as false (default is true) will call Response.End() internally and therefore will trigger a ThreadAbortException to stop execution.
One of two things are recommended here:
If you need to end the response, do not do it in a try/catch. This will cause the redirect to fail.
If you do not need to end the response, call this instead:
Response.Redirect(url, false);
Within try/catch:
try {
// do something that can throw an exception
Response.Redirect(url, false);
HttpContext.Current.ApplicationInstance.CompleteRequest();
} catch (SomeSpecificException ex) {
// Do something with the caught exception
}
To avoid postback handling and HTML rendering, you need to do more:
http://web.archive.org/web/20101224113858/http://www.c6software.com/codesolutions/dotnet/threadabortexception.aspx

Related

Why is this display alert not working? it worked fine when i tried it in a button Clicked event, but its not working in a Function

1 ) Its a weather Api and i want it to display no internet connection when there is no internet connected to the device.
public async void method()
{
Indicator.IsRunning = true;
Weather weather = await GetWeather(nameplace.Text);
if (weather != null)
{
if (weather.message == "city not found")
{
txtLocation.Text = "city not found";
}
else
{
Location.Text = weather.Title;
Temperature.Text = weather.Temperature;
Temperature.Text += "°";
txtWind.Text = weather.Wind;
Humidity.Text = weather.Humidity;
Sunrise.Text = weather.Sunrise;
Sunset.Text = weather.Sunset;
double condition = Convert.ToDouble(weather.Condition);
if (condition >= 0 && condition < 30)
{
Condition.Text = "Clear Sky";
}
else if (condition >= 30)
{
Condition.Text = "Cloudy";
}
}
}
else
{
await DisplayAlert("Alert", "Sorry ! No internet connection","Ok")`
}
}
3) // Below in a getservice function i have
if (Plugin.Connectivity.CrossConnectivity.Current.IsConnected)
{
var response = await client.GetAsync(QueryString);
// pQueryString is the http request
_httpStatusCode = response.StatusCode.ToString();
if (response == null)
{
return "Sorry! No record Found.";
}
else if (response != null)
{
string json = response.Content.ReadAsStringAsync().Result;
data = JsonConvert.DeserializeObject(json);
}
}
else
{
data = null;
}
return data;
4) i have return null and put a condition in there so that it can display an alert saying no internet connection
It is possible that your async void method messes with the Thread context, and that you end up not calling your code in the ui thread.
You could try this:
Xamarin.Forms.Device.BeginInvokeOnMainThread(
() => DisplayAlert("Alert", "Sorry ! No internet connection","Ok"));
Also it's a bad design to put UI code in your service layer.
Your should call your DisplayAlert code in your ViewModel not in your service.

Try and catch block is not catching format exception

I am trying to catch format exception but the program stops on try block and never reaches to catch block, what is the problem with the code
please help me?
private void txtBags_TextChanged(object sender, EventArgs e)
{
if (txtBags.Text != "" && PackingBox.Text != "")
{
try
{
txtQty.Text = ((Convert.ToDecimal(txtBags.Text)) *
(Convert.ToDecimal(PackingBox.Text)) / 100).ToString();
}
catch (FormatException eX)
{
MessageBox.Show(eX.Message);
}
}
else
{
txtQty.Text = "";
}
}
I want to catch the exception and show the message to the user?
please tell me how can I do that?
Why handle the exception at all? Why not just avoid it altogether by using TryParse?:
if (!string.IsNullOrEmpy(txtBags.Text) && !string.IsNullOrEmpty(PackingBox.Text))
{
if (!Decimal.TryParse(txtBags.Text, out var bags))
{
// handle parse failure
return;
}
if (!Decimal.TryParse(PackingBox.Text, out var packingBox))
{
// handle parse failure
return;
}
txtQty.Text = (bags * packingBox / 100).ToString();
}
If you're not building with Roslyn/are using an older version of C#, you might need to define the variable beforehand:
decimal bags;
if (!Decimal.TryParse(txtBags.Text, out bags))
And then the same with PackingBox, of course.

c# hidden input not populating on page load when failed

Very odd one this - when i run some code on page_load and it fails, i want to populate a hidden text box with a value. The code fires and steps through in debug but the value still turns out blank. The code runs fine and hits this:
if (strResults[0] != "Success") {
fail.Value = "Failed";
}
so fail's value should say "Failed" if the submit was a failure (Success if it worked) but it doesn't.
Here' the code (edited)
try {
if (Request.QueryString["bla"] != null) {
if (Request.QueryString["blabla"] == "yes")
}
if (Request.QueryString["blablablabla"] != null) {
if (Request.QueryString["bla"] == "yes") {
string strResponse = "";
try {
if ());
if (intTransactionCodeAlreadyExists > 0) {
} else {
//do stuff
);
string[] strResults = strResponse.Split('|');
if (strResults[0] != "Success") {
fail.Value = "Failed";
}
}
}
} catch (Exception ex) {
//do stuff
}
}
}
} catch (Exception ex) {
//do stuff
}
This was a bit messed up in my setup. After a re-install of visual studio, the code started working as expected. Not 100% sure what the issue was here but all fixed. Thanks for the help.

Why is my label field is giving me an error in this c# code

Im kinda new to c# so if somebody please tell me why im getting an error
private void button2_Click(object sender, EventArgs e)
{
lblTaskManager.Text = null;
RegistryKey objRegistryKey = Registry.CurrentUser.CreateSubKey(
#"Software\Microsoft\Windows\CurrentVersion\Policies\System");
try
{
if (objRegistryKey.GetValue("DisableTaskMgr") == null)
objRegistryKey.SetValue("DisableTaskMgr", "1");
lblTaskManager.Text = ("Disabled");
else
objRegistryKey.DeleteValue("DisableTaskMgr");
objRegistryKey.Close();
lblTaskManager.Text = ("Enabled");
}
catch
{ }
}
}
}
The error is at ("Disabled"); it suggests that a } is required but adding that does not change anything. And also how can I avoid this error in the future.
Use { } correct with if:
if (objRegistryKey.GetValue("DisableTaskMgr") == null)
{
objRegistryKey.SetValue("DisableTaskMgr", "1");
lblTaskManager.Text = ("Disabled");
}
else
{
objRegistryKey.DeleteValue("DisableTaskMgr");
objRegistryKey.Close();
lblTaskManager.Text = ("Enabled");
}
The ( ) are not needed but shouldn´t harm your code.
And maybe you should move the objRegistryKey.Close(); to the finally of the try catch.
Well,
Put RegistryKey creation into using and drop explict Close().
Add {} after if and else.
Remove () around the strings assigned.
Drop that nightmare try { ... } catch {} (ignore all exceptions thrown) and never ever use such code again.
Something like this:
using (RegistryKey objRegistryKey = Registry.CurrentUser.CreateSubKey(
"#Software\Microsoft\Windows\CurrentVersion\Policies\System")) {
if (objRegistryKey.GetValue("DisableTaskMgr") == null) {
objRegistryKey.SetValue("DisableTaskMgr", "1");
lblTaskManager.Text = "Disabled";
}
else {
objRegistryKey.DeleteValue("DisableTaskMgr");
lblTaskManager.Text = "Enabled";
}
}

global.asax Application_Error reporting on original page

I think I know the answer, but is it possible to have the global.asax Application_Error event modify a textbox on the original page and not move the client to a different page? something like:
Exception exp = Server.GetLastError().GetBaseException();
System.Data.SqlClient.SqlException sqlex;
if (exp is System.Data.SqlClient.SqlException) {
sqlex = (System.Data.SqlClient.SqlException) exp;
if (sqlex.Number == 50000) {
if (HttpContext.Current.CurrentHandler is Page) {
Page p = (Page) HttpContext.Current.CurrentHandler;
Control c = p.FindControl("ErrorText");
if (c != null && c is Label) {
((Label) c).Text = exp.Message;
Server.ClearError();
return;
}
}
}
}
If you want to do this then you should use the "OnError" event of the page itself.

Categories