Trim exception message - asp.net

I'm trying to trim an exception message with the below code:
Response.Redirect("IllegalCharactersError.aspx?error=");
string message = ex.Message;
string cleanMessage = message.Substring(message.IndexOf("=") + 1);
Session.Add("IllegalCharactersError", cleanMessage.Replace("\\", ""));
Here is a sample of the string:
A potentially dangerous Request.Form value was detected from the client
(ctl00$Main$EmployerRegistrationCtrl$CompanyDetails$CompanyTradingAs="'<'My Company Trading").
I only want to display '<'My Company Trading but my label is displaying \"'<'My Company Trading\"). with back slashes so its not displaying and I cant seem to remove, any ideads how to acheive this?
Thanks
Darren

You should use HttpUtility.HtmlEncode:
lbl.Text = HttpUtility.HtmlEncode(value);
Use HttpUtility.HtmlDecode to read the Text of the label later:
string value = HttpUtility.HtmlDecode(lbl.Text);
If you want to transfer the error-message via URL, you need HttpUtility.UrlEncode and later HttpUtility.UrlDecode.
But i'm not sure where you are getting the backslashes from. The original error-message has none, are you masking it somewhere?
For the sake of completeness, here you find informations how you prevent the "dangerous Request.Form value"-error: A potentially dangerous Request.Form value was detected from the client

Did you make the IllegalCharactersException (or however it is called in your example) yourself? If you did, you should add some useful properties to it:
ex.OffendingValue
ex.Field
These properties should be filles when the exception is thrown.
That saves you from parsing the string at all.

Related

SQLDataSource parameter insertion: Sanitisation and formatting

I am building a Web application and I want to allow users to insert records into a database. The method that I came across is to take the information from text boxes and run this code:
SqlDataSource1.InsertParameters["ProductCode"].DefaultValue = txtProductCode.Text;
SqlDataSource1.InsertParameters["Name"].DefaultValue = txtName.Text;
SqlDataSource1.InsertParameters["Version"].DefaultValue = txtVersion.Text;
SqlDataSource1.InsertParameters["ReleaseDate"].DefaultValue = txtReleaseDate.Text;
try
{
SQLDataSource1.Insert();
}
...
If I try to inject some SQL I get the error message:
Message: String or binary data would be truncated. The statement has been terminated.
Does this method sanitise the parameters? I am having a hard time finding this information because I am not sure if there is still a way to get around this error. If it does not how should I go about sanitising the inputs?
Additionally, the ReleaseDate parameter seems to be currently reading as dd/MM/yyyy but is there a way to lock this so that the same code on a different system doesn't behave differently. I am worried that if the code is run on a system with different regional settings it will use a different format.
One of your field in the table is not long enough to insert the value. You need to check each of ProductionCode, name, Version and ReleaseDate for their length and increase them accordingly.
http://msdn.microsoft.com/en-us/library/aa196741(v=sql.80).aspx

What is the use of =? in links?

I saw my friend doing some Web Development, and one of his code caught my attention is the Response.Redirect.
What is the use of Home?=, isn't it the LogIn.aspx is the name of the page how come it's still redirecting if it has Home?=. Can someone answer this question of mine please, and explain it very well.
String url = "LogIn.aspx?Home?=" + Username;
Response.Redirect(url);
Update
Working from all your comments, the answer is: The query string parameter name (key) is actually "Home?", not just "Home". Details (including why the code generating that is technically incorrect) below.
how come it's still redirecting if it has Home?=?
Because there's no reason it shouldn't redirect. Granted the URL is invalid (? is a reserved character, it cannot appear unencoded in the query string, so the second ? in the URL is incorrect), but browsers are pretty content to deal with invalid URLs.
Separately, unless Username has already been URL-encoded, the URL could have other errors depending on the content of Username. (All query string parameters must be URL-encoded, in .Net you do that with HttpUtility.UrlEncode.)
Re your comment:
what i mean is i don't know why he use Home?= and what is the use of it
It has no use, it's an error. He probably just meant (no, apparently not, see below after your next comment)
String url = "LogIn.aspx?Home=" + Username;
...which would more correctly be:
String url = "LogIn.aspx?Home=" + HttpUtility.UrlEncode(Username);
(Technically, you have to URL-encode both the keys and values [both "Home" and Username], but the URL-encoded form of "Home" is "Home", so we can get away without making the call for the key. Not true if the key needs to have any of the URL reserved characters in it.)
Re your further comment consisting entirely of this code:
string retrieveValue;
protected void Page_Load(object sender, EventArgs e) {
this.lblUsername.Text = Request.QueryString["Home?";
retrieveValue = this.lblUsername.Text;
}
Assuming the syntax error in the above is fixed (missing ] on line 3), it would appear that he's actually using "Home?" as a key (parameter name). That means the redirect should be:
String url = "LogIn.aspx?" + HttpUtility.UrlEncode("Home?") + "=" + HttpUtility.UrlEncode(Username);
...because the key has a reserved character in it (?). Because that will be decoded for you on receipt, that should make the code above work.
Note that most browsers will probably let you get away with the string as he specified it. It's incorrect, but in a way browsers probably allow.
Regardless of the errors that T.J covered, what he meant to do was load the page LogIn.aspx with the variable "Home" being set to the visitors username. This allows the page to "GET" the variable and use it. Its basically a way of sending data from one page to another.

