HttpRequestValidationException - How to get full value entered? - asp.net

We receive multiple HttpRequestValidationExceptions on our website. We catch these appropriately, but would like to start logging them in more detail. The message that is caught shows
"A potentially dangerous Request.Form value was detected from the client (ctl00$txtSearch=\"<a href=\"www.google.com...\")."}
We would like to know the full text of what was entered in the text box and will do nothing except log it. I know that I entered
www.google.com
but as you can see, it did not show all of that in the Message part of the exception. InnerException is null, so that is of no help.
This is the code we use:
void Application_Error(object sender, EventArgs e)
{
// Get the last exception that has occurred
if (Server.GetLastError() != null)
{
var ex = Server.GetLastError().GetBaseException();
//...log it here
}
}
How can we get the full text entered into the text box? Turning off the page validation is not an option. Thank you in advance!

Use Request.Form["key name"] after catching last exception.
var val = Request.Form["txtInput1"];
You can also use
foreach (string key in Request.Form.AllKeys)
{
//Log everything.
var x = Request.Form[key];
}
Above I had tbSource as a text box and capturing the Value on Application_Error

Related

How to try catch block in Jmeter.Webdriver webdriver Sampler

I want to do the exception handling in Jmeter.Webdriver Webdriver Sampler
Please let me , How to use try/catch block in Jmeter.Webdriver webdriver Sampler ?
You can do this via normal JavaScript try block, here is an example of taking a screenshot when error occurs:
var pkg = JavaImporter(org.openqa.selenium)
var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
var wait = new support_ui.WebDriverWait(WDS.browser, 5)
var exception = null
WDS.sampleResult.sampleStart()
try {
WDS.browser.get('http://example.com')
wait.until(conditions.presenceOfElementLocated(pkg.By.linkText('Not existing link')))
} catch (err) {
WDS.log.error(err.message)
var screenshot = WDS.browser.getScreenshotAs(pkg.OutputType.FILE)
screenshot.renameTo(java.io.File('screenshot.png'))
exception = err
} finally {
throw (exception)
}
WDS.sampleResult.sampleEnd())
Don't forget to "throw" the error after you handle it otherwise it will be "swallowed" and you get a false positive result.
See The WebDriver Sampler: Your Top 10 Questions Answered article for more tips and tricks
Surround the code with try block and add catch block at the end by giving variable name to capture the exception. (in the example, it is exc)
try as follows:
try{
WDS.sampleResult.sampleStart()
WDS.browser.get('http://jmeter-plugins.org')
var pkg = JavaImporter(org.openqa.selenium)
WDS.browser.findElement(pkg.By.id('what')) // there is no such element with id what
WDS.sampleResult.sampleEnd()
}
catch(exc){ //exc variable name
WDS.log.error("element not found" + exc)
}
in the JMeter log, you can see the complete trace of NoSuchElementException, which is raised when trying to find the element by id with the values as what, which is not present in the HTML.
Note: use View Results in Table to see the Sampler response time.
Reference:
https://jmeter-plugins.org/wiki/WebDriverSampler/
Reference Image:
It is same as how do you do in other IDEs like eclipse.
you can see below code
//try block starts here
try{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("element"))).click();
}
catch(Exception e)
{
WDS.log.info("Exception is : " +e);//you can print the exception in jmeter log.
}
double quotes should be replaced with the single quote if you are using javascript Since the BeanShell is easy and it is similar to java use BeanShell as much as possible

validation step by step

