Concatenating string with exception message - c#

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;
}

Related

Decoding JSON command line arguments fails after build but succeeds during debug

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.

Response.Redirect not sending string

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

Query Active Directory in C#

I am trying to perform a query to Active Directory to obtain all the first names of every user. So I have created a new console application and in my main method have the following code:
try
{
DirectoryEntry myLdapConnection =new DirectoryEntry("virtual.local");
myLdapConnection.Path = "LDAP://DC=virtual,DC=local";
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.PropertiesToLoad.Add("cn");
SearchResultCollection allUsers = search.FindAll();
I have added some code to check that the connection is being made and that the path can be found. I also ensure that the Collection is not empty.
//For Debugging
if(DirectoryEntry.Exists(myLdapConnection.Path())
{
Console.WriteLine("Found");
}
else Console.WriteLine("Could Not Find LDAP Connection");
//In my case prints 230
Console.WriteLine("Total Count: " + allUsers.Count);
foreach(SearchResult result in allUsers)
{
//This prints out 0 then 1
Console.WriteLine("Count: " + result.Properties["cn'].Count);
if (result.Properties["cn"].Count > 0) //Skips the first value
{
Console.WriteLine(String.Format("{0,-20} : {1}",
result.Properties["cn"][0].ToString())); //Always fails
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
I have specified in the code, where it prints out the properties, that it always fails. I get a System.FormatException being caught here that states the Index must be greater than zero and less than the size of the argument list.
So in the end I'm not really sure how "result.Properties" works and was wondering if you had any advise on how to fix or troubleshoot the problem.
You are defining two format specifiers {0} and {1} but only specifying one argument.

Display exception message through javascript alert in asp.net

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.

how to check whether some entered InnerText is present in an XML or not and to give an exception?

I have written a code in C# - XML which checks whether a value is there or not in a given XML document and prints the value and the particular tag associated with the value.
When we enter the Value of the Inner Text it will look for the value in the document and find it. I dont understand what exception to catch when the entered value is not there in the document.
I tried doing like this but it is not working.
1.
if (inpXMLString != AppChildNode.InnerText)
throw new InvalidDataException("The entered value" + " " + inpXMLString + " " + "doesnot exist");
Here : inpXMLstring = entered value;
AppChildNode.InnerText = value of the tags searched.
2.
catch (System.Xml.XmlException e1)
{
Console.WriteLine(e1.Message);
}
this does not give any exception when the entered value is not there in the XML document.
Please help me in this regard.
Looks like the code is catching a different exception than it is throwing. The code appears to throw a InvalidDataException but catches a System.Xml.XmlException. Here are a few articles on exception handling:
http://msdn.microsoft.com/en-us/library/ms173160(VS.80).aspx
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=128
Something Like this:
void DoSomething()
{
try
{
/*
* Do Something Useful.
*/
CheckValue("Hello");
}
catch (InvalidDataException e)
{
Console.WriteLine(e.Message);
}
}
private void CheckValue(string inpXMLString)
{
if (inpXMLString != AppChildNode.InnerText)
throw new InvalidDataException("The entered value" + " " + inpXMLString + " " + "doesnot exist");
}

Categories