Getting "object reference not set to an instance" in HttpContext.Current.Application - httpcontext

I'm hardly to figure out how to solve this.. I want to catch the error when the server is turn off and redirect the page to Maintenance.aspx. But it's getting error at HttpContext.Current.Application["ErrorCode"].ToString();.Please help me how to solve this...
Many thanks.
try{
// method here
}
catch (Exception ex)
{
Panel1.Visible = true;
string statuscode = HttpContext.Current.Application["ErrorCode"].ToString(); //Getting error here!
if (statuscode != null || statuscode != string.Empty)
{
if (statuscode == "500")
{
lblDetailMsg.Text = "<b>Error Page- <b> " + HttpContext.Current.Application["ErrorPage"].ToString() + " <br /> <b>Error Message-</b> The Requested Page was not found.";
Response.Redirect("Maintenance.aspx");
}
}
}

If I understand your code right, then the error must be due to .toString() method.
Try this
string statuscode = Convert.ToString(HttpContext.Current.Application["ErrorCode"]); // added Convert.Tostring()
if (statuscode != null || statuscode != string.Empty)
{
if (statuscode == "500")
{
lblDetailMsg.Text = "<b>Error Page- <b> " + Convert.ToString(HttpContext.Current.Application["ErrorPage"]) + " <br /> <b>Error Message-</b> The Requested Page was not found.";
Response.Redirect("Maintenance.aspx");
}
}
Convert.ToString() handles null, while ToString() doesn't.
Here it seems that HttpContext.Current.Application["ErrorCode"] does not contain value for "Error Code", so it giving null value.

Related

Continue foreach loop even after an exception is encounterd in asp.net core razor pages

I have to log the exception into a database table and continue the foreach loop without any interruptions .
When i am trying to insert the exception into database table in catch block,its throwing null referenece exception. Here is my code.
foreach (var row in toEmailList)
{
foreach (var matrix in emailMatrixList.Where(u => names.Contains(u.BusinessUnit)))
{
// Send to Staff + Supervisor/Manager
if (row.DaysDueDate <= 42 && row.DaysDueDate >= 28)
{
if (matrix.StaffID.Equals(row.StaffID))
{
if (!row.EmailLevelSent.Equals("First Level"))
{
try {
var message = new MailMessage();
var bodyText = "<div style='font-family: Calibri, Arial, Helvetica, sans-serif;'>" +
"<p>Dear #FirstName #LastName,</p>" +
"<p>This is a notification to remind you that you have <b>#DaysDueDate</b> days to complete the following online <b>#TrainingTitle</b> training.</p>" +
"<p>Please remember to complete the training course within the next few days.</p>" +
"<p>If you do not complete this training within the required time frame, this information will be forwarded to your next level manager.</p>" +
"<p>Thank you very much,<br/>Kind regards,</p>" +
"<p>Manager</p>" +
"</div>";
var body = bodyText.Replace("#FirstName", row.FirstName).Replace("#LastName", row.LastName).Replace("#DaysDueDate", row.DaysDueDate.ToString()).Replace("#TrainingTitle", row.TrainingTitle.ToString());
if (matrix.StaffEmail.Contains("#domain.com"))
{
message.To.Add(new MailAddress(row.StaffEmail));
}
else if (matrix.ManagerEmail.Contains("#domain.com"))
{
message.To.Add(new MailAddress(matrix.ManagerEmail));
}
message.From = new MailAddress(_from);
message.Subject = "Training Notification for " + row.TrainingTitle;
if (matrix.ManagerEmail.Contains("#domain.com"))
{
message.CC.Add(new MailAddress(matrix.ManagerEmail));
}
else if ((matrix.ManagerEmail.Contains("N/A")) || (matrix.ManagerEmail.Contains("NA")) || (matrix.ManagerEmail.Contains("#N/A")) || (matrix.ManagerEmail.Contains("na")))
{
message.To.Add(new MailAddress(row.StaffEmail));
}
if (!string.IsNullOrEmpty(matrix.InTheLoop))
{
message.CC.Add(new MailAddress(matrix.InTheLoop));
}
message.Body = string.Format(body);
message.IsBodyHtml = true;
await smtp.SendMailAsync(message);
TempData["MailSent"] = "MailSent";
Debug.WriteLine("Sending first level email to " + row.FirstName + " " + row.LastName);
Debug.WriteLine("CC: " + message.CC.ToString());
row.EmailLevelSent = "First Level";
Debug.WriteLine("First Level email sent to " + row.FirstName);
}
catch (Exception e)
{
FailedEmails.StaffID = row.StaffID;
FailedEmails.FirstName = row.FirstName;
FailedEmails.LastName = row.LastName;
FailedEmails.StaffEmail = row.StaffEmail;
FailedEmails.ExceptionLog = e.Message;
FailedEmails.SentDate = DateTime.Now;
_context.Entry(FailedEmails).State = EntityState.Added;
}
}
}
}
}
}
Any help would be appreciated, is there anything i am missing. Thanks!

