Invalid Cast Exception calling SqlMembershipProvider GetUser - asp.net

I am implementing authorisation on a web application using the ASP.NET SqlMembershipProvider, but it is randomly throwing an invalid cast exception when calling the GetUser method.
I can log in, and navigate the pages all fine, but than at random points, boom, it craps out, and throws the exception:
Unable to cast object of type 'System.Int32' to type 'System.String'
Looking at the stack trace you can clearly see it is being caused by the Membership Provider:
[InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.]
System.Data.SqlClient.SqlBuffer.get_String() +5002910
System.Data.SqlClient.SqlDataReader.GetString(Int32 i) +55
System.Web.Security.SqlMembershipProvider.GetUser(String username, Boolean userIsOnline) +1169
System.Web.Security.Membership.GetUser(String username, Boolean userIsOnline) +63
System.Web.Security.Membership.GetUser() +19
_Default.LoadLeadOverview() in \\file1\default.aspx.vb:169
_Default.Page_Load(Object sender, EventArgs e) in \\file1\default.aspx.vb:30
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
I have had a look around and found other people with the same issue, but no solution. Any thoughts would be welcome.

Whilst I haven't done anything to specifically resolve this issue, I haven't seen it in a couple of weeks. Looking back, I was testing the site in multiple browsers at the same time, with the same account, logging in and out a lot, and that seemed to be when then problem came up. Now all the CSS and other cross-browser stuff has been settled, I'm not using multi browsers so heavily, and not at the same time and it seems to be fine.

Is it possible some of your users have all digits as their username? It might be that auto type is boxing wrong somewhere along the way.

Related

Getting "The trust relationship between this workstation and the primary domain failed." error while debugging on long-working web page

Here's the short version of how I'm getting this error. Our company has a tool written in Aspx which is pretty barebones and used for handheld scanner devices. This page, when loaded detects to see if a user has logged on, if not, it prompts them to login, then it asks them to make a selection from a drop-down to specify their location and then it loads the main application menu.
For a long time, I've been able to run this application on my machine in debug mode. However, I'm getting a new error. When I run the application, I am prompted to login. I can login successfully and get to the location selector. On the next step, I can select my location from a drop-down and click continue.
On the back-end, there is a a redirect that takes you to home.aspx. Home.aspx is a blank page with a Menu user control. Both the Home page and the menu are super basic. I have put break points in both Page_Load methods and they execute entirely. After the home page and menu have loaded, something is breaking internally and I'm getting this error:
[SystemException: The trust relationship between this workstation and the primary domain failed.
]
System.Security.Principal.NTAccount.TranslateToSids(IdentityReferenceCollection sourceAccounts, Boolean& someFailed) +1271
System.Security.Principal.NTAccount.Translate(IdentityReferenceCollection sourceAccounts, Type targetType, Boolean& someFailed) +46
System.Security.Principal.NTAccount.Translate(IdentityReferenceCollection sourceAccounts, Type targetType, Boolean forceSuccess) +43
System.Security.Principal.WindowsPrincipal.IsInRole(String role) +135
System.Web.SiteMapProvider.IsAccessibleToUser(HttpContext context, SiteMapNode node) +193
System.Web.SiteMapNode.IsAccessibleToUser(HttpContext context) +18
System.Web.StaticSiteMapProvider.GetChildNodes(SiteMapNode node) +260
System.Web.XmlSiteMapProvider.GetChildNodes(SiteMapNode node) +29
System.Web.SiteMapNode.get_ChildNodes() +27
System.Web.UI.WebControls.SiteMapDataSource.GetNodes(SiteMapNode node) +57
System.Web.UI.WebControls.SiteMapDataSource.GetNodes() +347
System.Web.UI.WebControls.SiteMapDataSource.GetTreeView(String viewPath) +37
System.Web.UI.WebControls.SiteMapDataSource.GetHierarchicalView(String viewPath) +34
System.Web.UI.HierarchicalDataSourceControl.System.Web.UI.IHierarchicalDataSource.GetHierarchicalView(String viewPath) +11
System.Web.UI.WebControls.HierarchicalDataBoundControl.GetData(String viewPath) +26
System.Web.UI.WebControls.Menu.DataBindItem(MenuItem item) +50
System.Web.UI.WebControls.Menu.PerformDataBinding() +129
System.Web.UI.WebControls.HierarchicalDataBoundControl.PerformSelect() +111
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +76
System.Web.UI.WebControls.Menu.DataBind() +10
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +114
System.Web.UI.WebControls.Menu.EnsureDataBound() +35
System.Web.UI.WebControls.Menu.CreateChildControls() +109
System.Web.UI.Control.EnsureChildControls() +97
System.Web.UI.Control.PreRenderRecursiveInternal() +42
System.Web.UI.Control.PreRenderRecursiveInternal() +163
System.Web.UI.Control.PreRenderRecursiveInternal() +163
System.Web.UI.Control.PreRenderRecursiveInternal() +163
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +906
I have turned on in VS that is should break on all exceptions. It's not breaking on any call in my code and, in fact, it doesn't break on any exception. It just throws up this error in the browser.
I've tried Googling this error, but nothing seems to work. We use Web Auth with roles, so I'm not sure what's happening. My local machine (or my personal user account) is what's used to call Db calls, but I've had no trouble with that in the past. In fact, within SSMS, I can execute any SQL code I want from within our Dbs, so this isn't a database issue.
Any clue what could cause this? I know you guys like to see code, but in this context, this doesn't have anything to with my code. There is a binding method for the menu, however, I've put a breakpoint at the earliest point in that method. This is the method (within my code) that should execute next after the Page_Load call. That breakpoint never gets hit before I receive this error. I have no clue what's going on. Thanks.
I awoke this morning to try running gpupdate /force to see if that would help at all. I have no clue what changed, but it seems to have fixed the problem.

