I am trying to show exception message through javascript alert box.
Here is the sample code.
public static void HandleException(Page page, Exception ex)
{
string message = ex.Message.ToString();
ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "", "alert('"+message+"');", true);
}
It runs if i give literal values for the string variable.
e.g.
string message = "Hello World";
But it fails if I give message = ex.Message;
Any Idea?
You need to encode it, for example using JavaScriptSerializer because if the message contains some escape characters like ' or " this will definitely break your javascript:
var message = new JavaScriptSerializer().Serialize(ex.Message.ToString());
var script = string.Format("alert({0});", message);
ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "", script, true);
try
{
//do some thing
}
catch (Exception ex)
{
Response.Write("<script language='javascript'>alert('" +
Server.HtmlEncode(ex.Message) + "')</script>");
}
Does your ex.Message have any ' characters in it? They may need escaping.
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'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
Is there a way to retrieve log in information after logging in to outlook with lumisoft? This is my code
private void Connect()
{
string m_pUserName = "user#hotmail.com";
string m_pPassword = "pass";
string m_pServer = "imap-mail.outlook.com";
IMAP_Client imap = new IMAP_Client();
try
{
imap.Logger = new Logger();
imap.Connect(m_pServer, 993, true);
imap.Login(m_pUserName, m_pPassword);
MessageBox.Show(imap.GreetingText);
}
catch (Exception x)
{
MessageBox.Show(this, "IMAP server returned: " + x.Message + " !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
imap.Dispose();
}
}
If the credentials are wrong it will eventually throw an exception.
However if they are correct I want to retrieve informations other than GreetingText. For example email and password of the user logged in etc.
Any tips?
Most of the informations I was searching, not all, are in IMAP_Client.AuthenticatedUserIdentity so imap.AuthenticatedUserIdentity
will give me most of the things I am looking for.
Thanks and sorry for troubles.
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 have RegisterStartupScript in the code-behind class to alert error message -- it works fine except when the error has line feeds or carriage returns (I think). Here is the snippet:
The commented code works fine!
catch (Exception ex)
{
//Page.ClientScript.ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Failure", "alert('ERROR: '), true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "System Error", "alert('" + ex.Message.Replace("'", "\\'") + "');", true);
}
Line terminators are not allowed in js strings.
Eliminate the line terminators (carriage returns, new line symbols etc.) using regular expressions:
var errorMsg = Regex.Replace(ex.Message,
#"[\u000A|\u000D|\u2029\u2028|\u000D\u000A]", " ");
Page.ClientScript.RegisterStartupScript(this.GetType(), "System Error",
String.Format("alert('{0}');", errorMsg), true);