Using string translation in adapter return numbers

I am trying to use translation string in my adapter but it returns numbers instead
if(currentItem.budget != null){
holder.budget.text = "$ " + currentItem.budget.format()
} else {
holder.budget.text = R.string.open_to_suggestions.toString()
}
R.string.open_to_suggestions.toString() supposed to return string text Open to suggestions but it returns numbers such as 2131755113 not sure why! any idea?
To show the string resource you must use context.getString()
if(currentItem.budget != null) {
holder.budget.text = "$ " + currentItem.budget.format()
} else {
val context = holder.itemView.context
holder.budget.text = context.getString(R.string.open_to_suggestions)
}
Please take a look at the definition of getString here

How to fix '0 level missing for abstractListDefinition 0' error when using Emulator.getNumber()

I used docx4j to read the docx file. And I need to read the paragraph number format characters. I use Emulator.getNumber() to process, but I got this error. How should I deal with it?
try {
PPr pPr = ((P) p).getPPr();
if (pPr != null && pPr.getNumPr() != null) {
Emulator.ResultTriple triple = Emulator.getNumber(wordprocessingMLPackage, pPr);
if (triple != null) {
order = triple.getNumString();
}
}
} catch (Exception e) {
// throw error '0 level missing for abstractListDefinition 0'
e.printStackTrace();
}
Any help would be appreciated.Thanks.
docx4j version: 6.1.2
docx4j's html output uses it like so:
// Numbering
String numberText=null;
String numId=null;
String levelId=null;
if (pPrDirect.getNumPr()!=null) {
numId = pPrDirect.getNumPr().getNumId()==null ? null : pPrDirect.getNumPr().getNumId().getVal().toString();
levelId = pPrDirect.getNumPr().getIlvl()==null ? null : pPrDirect.getNumPr().getIlvl().getVal().toString();
}
ResultTriple triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal, numId, levelId);
if (triple==null) {
getLog().debug("computed number ResultTriple was null");
} else {
if (triple.getBullet() != null) {
//numberText = (triple.getBullet() + " ");
numberText = "\u2022 ";
} else if (triple.getNumString() == null) {
getLog().error("computed NumString was null!");
numberText = ("?");
} else {
numberText = (triple.getNumString() + " ");
}
}
if (numberText!=null) {
currentParent.appendChild(document.createTextNode(
numberText + " "));
}
XSL-FO output:
if (pPrDirect!=null && pPrDirect.getNumPr()!=null) {
triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal,
pPrDirect.getNumPr().getNumId().getVal().toString(),
pPrDirect.getNumPr().getIlvl().getVal().toString() );
} else {
// Get the effective values; since we already know this,
// save the effort of doing this again in Emulator
Ilvl ilvl = pPr.getNumPr().getIlvl();
String ilvlString = ilvl == null ? "0" : ilvl.getVal().toString();
triple = null;
if (pPr.getNumPr().getNumId()!=null) {
triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal,
pPr.getNumPr().getNumId().getVal().toString(),
ilvlString );
}
}

How to validate a link showing 500 error in Selenium?

I am trying to validate the links of a website using server response code and page title, the server response found through the code shown below is 200 and page title is also same for all the pages.
the code is as follows:
if(url == null || url.isEmpty())
{
System.out.println("URL is either not configured for anchor tag or it is
empty");
objExcelFile.writeExcel(filePath,"skipped_links",url);
}
else if(!url.startsWith(homePage)){
System.out.println("URL belongs to another domain, skipping it.");
objExcelFile.writeExcel(filePath,"skipped_links",url);
}
else{
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
if(respCode != 200){
System.out.println(url+" is a broken link");
String Actualtitle = driver.getTitle();
System.out.println(Actualtitle);
System.out.println(respCode);
objExcelFile.writeExcel(filePath,"broken_links",url);
}
else{
String Actualtitle = driver.getTitle();
System.out.println(Actualtitle);
if (Actualtitle.contentEquals(unexpectedTitle)){
System.out.println(url+ " is a broken link");
objExcelFile.writeExcel(filePath,"broken_links",url);
} else {
System.out.println(url+ " is a valid link");
System.out.println(respCode);
objExcelFile.writeExcel(filePath,"valid_links",url);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
The header is intact but the link is showing 500 error below the header. The issue is that even though page is showing 500 error, I am getting the server response code as 200, hence I am not able to make out whether this link is broken or not
This is the screenshot of the issue for the page I am validating :
enter image description here
Once you induce connect() as in :
huc.connect();
You can write as many for() loops to check any condition of the Response Code invoking getResponseCode() method as below :
if (huc.getResponseCode() == 200)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 500)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 404)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 402)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == httpUrlConnect.HTTP_NOT_FOUND)
{
System.out.println(
linkURL + " - " + huc.getResponseMessage() + " - " + huc.HTTP_NOT_FOUND);
}
} catch (IOException e)
{
System.out.println(e.getMessage());
}

