Error while editing data in gridview in ASP.NET - asp.net

I am making an online bug tracking system(BTS) in ASP.NET. I am using Gridview for displaying the records on a web page. It is working properly in some web forms but in some web forms, i am getting error as given below when i click edit event of gridview. Please guide me to solve this error.
Server Error in '/BTS' Application.
Invalid postback or callback argument. Event validation is enabled using
<pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Just do this --> EnableEventValidation="false" like below
<%# Page Title="" Language="C#" MasterPageFile="~/shirish.master" AutoEventWireup="true"
CodeFile="s.aspx.cs" Inherits="_s" EnableEventValidation="false" %>

This is a typical error in ASP.NET when request validation fails. The most common scenario is when you are issuing a postback and one of the input controls (usually a TextBox) contains html or javascript code. As the error message states, there's several ways you can bypass this validation:
By disabling request validation at the page level which be achieved by setting the EnableEventValidation property of the page directive to false. Note that you can do the same site-wide from the web.config file
By registering the required control for event validation using the ClientScriptManager.RegisterForEventValidation method
If you use the first approach, you will be turning off event validation which means you will be relaxing some of the built-in security features. On the other hand, the second approach is a bit clumsy because it requires to anticipate the values allowed by the control

Related

How to validate Request.RawUrl in Application_BeginRequest event in Global.asax.cs file?

Some bots are requesting URLs like www.example.com/test-</p><p>they-are-angry... which is creating A potentially dangerous exception in my asp.net application.
I need to validate the HttpContext.Current.Request.RawUrl in Application_BeginRequest event of Global.asax.cs file and if it is invalid I will redirect to another error page.
I do NOT want to set validateRequest="false" or requestValidationMode="2.0" but want to redirect to a particular error page if Request.RawUrl is invalid.
How to achieve this? Is there any Asp.Net predefined method to validated this URL?
Any help is highly appreciated!
If you want to just redirect to an error page, you can simply configure customErrors or implement global error handlers as detailed in existing post and on MSDN.
However, if you want to delay validation until later, such as Application_BeginRequest, you can disable request validation and invoke it explicitly, as mentioned in Imran's blog:
1. set requestValidationMode="2.0"
2. invoke Request.ValidateInput()
protected void Application_BeginRequest()
{
Request.ValidateInput();
var q = Request.QueryString;
}

Asp.net Event code 3003

My event log has thousands of entries for code 3003 which says "A validation error has occurred.". I am properly handling the validation on server side and error is caught in global.asax and proper message is shown to the user. I don't want to add code to handle the characters on client side by javascript or turning on ValidateRequest=false
My concern is only the event log entries and is there any way I can stop asp.net not to log event 3003 in event log?
Just add:
<pages validateRequest="false" enableEventValidation="false"/>
To your web.config to apply it to the whole site.
Edit:
Goes in the System.web section.

ASP.NET Common Error Page Best Practises

I am working on an ASP.NET web application. I am implementing the logging framework for the entire application.
web application has around 7-8 pages and is a simple CRUD operations web application.
Its an Azure hosted application. Following is the approach i am following for logging and exception handling.
1) Added Try...Catch blocks in the Data Access Layer, and Click events.
2) Upon catching errors, I am propagating the exceptions upto the Globabl.asax leve, and in Application_Error event logging the error into Event Logs and Trace Logs.
3) After this in the Global.asax file I am Redirecting to an Error Page to show a User Friendly Message and link to the failed page.
4) Just wanted to know whether is it a good approach to do this.
Thanks Friends.
Are you actually handling exceptions on the DAL (ie, logging, trying to fix it, etc)? If not, then the try catch serves no purpose other than spinning cycles. The same is true for the click events, but it is not a bad practice to handle errors on the UI, even if you are not truly doing anything with them, as you will divert the user from the ugly error page to your own friendly message.
A single error page works fine, if you truly cannot handle the exception thrown. The upside is time to market, as you write precious little code to avoid showing the user an ugly message. The downside is the user misses context. I am not really up on the one size fits all exception handler, except as a backup (have an error I did not envision that got past my first line handler).
There is a variation of the common error page, if you are handling based on HTTP statuses and that is to use config.
Another pattern is to set up your own base page and have it work as an error handler. You can then set aside a container to fill when an error occurs. This approach works nicely for adding context, as the user still sees part of the page he was on, but you have given an error message, so he knows things have failed. I have seent this pattern used with a user control that is added to the container when an error occurs, but this is a bit more invovled, as you have to set up a table of codes and proper messages to show (which can be buggy in and of itself).
Why not using ASP.NET custom error pages ? You can specify each error page for each status code or you can specify a default redirect.
You can configure this in the web config and you are all set.
<customErrors defaultRedirect="GenericError.htm" mode="On">
<error statusCode="404" redirect="notfound.htm"/>
</customErrors>
You can configure it for showing the custom error pages to all users or only to remote users etc..
http://aspnetresources.com/articles/CustomErrorPages
I totally agree that you should log all errors in your catch block and write it to a log.
It sounds like you're kind of reinventing the wheel here. ASP.NET already includes things to help you achieve the desired result. Unless you need handling logic to cleanup after the errors, I wouldn't use try catch blocks. Have a look at the ASP.NET Health Monitoring Overview for logging errors. As far as presenting a custom error page see How to create custom error reporting pages in ASP.NET by using Visual C# .NET.
I think, You need not to use Exception Handling. Suppose You have a Presentation Layer and a Business Logic Layer/DataAccess Layer.
Upon facing the error in say Business Logic, it will move directly to Glogal.asax.cs file under Application_Error Event without going back to the calling function. Here you can log the error message like below....
HttpContext.Current.Server.GetLastError().InnerException.StackTrace
HttpContext.Current.Server.GetLastError().InnerException.Message
HttpContext.Current.Server.GetLastError().InnerException.Source
HttpContext.Current.Server.GetLastError().InnerException.TargetSite.DeclaringType.FullName
HttpContext.Current.Server.GetLastError().InnerException.TargetSite.DeclaringType.Name
HttpContext.Current.Server.GetLastError().InnerException.TargetSite.DeclaringType.Namespace
Now in the Web Config you can write code to redirect the user on some default page like below.
<customErrors defaultRedirect="ErrorPage.htm" mode="On">
<error statusCode="404" redirect="ErrorPageNotFound.htm"/>
</customErrors>