xmlreader.Create return none

i am trying to read from xml string But ,
` XmlReader reader=XmlReader.Create(new StringReader(stringXml)`
reader is always none. why is reader objest none ?
You have to call the read function.
reader.Read();
Here is the answer for your question. There seems to be no problem and the XmlReader is ready to be utilized.
Actually, if you are open to use .NetFramework 3.5 and higher you could benefit from using Linq To Xml:
XElement x = XElement.Load(new StringReader(s));
this happened to me in code that had been working for years. there were two paths for populating the xml string used in creating the xReader. The first pulled xml from a text parameter. If the text parameter was empty then it would fetch the string from sql server. If the text parameter was null, however, then I was getting "none" from the xReader. This despite the fact that SQL return perfectly formed xml. If the text parameter was an empty zero-length string, however, then everything worked fine, that is, the fetch to SQL ran, fetch xml and loaded the reader. It was like the runtime .net engine was running both paths simultaneously and giving me the worst possible outcome, instead of the desired outcome.

How can I isolate which parameter is throwing error in Insert Method?

I'm passing parameters (over 30 in all) from a system.data.dataset into a tableadapter insert method, but I'm getting an "Input string was not in a correct format" exception.
The error points to the method that is throwing, which is great, but is there a way I can tell exactly which parameter is throwing the error?
(Sorry about the code formatting -- I fought with it for 5 minutes before giving up)
myTableAdapter.Insert(
row["GUID"].ToString(),
Convert.ToInt16(row["domain"].ToString()),
Convert.ToInt16(row["plan"].ToString()),
Convert.ToInt16(row["type"].ToString()),
Convert.ToInt16(row["type_alt"].ToString()), ...etc
Thanks in advance!
Create a bunch of Int16 variables, convert into them, then pass to the Insert() method
Int16 domain = Convert.ToInt16(row["domain"].ToString());
Int16 plan = Convert.ToInt16(row["plan"].ToString());
..etc..
myTableAdapter.Insert(
row["GUID"].ToString(),
domain,
plan,
..etc..

Input String was not in correct format in asp.net

We've been facing an issue while saving our page. It throws "Input String was not in correct format". After trying so many time, we found there was no problem with the code, but with the "Cache (Temporary Internet File"). After Cache was cleared, it saved without any error. Does anyone knew the reason behind it?
That sounds like the sort of error that you get from a bad parse, say Int32.Parse("foo") where you were expecting "foo" to be something like "123". I am not sure why this would be affected by the cache.
My recommendation would be to look at the method where the exception occurs and see if it attempts to parse a string. If you expect that the string might not be in the correct format (say, it's a string entered by the user, you can replace
int i = Int32.Parse(myString);
with
int i;
if (Int32.TryParse(myString, out i))
Then you can handle the case of bad input in the else.
If however you expect the string should always be in the correct format (in other words, this is truly "exceptional" behavior), then I would leave it as a Parse and add a catch (FormatException ex), and within the catch log the string that caused the exception. This should hopefully help you in tracking down the underlying cause of the problem.
Or if the problem has never reoccured since you cleared the cache back in October of '09, just chalk it up to cosmic rays and move on I guess. ;)

Resources