I have an aspx page with three textbox controls, and i want to do validation for all.
i want to show the error message in a sequence,
for example if i left all three text boxes empty and click on submit button,
first it will show error message for first text box and then when i fill the first textbox and click again save then it shows the error message for the second textbox and so on.
that means i only want to show one error message at a time after clicking the submit button.
can you people suggest me the way.
You could do it though checking on submission of the form and posting back to a literal with error messages. Postback validation is better than just relying on javascript in any case.
So, depending on the level of checks you want to employ, you could do something like:
protected void btnSubmit_Click(object sender, eventArgs e)
{
if(String.IsNullOrEmpty(txtBox1.Text))
{
ltError.Text = "Sorry, error message for box1";
return;
}
}
Obviously you'd work in more checks and after passing stage1 you'd move on to stage 2. Not great from a user experience but would work.
you can return a function value like this
public string CheckValidation()
{
if (txtFirstName.Text.Trim().Equals(string.Empty))
return "Please enter firstname";
if (txtLastName.Text.Trim().Equals(string.Empty))
return "Please enter lastname";
}
and so on as per your validation fields.
Hope this helps you
Can you use the AJAX control toolkit? The VaidatorCallout controls behave this way and you get a nice little balloon indicating where the error is.
ASP.NET Validator Callout
I'd recommend an <asp:CustomValidator> control for each textbox. You can use something like the following for the custom validation routines:
var textBox1IsValid = function textBox1IsValid(sender, args) {
var tb = document.getElementById('TextBox1'),
resultOfValidation = false;
//do validation, modifying resultOfValidation as needed.
arg.IsValid = resultOfValidation;
return resultOfValidation;
},
textBox2IsValid = function textBox2IsValid(sender, args) {
var tb = document.getElementById('TextBox2'),
resultOfValidation = false;
//do validation, modifying resultOfValidation as needed.
//return either the validity of TextBox2
//or (if TextBox1 is not valid) return true so the
//validator for TextBox2 doesn't fire.
arg.IsValid = resultOfValidation || !textBox1IsValid(sender, args);
return resultOfValidation;
},
textBox3IsValid = function textBox3IsValid(sender, args) {
var tb = document.getElementById('TextBox3'),
resultOfValidation = false;
//do validation, modifying resultOfValidation as needed.
//return either the validity of TextBox3
//or (if either TextBox1 or TextBox2 is not valid) return
//true so the validator for TextBox3 doesn't fire.
arg.IsValid = resultOfValidation || !textBox1IsValid(sender, args) || !textBox2IsValid(sender, args);
return resultOfValidation;
};
The advantage of this approach is that TextBox2 and TextBox3 will return as valid if their contents are valid or if TextBox1 is not valid. This will fire only one validator at a time, until all fields are valid. It's also a little more flexible as your custom validation routine can check for:
required field
pattern matching
value comparison
or any other validation that you need, all wrapped up into one function.
The downside is that you'll also need to duplicate the validation logic server-side.

Object reference not set to an instance of an object error