Google Adwords tracking cookie triggers ASP.NET Request Validation exception

Sorry for my English.
I have a strange problem.
When user click adword link, Google write tracking cookie like that
1813234232.1302674912.30.51.utmgclid=CcgezrsXjagCFcs-zAod_h2oCQ|utmccn=(not set)|utmcmd=(not set)|utmctr= CAA:89 AB0=40#B%20>:
In keyword section(utmctr) there is bad braskets, that cause request validation exception
A potentially dangerous Request.Cookies value was detected from the client (__utmz="...0=40#B%20> at System.Web.HttpRequest.ValidateCookieCollection(HttpCookieCollection cc)
Is there any way to solve this problem without turning off request validation?
Edited
I'm probably found obvious solution: write own request validation module http://jefferytay.wordpress.com/2010/04/15/creating-your-own-custom-request-validation/
By default asp.net validate and check the data for potential attacts.
You can disable this automatic validation by set validateRequest="false" ether on page
<%# Page validateRequest="false" %>
ether on web.config that affect all pages.
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
The only think that you need to check by your self after that, is if someone enters any script data to your inputs. Your inputs then need to check out when you render them on the page, and when you enter them on the database.

ASP.NET MVC2 master page and authentication

Update: I can't delete this question, because the answer has been upvoted, yet it is not at all the answer to what I'm asking. I'd like to delete this, as it has been a week with no answer, and it's just dragging down my accept %. Thanks.
I have a strongly typed master page that includes information that is based on the currently authenticated user's UserId:
(Guid)Membership.GetUser().ProviderUserKey
Every other normal action/view would require the user to be authenticated prior to it being viewed, which means the user's information is guaranteed to be available.
The problem is, I'm only getting null reference exceptions when I attempt to access the user's info. from the site's master page. I'm guessing this is because there isn't such thing as an [Authorize] attribute that applies to master pages.
Do I have this wrong? Is there another possible cause?
Simple example:
My site's various pages all use a view model object that inherits the master page view model:
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<Models.MasterViewModel>" %>
the authenticated user object is a property of this base view model. All pages require authentication, so anyone who isn't is redirected to the login view, which has been working flawlessly. So a simple attempt to make use of a user's property in a view is thus:
<%= Model.UserName %>
which I'll put in one of the views, as well as in the site's master view.
When the user is already authenticated, all works as it should, with the UserName being printed twice on the page. When the auth ticket is expired, or a new user comes along however, the page will not redirect to the login, but instead generate an exception that complains of a null reference coming from the <%= Model.UserName %> in the master view.
When I remove the <%= Model.UserName %> from the master view, and leave it in the normal view, it redirects as it should, without throwing the error.
I hope this is somewhat more clear.
Edit:
Maybe someone could offer a better way to access the authenticated user's information in the master page?
Edit #2:
I would be very interested to see any example of an authenticated user's info being accessed in the master page...this is a real head-scratcher for me.
Update:
I haven't accepted the answer because I'm quite familiar with how I can test whether or not a user is authenticated. I am curious to know why no redirection to the login page is taking place.
It's not because of the master page.
Membership.GetUser() will return the current logged-on membership user. If no user is logged in it will return null and that's what is causing your problem.
you can use an if statement in your master page to check if the user is logged in or not before using any user's info.
if(Membership.GetUser() != null )
{
// Use User Info.
}
The only way i manage to reproduce this error is if i add the violating codeblock to a masterpage that is referenced from pages that does not require auth, then look at'em without signing in.
If your masterpage is not used on your logon-page, it could indicate something else is not entirely in place. How's your routing and authentication set up? If your View gets instantiated before the redirect, so will your masterpage, which could provoke this behaviour.
not sure if this still applies in mvc2, but have you tried defining the loginUrl attribute in your web.config?
<authentication mode="Forms">
<forms loginUrl="/user/login" />
</authentication>
<authorization>
<deny users="?" />
</authorization>

Resources