IPathVariableManager.validateValue(URI) returns null

in the Eclipse plugin I'm working on I have a piece of code which basically looks like this:
public static void checkProblemV1() {
try {
String path = "C:\\temp";
org.eclipse.core.runtime.IPath value =
new org.eclipse.core.runtime.Path(path);
IPathVariableManager pathManager =
ResourcesPlugin.getWorkspace().getPathVariableManager();
String name = "somename";
IStatus statusName = pathManager.validateName(name);
IStatus statusValue = pathManager.validateValue(value);
if (statusName == null || statusValue == null) {
System.err.println("checkProblemV1(): statusName is " +
(statusName == null ? "null" : ("not null: '" + statusName + "'.")));
System.err.println("checkProblemV1(): statusValue is " +
(statusValue == null ? "null" : ("not null: '" + statusValue + "'.")));
}
else if (statusName.isOK() && statusValue.isOK()) {
pathManager.setValue(name, value); // setValue is deprecated
System.out.println("checkProblemV1(): Everything fine");
}
else {
if (!statusName.isOK()) {
System.err.println("checkProblemV1(): statusName is not OK.");
}
if (!statusValue.isOK()) {
System.err.println("checkProblemV1(): statusValue is not OK.");
}
}
}
catch (CoreException e) {
System.err.println("checkProblemV1(): CoreException: " + e.getMessage());
}
}
When the above method is executed, there are no problems, but I get a deprecation warning for setValue() when compiling. It's when I wanted to fix that deprecation warning by replacing the call to setValue() with a call to setURIValue() that I got into trouble. First I had to tweak how that Windows-style path was written to avoid an URISyntaxException but after doing that, setURIValue() returns null and after having a look in the documentation I can't see that it should do that? I guess the URI is invalid after all but don't know how to fix it. Below is a test method in the same style as the one above demonstrating the problem.
public static void checkProblemV2() {
try {
String path = "C:\\temp";
// Have to replace \ with /, or we get URISyntaxExeption:
// checkProblemV2(): URISyntaxException: Illegal character in opaque part at index 2: C:\temp
path = path.replace('\\', '/');
java.net.URI value = new java.net.URI(path);
IPathVariableManager pathManager =
ResourcesPlugin.getWorkspace().getPathVariableManager();
String name = "somename";
IStatus statusName = pathManager.validateName(name);
IStatus statusValue = pathManager.validateValue(value);
if (statusName == null || statusValue == null) {
System.err.println("checkProblemV2(): statusName is " +
(statusName == null ? "null" : ("not null: '" + statusName + "'.")));
System.err.println("checkProblemV2(): statusValue is " +
(statusValue == null ? "null" : ("not null: '" + statusValue + "'.")));
}
else if (statusName.isOK() && statusValue.isOK()) {
pathManager.setURIValue(name, value);
System.out.println("checkProblemV2(): Everything fine");
}
else {
if (!statusName.isOK()) {
System.err.println("checkProblemV2(): statusName is not OK.");
}
if (!statusValue.isOK()) {
System.err.println("checkProblemV2(): statusValue is not OK.");
}
}
}
catch (URISyntaxException e) {
System.err.println("checkProblemV2(): URISyntaxException: " + e.getMessage());
}
catch (CoreException e) {
System.err.println("checkProblemV2(): CoreException: " + e.getMessage());
}
}
When I run the above two methods, I get the following output.
checkProblemV1(): Everything fine
checkProblemV2(): statusName is not null: 'Status OK: unknown code=0 OK null'.
checkProblemV2(): statusValue is null
Thanks for reading and for any help, it's seriously appreciated!
There's a bug in org.eclipse.core.internal.resources.PathVariableManager.validateValue(URI) where it is using other internal methods but returning null no matter what else is going on. Please open a bug with Eclipse Platform/Resources.
And I agree with your comment, you should use:
URI uri = new File("C:\\temp").toURI();
pathManager.setURIValue(theName, uri);