I have Default.aspx and Upload.aspx.
I'm passing Id through query string to default.aspx(like:http://localhost:3081/default.aspx?Id=1752).In default page i have a link button to open the upload.aspx to upload file.When i use the Request.QueryString["Id"] in upload.aspx,it is showiing error as "Object reference not set to an instance of an object".I'm dealing with RadControls.
To open when i click a link(OnClientClick="return ShowAddFeedBackForm()") i have code like:
<script>
function ShowAddFeedBackForm() {
window.radopen("Upload.aspx", "UserListDialog");
return false;
}
</script>
I'm using detailsview in upload page with a textbox and a fileupload control.
code to bind when a file upload in upload.aspx
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
string qString = Request.QueryString["Id"].ToString();
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
//string qString = Request.QueryString["Id"].ToString();
//int Projectid = Convert.ToInt32(Session["ProjectId"]);
ProTrakEntities objEntity = new ProTrakEntities();
TextBox txtTitle = DetailsView1.FindControl("txtTask") as TextBox;
//RadComboBox cmbStatus = DetailsView1.FindControl("cmbStatus") as RadComboBox;
//var id = (from project in objEntity.Projects where project.ProjectId == Projectid select project).First();
RadComboBox cmbTaskType = DetailsView1.FindControl("cmbTasktype") as RadComboBox;
//RadComboBox cmbTaskPriorty = DetailsView1.FindControl("cmbPriority") as RadComboBox;
string Description = (DetailsView1.FindControl("RadEditor1") as RadEditor).Content;
var guid = (from g in objEntity.Projects where g.ProjectGuid == qString select g).First();
int pID = Convert.ToInt32(guid.ProjectId);
ProjectFeedback objResource = new ProjectFeedback();
objResource.ProjectId = pID;
objResource.Subject = txtTitle.Text;
objResource.Body = Description;
objResource.CreatedDate = Convert.ToDateTime(System.DateTime.Now.ToShortDateString());
objResource.FeedbackType = cmbTaskType.SelectedItem.Text;
objEntity.AddToProjectFeedbacks(objResource);
objEntity.SaveChanges();
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind('navigateToInserted');", true);
}
}
Getting error at querystring statement-"Object reference not set to an instance of an object"
The query string is not inherited when you open a new page. You have to include the id in the URL, i.e. Upload.aspx?id=1752.
Edit:
A simple solution would be to just copy the search part of the page URL:
window.radopen("Upload.aspx" + document.location.search, "UserListDialog");
However, typically you would use the id value that you picked up from the query string in the server side code and generate client code to use it.
I am not sure but if I had to guess I would question whether the window object has been instantiated at the time you call radopen in the script section of your page. You should put a msgbox before the call window.radopen() call to print the contents of the window object if it is null that is your problem otherwise this will take more digging. Just my two cents.
I also noted that if the guid query returns no results the call to .First() will cause this error as well. Just another place to check while researching the issue.
There is one last place I see that could also throw this error if the objEntities failed to construct and returned a null reference then any call to the properties of the object will generate this error (i.e objEntitiey.Projects):
ProTrakEntities objEntity = new ProTrakEntities();
var guid = (from g in objEntity.Projects where g.ProjectGuid == qString select g).First();
This error is occurring because, as the other answerer said, you need to pass the ID to the RadWindow since the RadWindow doesn't know anything about the page that called it. You're getting a null reference exception because the window can't find the query string, so it's throwing an exception when you try to reference .ToString().
To get it to work, make your Javascript function like this:
function ShowAddFeedBackForm(Id) {
window.radopen(String.format("Upload.aspx?Id={0}", Id), "UserListDialog");
return false;
}
In the codebehind Page_Load event of your base page (ie, the page that is opening the window), put this:
if (!IsPostBack)
Button.OnClientClick = string.Format("javascript:return ShowAddFeedBackForm({0});", Request.QueryString["Id"]);
Of course, Button should be the ID of the button as it is on your page.

how to get value of hidden field value?

I have an asp.net application in which i want to get the value of hidden field value in to my code behind page.
Actually its executing code first and after that its executing javascript.
That's why i am not getting the value. Please tell me how can i get the value.
Javascript
function changeCSS(colr,wd)
{
chooseStyle(colr, wd)
var CssTitle = document.getElementById('<%= hdCssTitle.ClientID %>');
CssTitle.value = colr;
}
and code behind page is
protected void Page_Load(object sender, EventArgs e)
{
string CssTitle = hdCssTitle.Value;
}
Values changed in Javascript won't be reflected in your server side script. You would have to make an Ajax post to your code-behind to obtain it.
Get hidden field and access that value like this string s = hidden.Text

Catch upload of to big files

