Having issue with View State on ASP.net Website - asp.net

I have just moved my dev website to a new computer and have got most of the web pages working. The only web pages that won't work are pages that have a postback. I know the code works fine which is why I think it is being caused by the view state. I keep getting this error:
Value cannot be null.
Parameter name: inputString
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.ArgumentNullException: Value cannot be null.
Parameter name: inputString
This is the function where the error is being thrown:
Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
'Dim vState As String = Me.Request.Form("__VSTATE")
PageStatePersister.Load()
Dim vState As String = PageStatePersister.ViewState.ToString
If Not vState Is Nothing Then
Dim bytes As Byte() = System.Convert.FromBase64String(vState)
bytes = vioZip.Decompress(bytes)
Dim format As New LosFormatter
Return format.Deserialize(System.Convert.ToBase64String(bytes))
Else
Return Nothing
End If
End Function
Does anyone know why it is giving me this error? I can't find what is being passed to it that might be null, but I know the code itself does not pass any null values. Let me know if you need any more information. Thank you in advance for your responses.

Check if the page has EnableViewState="true"
And verify the site-wide setting in web.config -
<pages enableViewState="true" enableViewStateMac="true" ... />

Related

Website - The type initializer for 'Static Class' threw an exception

I have a VB.NET website project. In one of the pages, during a button click, it is supposed to load a telerik RadGrid with data. It works fine on my local machine. However when I deploy it to pre-production on a server, it throws the following error.
The type initializer for 'Utility' threw an exception
Utility is a Static class and while calling any members of the static class (either public static functions or public static variables) I was receiving this error.
Here is the code snippet:
Partial Class Session
Inherits System.Web.UI.Page
Protected Sub RadGrid1_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemDataBound
If TypeOf e.Item Is GridDataItem Then
Dim testString As String = String.Empty
Dim encryptString As String = String.Empty
Try
encryptString = Utility.EncryptString(cellValue.ToString())
testString = Utility.test
Catch ex As Exception
Logger.getInstance().log("Value1" & cellValue.ToString() & "Value2" & testString)
Finally
End Try
End If
End Sub
End Class
In my Utility.vb, this is what I have:
Public Class Utility
Public Shared test As String = "hello"
Public Shared Function EncryptString(ByVal strEncrypted As String) As String
Try
Dim b As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(strEncrypted)
Dim encryptedConnectionString As String = Convert.ToBase64String(b)
Return encryptedConnectionString
Catch ex As Exception
Logger.getInstance().log("Error occurred in Utility.vb while executing EncryptString method. \nSOURCE: " & ex.Source.ToString() & "\nMESSAGE: " & ex.Message.ToString() & "\nTARGETSITE: " & ex.TargetSite.ToString() & "\nSTACKTRACE: " & ex.StackTrace.ToString())
Logger.getInstance().log("\nstrEncrypted: " & strEncrypted)
Finally
End Try
End Function
End Class
From my logging statements, I realized that the error is happening right when I call the Utility class because none of the logging statements I added into the EncryptString() function are being shown in my logs.
I tried commenting out the code for EncryptString() function and added just a public static string variable called test in my Utility class, and tried accessing it from my code from Session.aspx.vb. That string value was not being returned as well.
By the way, all of my code is in the same website project. The error is driving me crazy for past 2 days. Like I mentioned, it works fine on my local machine, but fails only on the pre-prod server. The code was written using an older framework (3.5 I believe) and then we upgraded to 4.6.2 and migrating to new servers. We are facing this issue during the migration process on the new server.
OK, so I figured out the issue. At the beginning of the Utility.vb class there were some unsupported cryptographic algorithm variable declarations.
Private Shared DES As New TripleDESCryptoServiceProvider
Private Shared MD5 As New MD5CryptoServiceProvider
FIPS compliance is turned on, on the server and we already knew these algorithms were non-compliant with the latest .net frameworks. But I didn't realize even just these declarations would throw a misleading error, when they were not really being used in my function calls.
When I commented out those parts of the code, it started working fine.
Check the InnerException property of the exception. Any time a class initializer fails the original exception should be set as the InnerException property of the unhandled exception.
If you want a truly static class, you need to make it a module, in VB.Net.

ASP.NET web service returns 400

