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.
Related
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.
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";
}
}
I have a recursive function in a windows service. This function upon completion rewinds itself as it has been repeated multiple times in recursion. Isn't that an overhead ?
Is there any way to avoid unwinding ? Is there any better approach?
Edit : In this method, I get 100 records from DB and then process them and then get another 100 and so on till all the records in DB have been processed.
Also, there is no limit of how many total records there might be in the db so this function can repeat itself quite a lot.
public void ServiceFunctionality()
{
try
{
// Get Data From WEBAPI
HttpClient client = new HttpClient();
HttpResponseMessage response = response = client.GetAsync("webapi url link").Result;
Response<ServiceWrapper> objResponse = response.Content.ReadAsAsync<Response<ServiceWrapper>>().Result;
if (objResponse != null)
{
if (objResponse.isSuccess == true)
{
listContact = objResponse.data.lContact;
int MaxPKinSelectedRecords = objResponse.data.MaxPKinSelectedRecords;
int MaxPKinTotalRecords = objResponse.data.MaxPKinTotalRecords;
if (listContact != null && listContact.Count>0)
{
try
{
Parallel.ForEach(listContact, contact =>
{
// some code...
});
// Recursive Call
if (MaxPKinTotalRecords != MaxPKinSelectedRecords)
{
ServiceFunctionality();
}
}
catch (Exception ex)
{
// Logging
}
}
}
else
{
// Logging
}
}
else
{
// Logging
}
}
catch (Exception ex)
{
// Logging
}
}
You can always unwind to a while loop. Because your calls aren't altering state, this is trival.
public void ServiceFunctionality()
{
bool done = false;
while(!done) {
try
{
done = true; //if we don't reset this, we're done.
// Get Data From WEBAPI
HttpClient client = new HttpClient();
HttpResponseMessage response = response = client.GetAsync("webapi url link").Result;
Response<ServiceWrapper> objResponse = response.Content.ReadAsAsync<Response<ServiceWrapper>>().Result;
if (objResponse != null)
{
if (objResponse.isSuccess == true)
{
listContact = objResponse.data.lContact;
int MaxPKinSelectedRecords = objResponse.data.MaxPKinSelectedRecords;
int MaxPKinTotalRecords = objResponse.data.MaxPKinTotalRecords;
if (listContact != null && listContact.Count>0)
{
try
{
Parallel.ForEach(listContact, contact =>
{
// some code...
});
// set loop variable
if (MaxPKinTotalRecords != MaxPKinSelectedRecords)
{
done = false;
}
}
catch (Exception ex)
{
// Logging
}
}
}
else
{
// Logging
}
}
else
{
// Logging
}
}
catch (Exception ex)
{
// Logging
}
}
}
Do not use recursion for calling a function whenever you have alternate suitable solution. I personally almost never do
I have tried to keep it same other than using a while..
Do not forget to break your loop. I tried to handle this thing but still
Just to be very careful, never take a risk of infinite loop on server I took maxPossibleIterations. So that in case of any mistake your web service server would not have to go for infinite iterations
public void ServiceFunctionality()
{
long maxPossibleIterations = 999999;
try
{
while (true)
{
maxPossibleIterations++;
// Get Data From WEBAPI
HttpClient client = new HttpClient();
HttpResponseMessage response = response = client.GetAsync("webapi url link").Result;
Response<ServiceWrapper> objResponse = response.Content.ReadAsAsync<Response<ServiceWrapper>>().Result;
if (objResponse != null)
{
if (objResponse.isSuccess == true)
{
listContact = objResponse.data.lContact;
int MaxPKinSelectedRecords = objResponse.data.MaxPKinSelectedRecords;
int MaxPKinTotalRecords = objResponse.data.MaxPKinTotalRecords;
if (listContact != null && listContact.Count>0)
{
try
{
Parallel.ForEach(listContact, contact =>
{
// some code...
});
if (MaxPKinTotalRecords == MaxPKinSelectedRecords)
{
break;
}
}
catch (Exception ex)
{
// Logging
}
}
else
break; //Important
}
else
{
// Logging
break;
}
}
else
{
// Logging
break;
}
} // End while
}
catch (Exception ex)
{
// Logging
}
}
I am trying to set my ASP row and cell color based off my method in my data class. I have the color set and the method running. The method returns true or false based on the conditions below. How can I prevent the method from running multiple times?
For instance, it runs once and returns correctly then it runs again with "" in the lineNum and brandNum fields with the pack count as the same number as the first run. It processed to run once for every instance of my method call. Then when I actually call the method again it runs everything again. Why is it running more than once and how can I fix this?
output:
lineNum:123 brandNum:456 packCount:15
second run (not asked for)
lineNum:"" brandNum:"" packCount:15
Method to determine if true:
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("#GenNum6", itemNum),
new SqlParameter("#GenTxt9", brandNum)
};
try
{
reader = App_Code.DBHelper.executeQuery(dbConn,
sqlString.ToString(), parameters);
if (reader.HasRows)
{
while (reader.Read())
{
PackCount = reader["PackCount"].ToString();
}
}
reader.Close();
reader.Dispose();
dbConn.Close();
dbConn.Dispose();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (dbConn != null)
{
try { dbConn.Close(); dbConn.Dispose(); }
catch { }
}
if (reader != null)
{
try { reader.Close(); reader.Dispose(); }
catch { }
}
}
if (Convert.ToInt32(PackCount) <= 12)
{
return true;
}
else
{
return false;
}
Call:
if (lineData.PacksLeft1(L1.Text,L2.Text))
{
myTable.Rows[1].Cells[0].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[1].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[2].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[3].BgColor = "#FE2E2E";
}
There is no need for the finally statement as it performs the same action that is performed in the try statement. I believe that after seeing this piece, if you go back through where it is being called from, you may have it running in a try catch, doing the exact same thing. I would suggest taking the
reader.Close();
reader.Dispose();
dbConn.Close();
dbConn.Dispose();
out of the try block and leaving the finally statement. This way, no matter the outcome, these items are performed.
Finally is only used when you want the code to run something after it has preformed the try statement. Such as:
Try{
//Try this statement, if it works, run it.
}
catch{
//error occurred
}
finally{
//run this code whether the try failed or not.
}
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