Asp.Net has an upper limit for file uploads. I try to catch this situation on the server side. According to the documentation I found, it should be possible to override Application_Error in Global.asax, but it does not work for me. The second option would be to override OnError of the receiving page, but that also does not work.
Can anybody show some working code on how to catch this error on the server side?
Put following in Golobal.asax.cs:
void Application_Error(Object sender, EventArgs e)
{
HttpException ex = Server.GetLastError() as HttpException;
if (ex != null)
{
if ((ex.GetHttpCode() == 500 || ex.GetHttpCode() == 400) && ex.ErrorCode == -2147467259)
{
Server.ClearError();
Response.Redirect("~/MaximumFileError.aspx", false);
}
}
}
This worked for me, but I'm not sure if it works for all cases.
Uploadify is a jquery and flash uploader that allows you to specify a max size for files to be downloaded. This way you can prevent the user from downloading the file in the first place and dont have to worry about catching it after.
Rather than catch the error can't you check the size of the file against the maximum size specified in the web.config file? You can use the following to get the max size:
System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
double maxFileSize = section.MaxRequestLength;
"Can anybody show some working code on
how to catch this error on the server
side?"
Nope. It's not possible to use code to catch this error, as it occurs before any code is started.
As far as I have found, you can't even specify an alternative error page for this error, the web server just refuses to accept the request when it's too large.
First you should understand few things about maxRequestLength. Using a server side approach validation you cannot predict what will be file size. Setting value to high is increasing the risk of DoS Attack.
I set in web.config maxRequestLength to 8MB:
<httpRuntime maxRequestLength="8192" executionTimeout="3600" />
I check in my code-behind of form if uploaded by user file is not greater than half of given in maxRequestLength, but this checking may never happen if the size of uploaded file turn out to be greater than max RequestLength specified in web.config, because the exception will be thrown. Such exception should be catch on the level of Global.asax. There I check whether the Exception is containing words identifying our problem, because System.Web.HttpUnhandledException can be thrown in many other situations! Good hint may be checking from which page the exception come, to be sure that we deal with certain form, what is important by redirecting user back to form.
void Application_Error(object sender, EventArgs e){
Exception wyjatek = Server.GetLastError();
if (wyjatek.InnerException != null && wyjatek.InnerException.Message.Contains("Maximum request length exceeded"))
{
Server.ClearError();
Response.Redirect("FormWithFile.aspx?alert=Za-duzy-plik");
}
}
If I recognize in Global.asax this exception I redirect user to the page with alert(given in GET).
In my code-behind of ASPX page:
First I retrive value of MaxRequestLength from web.config by this tree lines, and half it:
static System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
static HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
int maxFileSize = (section.MaxRequestLength/2)*1024;
Then in Action connected with insert button, I proceed as follows:
protected void InsertButton_Click(object sender, EventArgs e)
{
if (((FileUpload)FormView1.FindControl("FileUpload1")).HasFile) // WHEN USER WANT TO UPLOAD FORM WITH FILE (its, optional)
{
HttpPostedFile file = (HttpPostedFile)(((FileUpload)FormView1.FindControl("FileUpload1")).PostedFile);
int iFileSize = file.ContentLength;
if ((file != null) && (file.ContentLength > 0))
{
if (iFileSize > maxFileSize) // checking image SIZE!
{
MessageForUser.Text = "<h1 class=error>Bad File! File is to big!</h1>";
}
else
{
byte[] plik = ((FileUpload)FormView1.FindControl("FileUpload1")).FileBytes;
// HERE COMES CODE FOR INSERT OF FORM WITH FILE
MessageForUser.Text = "<h1>Insert was sucessfull</h2>";
}
}
}
else
{
// HERE COMES CODE FOR INSERT OF FORM WITHOUT FILE
MessageForUser.Text = "<h1>Insert was sucessfull</h2>";
}
}
In Page_Load I define also how to retrive communicate given by GET from Global.asax, to inform the user what happend.
if (Request.QueryString["alert"]!=null)
{
string temp = Request.QueryString["alert"].Replace('-',' ');
MessageForUser.Visible = true;
MessageForUser.Text = "<h1 class=error>ERROR: " + temp + "</h1>";
}
This solution has of course its drawbacks:
Still, we can be under DoS attack with 8MB files, what we recognize first at level of server, what is already very late.
The state of user form is lost in case of redirection from Global.asax, but this with some bit of code can be overcome.
User expirience is rather poor, because of checks on the server side, and by the load of many users, applicaiton can become slow.
Temporarly to the server come files even greater than 8MB, but such which manage in executionTimeout
Possible alternatives:
Use some flash technology to check on client side the file size
Use some stream techniques, to transfer bites in small packets, and in the moment, when given threshold is reached, throw own exception and handle it.
apropriate reading: Sending File in Chunks to HttpHandler

Resources