If I de-serialize the data and an error occurs later in the update process (for example: the change fails to meet a database constraint). I'd like to report something useful to the end user here, but it looks like .NET is swallowing the error. Any idea why?
<WebInvoke(method:="POST", uriTemplate:="changes", bodyStyle:=WebMessageBodyStyle.Bare)>
Public Function PostChanges(body As Stream) As String
Try
' This returns 500 Server Error (with wrapped exception)
'Throw New Exception("TEST")
Dim data As String = ""
Using reader As New StreamReader(body)
data = reader.ReadToEnd()
End Using
' This returns 400 Bad Request
'Throw New Exception("TEST")
' Code handling data removed (no error if exceptions are removed)
Catch ex As Exception
Throw New WebFaultException(Of DisplayError)(New DisplayError(ex.Message, ex.StackTrace), Net.HttpStatusCode.InternalServerError)
End Try
Apparently, StreamReader disposes of its underlying Stream object which causes problem if your code has the temerity to break normal flow by raising an exception.
So, now I'm using OperationContext.Current.RequestContext.RequestMessage.ToString, which has its own problems but at least I'm not choosing between messed up error logging or a resource leak.

Custom Exception with Entity Framework and Repository Pattern

I am following this Asp .Net tutorial as a guide:
http://www.asp.net/web-forms/tutorials/continuing-with-ef/using-the-entity-framework-and-the-objectdatasource-control-part-2-adding-a-business-logic-layer-and-unit-tests
I have created a custom error to prevent duplicate records on insert and update
Public Class DuplicateAgencyException
Inherits Exception
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
I have created a validation method that checks for duplication on insert or update:
Public Sub ValidateAgencyName(ByVal agency As agency_temp)
If Not IsNothing(agency) Then
Dim duplicateAgency As agency_temp = AgencyRepository.GetAgencyByName(agency.agency_name).FirstOrDefault()
If Not IsNothing(duplicateAgency) AndAlso duplicateAgency.agency_id <> agency.agency_id Then
Throw New DuplicateAgencyException(String.Format("Agency: {0} already exists.", duplicateAgency.agency_name))
End If
End If
End Sub
I run a unit test to insert a record, and purposefully insert a duplicate, and it throws the correct error. Now I need to handle this error with the ObjectDataSource that displays this data, such as OnInserted and OnUpdated, but I can't even get to that point. When I insert a record, I get the error assistant telling me that DuplicateAgencyException was unhandled by user code. Do I need a try...Catch there? (I did try that to no avail).
I believe you need to wrap your exception within the methods referenced by the events you mention in a try catch block as you suggest. You should wrap the existing code like so
MethodName(params)
《
try 《 /// existing code
》
catch (ExceptionType ex) 《
/// error handling code
》
》
If you post your event handling code and the aspx i can be more specific. Please excuse any errots wrote this on my phone.

Why do we get "Path not found" error while accessing vb code from classic asp page?

Could you please give your suggestions to the below problem:
I am working on a old project which was developed using traditional ASP and VB6.0.
I have registered the dll in component services. After creating the object in first line (in the code snippet below), when trying to call Login() method, it is giving the "Path not found" warning/error and I am not able to continue executing it further.
Thanks in advance for your consideration and help...also please let me know if you need more information...
SET objSecurity = Server.CreateObject( Application("APP_CLASS") & "Security" )
SET ox = new XMLTool
userID = uCase(userID)
dataXML = ""
IF objSecurity.Login( sessXML, userID, pwd, datXML ) Then
ox.LoadXML dataXML
..........
..........
"Path not found" is usually an IO exception. Does the objSecurity.Login() method read or write any data to a file or directory that does not exist? What is happening inside the objSecurity.Login() method?
Alternately, is there another "benign" method of the objSecurity object that you can call to verify that the object lives? Something like:
Dim sTest As String = objSecurity.Version()
or
Dim sTest As String = objSecurity.Name()
or even
Dim bExists As Boolean = (objSecurity IsNot Nothing)
I know that .ToString() didn't exist in VB6, but that's the idea.
Let's narrow down the problem to either objSecurity object itself, or something inside the .Login() method.

Determine the error that caused a redirect in ASP.NET

I have an ASP.NET web form application. In the web.config associated with this application, I handle my custom error like so:
<customErrors mode="Off" defaultRedirect="error.aspx" />
When a user gets to the error.aspx page, I want to determine what error caused this page to get reached. Does anyone know how I can do this?
Thank you!
You get the exception object with the GetLastError method:
Exception ex = Server.GetLastError();
(Copied straight out of the code of our error page, which has logged several million errors so far... :)
You can do it using Server.GetLastError Method
Exception LastError;
String ErrMessage;
LastError = Server.GetLastError();
if (LastError != null)
ErrMessage = LastError.Message;
else
ErrMessage = "No Errors";
Response.Write("Last Error = " + ErrMessage);

Resources