Index was outside the bounds of the array exception on GridView.LoadControlState after upgrading to ASP.NET 4

I've got a client with a legacy ASP.NET WebForms app that was, previously, running ASP.NET 2.0. The site needed a new feature that necessitated using a third-party component that required ASP.NET 4, so we moved his application from ASP.NET 2.0 to ASP.NET 4.0 and the move went smoothly except we're getting the following intermittent exception:
System.IndexOutOfRangeException
Index was outside the bounds of the array.
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Web.UI.WebControls.GridView.LoadControlState(Object savedState)
at System.Web.UI.Control.LoadControlStateInternal(Object savedStateObj)
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.maintenancetechnician_advancedsearch_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
There were some Stack Overflow questions on this, but all had to do with load balanced/multi-server environments and having this happen when a request bounced from one server with different settings than another (such as one having had some .NET SP installed and the other not).
But this is running in a single-server environment.
Moreover, this problem didn't start until the upgrade to ASP.NET 4. Searching hte ELMAH error logs reveals that this exception has happened 8 times today and not once prior to today (as far back as our logs go, at least, which is a month).
Any ideas on where to go from here?
I agree that posting code would help, but I think I may know what's happening. We ran into a similar issue a few months ago. It ended up being that the Gridview control had it's EnableViewState set to false. Check that viewstate is enabled on the grid and see if that clears it up.
This site has a decent description of what happens when the viewstate is off:
http://forums.asp.net/t/1026981.aspx?ObjectDataSource+GridView+Disabled+ViewState+Major+Concurrency+Issues+possible+solution+

Validation of viewstate MAC failed and anti XSRF issue

I know this was posted here so many times and had a valuable suggestions and suggested fixes. But none of them helped.
We have an e commerce site which is online ordering system. Our web site is hosted on IIS 7.0 with .net framework 4.0.(this is the only website running on IIS ). In our testing environment everything worked fine and we deployed it.
Now we are getting MAC ERROR when user is trying to access the site or if he is in the site and browsing to other pages, user is facing this error. Here is the stack trace.
Exception: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Stack Trace: System.Web.HttpException
Stack Trace:
at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString, Purpose purpose) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter2.Deserialize(String serializedState, Purpose purpose) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter2 formatter, String serializedState, Purpose purpose) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.pages_usagereports_index_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
We started getting this issue when we implemented a code to fix CSRF issue in the base page.
If we take out the code and tested with a user, we are not getting any error.
So far we have tried these solutions
1) Applied machine key to the website even though we are not web farm environment.
2) We don’t want to disable the enableviewstate to false or the viewstateencryption mode to never as it is preferred not to do that. We even tried this but didn’t help.
3) We tried assigning different combinations for the base.viewstateuserkey like combination of userhostaddress and user Agent but it didn't help.
4) We used Microsoft .net web protection library from this link
http://software-security.sans.org/developer-how-to/developer-guide-csrf
After this we started getting another error
Inner Exception Type: System.InvalidOperationException
Inner Exception: Validation of Anti-XSRF token failed.
Inner Stack Trace:
at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.signin_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Now we are getting two errors. MAC error and Anti XSRF error.
Searched on this error and I saw number of posts but i tried them. None of them helped.
Any suggestions on this are much appreciated.
Thanks in advance
The MAC for the ViewState is derived using the ANtiXsrfTokenKey generated in your master page. If the token is not present when the user accesses your site (cookies disabled or the value in the cookie changed or deleted) then the page will generate a new token. What then happens, if there is a ViewState in the page being posted back, is that the MAC will be checked with the new Token and won't match the old token, that is the first error you can see.
The Xsrf check in your master page is slightly confusing but uses the Xsrf token stored in a cookie and matches it to the value stored in the page. Usually these will match but if another site attempts to make an illegal request to your site, their site won't send the Xsrf cookie and the check will fail. The reason that this is confusing is that if you have a ViewState, this will fail before the Xsrf check.
Another issue with the Xsrf check is that it uses the logged in user's name as part of the check. If a user is logged in and then the auth cookie is deleted or expires, this part of the check will fail and you will see an Xsrf failure which is misleading, the real error is that "the authentication has expired causing the Xsrf check to fail".
I have re-worked the functions in Site.Master.cs several times to make these errors more clear.
Hope that helps.

