Checking for null value in HttpContext.Current Object - c#

We have strange situation where something is causing an exception on Http.Current object such as .Response or .Request. The exception is NullReferecne. I was under the impression that HTTPContext under normal circumstances can't be null. But since in our case it can how should I handle this type of exception? We're already handle HTTPException in Global.asax.cs and with ErrorSeverity as Fatal which is home grown class. I 've modified the code that checks for null value but I'm not cetain if that really catches this scenario - see code below:
protected void Application_Error(object sender, EventArgs e)
{
try
{
Exception exception = Server.GetLastError();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
if (httpException.GetHttpCode() == 404)
{
return;
}
}
string errMessage = "Running Application_Error. An unhandled error occured in the application.";
errMessage = errMessage + "Error message = " + exception.Message;
//This is the IF-ELSE I've added but it just doesn't "feel right"
if (HttpContext.Current.Request != null || HttpContext.Current.Response != null)
{
StaticServices.ErrorLogger.LogSingleException(exception, ErrorSeverity.Fatal);
}
else
{
StaticServices.ErrorLogger.LogSingleException(exception, ErrorSeverity.Info);
}
exception = exception.InnerException;
while (exception != null)
{
StaticServices.ErrorLogger.LogSingleException(exception, ErrorSeverity.Fatal);
exception = exception.InnerException;
}
QSession session = QSession.GetInstance();
bool mobileIndicator = session != null ? session.Packet.QPolicy.IsMobileApplication : false;
if (mobileIndicator)
{
LogAndRedirectTechDiff("MobileTechnicalDifficulties.htm", session != null);
}
else
{
//This is the IF-ELSE I've added but it just doesn't "feel right"
if (HttpContext.Current.Request != null || HttpContext.Current.Response != null)
{
LogAndRedirectTechDiff("TechnicalDifficulties.htm", session != null);
}
else
{
LogAndRedirectTechDiff("UnsupportedBrowser.htm", session != null);
}
}
}
catch (Exception ex)
{
EventLog.WriteEntry("FQ",
"Global.asax.cs Application_Error method caused an exception. This is the error message :" +
ex.ToString(), EventLogEntryType.Error);
}
}

Related

C# Are errors in DataGridView.Datasource assignments handled internally

I have an application that assigns a list of values to a DataGridView.
This is done inside a Try catch block.
Occasionally there is an issue with the with the procedure that produces this list (also in a try catch block) and this causes an error when the assignment is done.
It appears the exception is never caught by the block doing the assignment and the application freezes.
Is the exception handled inside the assignment call so that it is not propagated out to the catch block?
The exception produced as a pop up states
"The following exception occurred in the DataGridView:
System.IndexOutOfrangeException: Index 1 does not have a value at
System.Windows.Forms.dataGridViewDataConnection.GetError(Int32 rowIndex)
To replace this default dialog please handle the DataError event"
The code is basically
public void SetupRunners(EventDetails _eventDetails)
{
try
{
RunnerAssociates.Clear();
RunnerAssociates = null;
RunnerAssociates = createRunnerAssociateList(selectedEventDetails);
runnerAssociatesDataGridView.DataSource = RunnerAssociates;
runnerAssociatesDataGridView.DataMember = string.Empty;
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
}
private List<Runner_Associate> createRunnerAssociateList(EventDetails _meetAndRace) //NZRB_Global.MeetAndRace _meetAndRace)
{
const string methodName = "createRunnerAssociateList";
List<Runner_Associate> lra = new List<Runner_Associate>();
try
{
if (null != _meetAndRace)
{
_meetAndRace.UpdateAllProfiles();
foreach (RunnerDetail rd in _meetAndRace.runners.runnerList)
{
Runner_Associate ra = new Runner_Associate();
ra.Number = rd.number;
ra.RunnerName = rd.name;
RunnerProfile profile = rd.GetRunnerProfile();
if ((rbJockeyDriver.Checked) || (rbCustom.Checked))
{
ra.AssociateName = rd.person;
}
else if (profile != null)
{
if (rbTrainers.Checked)
{
ra.AssociateName = profile.trainer;
}
else if (rbOwners.Checked)
{
ra.AssociateName = profile.owners;
}
}
lra.Add(ra);
}
}
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
return lra;
}

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.

Unreachable code detected in C#.Net

I'm getting unreachable code warning in catch block and I'm not able to debug. Please suggest me how to rectify that bug:
private void HandleDevelopmentServer()
{
string sErrMsg = "";
try
{
QuasarInterfaces.ISecurity oSecurity = null;
Global.CreateSecurityComponent(ref oSecurity);
System.Data.DataSet oDS;
DataTable dtDBSettings = new DataTable();
string sDBString = System.Configuration.ConfigurationSettings.AppSettings["Environment"];
Global.ReadDBConfig(sDBString, ref dtDBSettings);
oSecurity.FetchAllUsers(out oDS, out sErrMsg, dtDBSettings)
if (sErrMsg.Length > 0)
throw new Exception(sErrMsg);
if ((oDS != null) && (oDS.Tables.Count != 0))
{
DropDownList1.DataSource = oDS;
DropDownList1.DataBind();
}
}
catch (Exception e)
{
throw new Exception("HandleDevelopmentServer function failed;" + e.Message);
Global.writeLog("" + e.ToString());
}
}
This line will never happen:
Global.writeLog("" + e.ToString());
You are throwing an exception just above it, meaning this method will exit at that point to the previous in the call stack
By just switching the two it will be fine.
catch (Exception e)
{
Global.writeLog("" + e.ToString());
throw new Exception("HandleDevelopmentServer function failed;" + e.Message);
}
And you can also remove the "" +.
You have to switch the two lines in the catch block so that the log is written before the exception is thrown.

Thread was being aborted when we use

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

Returning a bool and rethrowing an exception

Is it possible to return a bool and also rethrow an exception within the same method? Ive tried with the following code and it keeps saying that unreachable code is detected or that i cant exit the finally block.
public bool AccessToFile(string filePath)
{
FileStream source = null;
try
{
source = File.OpenRead(filePath);
source.Close();
return true;
}
catch (UnauthorizedAccessException e)
{
string unAuthorizedStatus = "User does not have sufficient access privileges to open the file: \n\r" + filePath;
unAuthorizedStatus += e.Message;
MessageBox.Show(unAuthorizedStatus, "Error Message:");
throw;
}
catch (Exception e)
{
string generalStatus = null;
if (filePath == null)
{
generalStatus = "General error: \n\r";
}
else
{
generalStatus = filePath + " failed. \n\r";
generalStatus += e.Message;
}
MessageBox.Show(generalStatus, "Error Message:");
throw;
}
finally
{
if (source != null)
{
source.Dispose();
}
}
}
Once you throw an exception, processing in your current method finishes and the exception works up the call stack. Either handle your exceptions locally and then return your boolean, or throw them and let them bubble up and handle them at the front end.

Categories