i've got a bit of a problem trying to set up a general error page in MVC.
I am handling all app errors in Global.asax.cs with the following code ->
protected void Application_Error(object sender, EventArgs e)
{
//if (Request.Url.ToString().StartsWith("http://localhost:"))
// return;
string msg;
Exception ex = Server.GetLastError().GetBaseException();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Exception Found");
sb.AppendLine("Timestamp: " + System.DateTime.Now.ToString());
sb.AppendLine("Error in: " + Request.Url.ToString());
sb.AppendLine("Browser Version: " + Request.UserAgent.ToString());
sb.AppendLine("User IP: " + Request.UserHostAddress.ToString());
sb.AppendLine("Error Message: " + ex.Message);
sb.AppendLine("Stack Trace: " + ex.StackTrace);
msg = sb.ToString();
Server.ClearError();
Response.Redirect(string.Format("~/Error/Error?w={0}", msg ));
}
My problem is that i'm not getting a redirect. I see the same page URL and a blank page when i'm creating an error.
If i remove "errorMsg" and add a SIMPLE STRING, it works, redirects with the required param. Ex:
string test = "testme";
Response.Redirect(string.Format("~/Error/Error?w={0}", test));
That does redirect me to the error page with param "testme". What am i doing wrong here?
You to need escape all the parameters (UrlEncode). At the moment it is unescaped and has a whole bunch of new lines too.
Before you do that, I suggest you just append "hello world" parameter and re-display that to ensure your redirect page is working
Related
I am building a C# application that handles a custom protocol used in my web application.
The links are like:
Print
These are handled using a handler in the windows registry (URL:zebra-wp Protocol):
"C:\Program Files (x86)\[My App Name]\[My App].exe" "%1"
I am running the following code in my app:
class LabelData
{
public string name;
public string barcode;
}
static class Program
{
[STAThread]
static void Main(string[] args)
{
if (args.Length > 0 && args[0].StartsWith("zebra-wp://"))
{
// retrieve data from argument
string argData = args[0].Remove(0, 11);
string decodedJson = "";
try
{
// Undo URL Encoding
decodedJson = WebUtility.UrlDecode(argData);
}
catch (Exception ex)
{
string msg = "Couldn't print label, failed to decode data.";
msg += "\nData: " + argData;
msg += "Error: " + ex.Message;
MessageBox.Show(msg);
Application.Exit();
}
// Unpack JSON string
LabelData decodedData = new LabelData();
try
{
decodedData = JsonConvert.DeserializeObject<LabelData>(decodedJson);
}
catch (Exception ex)
{
string msg = "Couldn't print label, failed to unpack data.";
msg += "\nData: " + decodedJson;
msg += "Error: " + ex.Message;
MessageBox.Show(msg);
Application.Exit();
}
// Do things with object
When I debug the application I enter the link URL into the "Command line arguments" start up option.
The program works as expected and the JSON data is successfully decoded.
When I build and install, the JsonConvert.DeserializeObject function gives me the following error:
Data: {"barcode":"000063","name":"Food Fun - Magnetic Multicultural set"}
Error: Unexpected end while parsing comment. Path '', line 1, position 68.
Is something different about how VS launches an app with command line arguments in debug?
Is there a way to debug the application with the same command line arguments as when I click the URL?
I have found the issue, apparently when passing URI's to custom protocol handlers, Windows adds a trailing forward slash to the URI, checking for this in the code and removing it solves the problem.
I have a "error.aspx" page which is there to mail me if any exception is caught. When I open the page manually, mysite.com/error.aspx, the page opens fine but when it is redirected by a catch block with the exception.message and exception.stackTrace as querystrings, I get an error "page not found". Are the querystrings directing the browser to open a different url? It works fine when run on localhost, though.
public void send_error(Exception ex)
{
Response.Redirect("error.aspx?time=" + DateTime.Now.ToString() + "&ex=" + ex.Message + "&st=" + ex.StackTrace.Replace("\n", " "), false);
}
If you check this Article, you will see that the max query length of url string is 2048 symbols for Internet explorer. Probably the url is bigger and because of that you have this problem. One solution is to save the desire message in the session as string and after that retrieve it on other pages.
string errorMessage = DateTime.Now.ToString() + " " + ex.Message + " " + ex.StackTrace.Replace("\n", " ");
Session["__ErrMessage"] = errorMessage;
When you are in other pages you can access this string like this:
string errMessage = "";
if(Session["__ErrMessage"] != null)
errMessage = Session["ErrMessage"].ToString();
I am trying to catch an exception when my XSD is invalid and just display a message on the console detailing to the user what went wrong. However the message that is displayed on the console is not as I expected.
try
{
// doing stuff here
}
catch (XmlException e)
{
Console.WriteLine("ERROR: Schema " + e.Message);
return false;
}
I expected the output to be something like:
"ERROR: Schema ' is an unexpected token. The expected token is '>'. Line 15, position 38."
However the output that I get is:
"' is an unexpected token. The expected token is '>'. Line 15, position 38."
My string at the beginning is not displayed before the message.
I have tried storing the values in two strings and tried concatenating those 2 string with no success. Ideally I would like one string that contains the concatenation of both the 'ERROR' part and the message produced by the exception.
I think your schema contains a newline. The text ERROR: Schema ' must be somewhere higher in the output window.
You can check this using:
catch (XmlException e)
{
string message = "ERROR: Schema " + e.Message;
message = message.Replace(Environment.NewLine, "");
message = message.Replace("\n", "");
message = message.Replace("\r", "");
Console.WriteLine(message);
return false;
}
Try with:
try
{
// doing stuff here
}
catch (XmlException e)
{
errorMessage = "ERROR: Schema " + e.Message.toString();
Console.WriteLine(errorMessage );
return false;
}
I'm using the following code in my global.asax file:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error event<hr />" + "Current User: " + HttpContext.Current.User.Identity.Name + "<hr />" +
"Error in: " + Request.Url.ToString() +
"<hr />Error Message:" + objErr.Message.ToString() +
"<hr />Stack Trace:" + objErr.StackTrace.ToString();
//EventLog.WriteEntry("Sample_WebApp", err, EventLogEntryType.Error);
doEmail.sendEmail("Application Error - Curato (" + System.Configuration.ConfigurationManager.AppSettings["OrganisationName"].ToString() + ")", err);
// We do not want the error handled by the web.config as well, so clear the error.
Server.ClearError();
// Now redirect ourselves...
Response.Redirect("~/error.aspx?aspxerrorpath=" + Server.UrlEncode(Request.Url.PathAndQuery));
}
This sends the stackTrace and current user to an admin email address, and redirects the user to a friendly error page.
How would I be able to include the full Trace information in err? That is, the same information as if I had set Trace="True" in the <%# Page directive.
I'm exploring the Trace object - and found how to read it from a 3rd party reader how to read trace but I'd like to read it just in native code.
You're already getting the full StackTrace of the exception, I believe you're looking at the wrong Exception object:
I think your error is in this line:
Exception objErr = Server.GetLastError().GetBaseException();
I think the correct one should be:
Exception objErr = Server.GetLastError();
You can also inspect the exception to see if there are InnerException:
if (objErr.InnerException != null)
err = err + "<hr/>Message:" + objErr.InnerException.Message;
See this question also:
Application_Error - GetLastError() or GetLastError().GetBaseException()
I get this exception but cant seem to find my issue:
A first chance exception of type 'System.Net.Http.HttpRequestException' occurred in System.Net.Http.dll
I am logging into a server with username and password, and the process is working just fine.
Heres my code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
teamScreen = "https://thewebsite.com/teambeta/Login.aspx?" + "username=" +
logInUserIdString + "&password=" + logInPasswordString +
"&mobile=1&offsetHours=" + timezone;
webView1.Navigate(targetUri);
}
But I dont want to submit an app to the store with the issue not resolved.
Does anyone know what the issue is as I cant seem to track down why I am getting the exception? Thanks.
still not solved but I did fix the following as I did not have the Uri set correctly.
Here is the correct code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
teamScreen = "https://thewebsite.com/teambeta/Login.aspx?" + "username=" +
logInUserIdString + "&password=" + logInPasswordString +
"&mobile=1&offsetHours=" + timezone;
Uri targetUri = new Uri(teamScreen);
webView1.Navigate(targetUri);
}
not sure why it actually worked before as I never set the URI. Very strange, but still getting the error.