Getting lots of "Object reference not set to an instance of an object." errors on Page_Load

we are getting a large amount of errors being reported from our website.
in Debug mode we are not seeing any and we cant seem to find a pattern.
about 1 in every 50-100 pageviews experience the error.
Any help would be greatly appreciated! thanks!
Error
Object reference not set to an instance of an object.
StackTrace
at _Default.Page_Load(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Without specifics it may be hard to diagnose. You could try to add more debug info into your release build in your project options for release configuration - this may then give you a line number.
Add some logging into there either through log4net or trace.write to try to get some more info out of this.
Is page_load accessing any httpcontext, cache, session, or application values?

ASP.NET: "The resource class for this page was not found."

Myself and a colleague have recently upgraded to Windows Vista, and have been using it to develop ASP.NET applications with Visual Studio 2008 without many issues. And up until this morning, I had been managing to use local resources fine too.
However, this morning, my application suddenly stopped working with local resources, in the sense that any controls with a meta:resourcekey attribute suddenly display an empty string. At first, I thought it was something I had done to the application, so I created a brand new web application, added a label to an ASPX page, and generated a local resource from it. But running it has the same issue - the text simply isn't displayed. See attached screenshot for the example, and its output.
However, running it on my colleague's machine (who also has Vista), works without issue.
Incidently, if I try to get the value in the code behind, it throws this exception:
Server Error in '/Resources' Application. The resource class for this page was not found. Please check if the resource file exists and try again. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The resource class for this page was not found. Please check if the resource file exists and try again.
Source Error:
Line 12: protected void Page_Load(object sender, EventArgs e) Line 13: { Line 14: object x = HttpContext.GetLocalResourceObject("~/Default.aspx", "lblTestResource1.Text"); Line 15: } Line 16: }
Source File: C:\inetpub\wwwroot.Net2\Standalone\Resources\Resources\Default.aspx.cs Line: 14
Stack Trace:
[InvalidOperationException: The resource class for this page was not found. Please check if the resource file exists and try again.] System.Web.Compilation.LocalResXResourceProvider.CreateResourceManager()
+2468866 System.Web.Compilation.BaseResXResourceProvider.EnsureResourceManager()
+20 System.Web.Compilation.BaseResXResourceProvider.GetObject(String resourceKey, CultureInfo culture) +15 System.Web.Compilation.ResourceExpressionBuilder.GetResourceObject(IResourceProvider resourceProvider, String resourceKey, CultureInfo culture, Type objType, String propName) +21 System.Web.HttpContext.GetLocalResourceObject(String virtualPath, String resourceKey, CultureInfo culture) +38 System.Web.HttpContext.GetLocalResourceObject(String virtualPath, String resourceKey) +6 Resources._Default.Page_Load(Object sender, EventArgs e) in C:\inetpub\wwwroot.Net2\Standalone\Resources\Resources\Default.aspx.cs:14 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
+14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive()
+50 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Version Information: Microsoft .NET Framework Version:2.0.50727.3074; ASP.NET Version:2.0.50727.3074
Anyone have any idea? The weird thing is that using resources was working. I have tried restarting my computer, and clearing my Temporary ASP.NET files - but the issue remains.
Many thanks
Steve
Okay, I did a system restore to a couple of days previously, and it works fine now. Bizarre, as I (knowingly) made no changes to system files or anything.
As an extreme measure you could try a repair installation of the .net framework...
I've never encountered or even heard of this problem before so I'm afraid I don't have a better solution.

Resources