I am using the following to control user log in authentication. This redirects fine when the user is inactive or locked out, but when the user is deleted from the database, I get an error message...
"Object reference not set to an instance of an object" on this line...
If currentuser IsNot Nothing And currentuser.IsApproved = False Or currentuser.IsLockedOut = True Then
What could be causing this to happen?
Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
If User.Identity.IsAuthenticated Then
Dim currentuser As MembershipUser = Membership.GetUser()
If currentuser IsNot Nothing And currentuser.IsApproved = False Or currentuser.IsLockedOut = True Then
FormsAuthentication.SignOut()
FormsAuthentication.RedirectToLoginPage()
End If
If currentuser IsNot Nothing Then
Response.Redirect("~/media")
End If
End If
End Sub
Change the If condition to:
If currentuser IsNot Nothing Then
If currentuser.IsApproved = False Or currentuser.IsLockedOut = True Then
FormsAuthentication.SignOut()
FormsAuthentication.RedirectToLoginPage()
End If
Response.Redirect("~/media")
End If
You need to parathesize the second part and use OrElse/AndAlso, otherwise currentuser IsNot Nothing will not be applied to all parts of your if
So this will fix it:
If currentuser IsNot Nothing AndAlso (Not currentuser.IsApproved OrElse currentuser.IsLockedOut) Then
Don't use Or (and AND) but OrElse (and AndAlso) which will short circuit. That means it will not evaluate the second part if the first part was already true. Or (and And) on the other side will evaluate both parts always.
Since 'And' receives precedence over 'Or' the expression will
be evaluated as follows:
If
{
currentuser IsNot Nothing And currentuser.IsApproved = False //condition 1
Or
currentuser.IsLockedOut = True //condition 2
}
Then..
If current user is in fact nothing:
condition 1- will not fail, but condition 2 will throw
an exception since the code is trying to evaluate (nothing).somthing.
To fix the problem you'll have to add parentheses as shown:
If
currentuser IsNot Nothing //condition 1
And
(currentuser.IsApproved = False Or currentuser.IsLockedOut = True) //condition 2
Then..
Now, the 2nd condition will be evaluated only if the first condition is true.
Related
how can i validate textbox1 and textbox 2.
here is the thing i needed.
if i fill in textbox1 then i must fill in textbox2 if either one is empty must show error message.
if both both textboxes are empty then no error, proceed to the result
how to do that, can anyone show me how to do
-the bellow code is where i just validate the date either greater than or not
Private Sub cvCmpDate_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs) Handles cvCmpDate.ServerValidate
If CompareMyDate.CompareDate(txtDateStart.Text.Trim, txtDateEnd.Text.Trim) Then
cvCmpDate.ErrorMessage = "* Activation Start Date cannot greater than Activation End Date."
args.IsValid = False
End If
End Sub
Select Case True
Case String.IsNullOrWhitespace(txtDateStart.Text) AndAlso Not String.IsNullOrWhitespace(txtDateEnd.Text)
' Show Error
Case String.IsNullOrWhitespace(txtDateEnd.Text) AndAlso Not String.IsNullOrWhitespace(txtDateStart.Text)
' Show Error
Case CompareMyDate.CompareDate(txtDateStart.Text.Trim, txtDateEnd.Text.Trim)
cvCmpDate.ErrorMessage = "* Activation Start Date cannot greater than Activation End Date."
args.IsValid = False
End Select
Thanks in advance for looking at my post. I'm new to cookies. I figured they'd be easier to work with if I create a property for each key of the collection. I created a set of private properties to deal with getting/setting cookies so I keep control state between pages. Here's what I have:
Private Property CK_Settings(pKey As String) As String
Set(value As String)
If Request.Cookies("Settings") Is Nothing Then
Response.Cookies.Add(New HttpCookie("Settings"))
End If
Response.Cookies("Settings").Item(pKey) = value
End Set
Get
If Request.Cookies("Settings") Is Nothing Then
Response.Cookies.Add(New HttpCookie("Settings"))
End If
Return Request.Cookies("Settings").Item(pKey)
End Get
End Property
Private Property CK_rb1 As String
Set(value As String)
CK_Settings("rb1") = value
End Set
Get
If CK_Settings("rb1") IsNot Nothing Then
Return CK_Settings("rb1")
Else
Return Nothing
End If
End Get
End Property
Private Property CK_Jobs As String
Set(value As String)
CK_Settings("Jobs") = value
End Set
Get
If CK_Settings("Jobs") IsNot Nothing Then
Return CK_Settings("Jobs")
Else
Return Nothing
End If
End Get
End Property
Private Property CK_rb2 As String
Set(value As String)
CK_Settings("rb2") = value
End Set
Get
If CK_Settings("rb2") IsNot Nothing Then
Return CK_Settings("rb2")
Else
Return Nothing
End If
End Get
End Property
Private Sub SetCookies()
Me.CK_rb1 = Me.rb1.SelectedIndex.ToString
Me.CK_Jobs = Me.ddlJobs.SelectedIndex.ToString
Me.CK_rb2 = Me.rb2.SelectedIndex.ToString
End Sub
Private Sub GetCookies()
If Me.CK_rb1 IsNot Nothing Then
Me.rb1.SelectedIndex = Me.CK_rb1.ToInteger
End If
If Me.CK_rb2 IsNot Nothing Then
Me.rb2.SelectedIndex = Me.CK_rb2.ToInteger
End If
Me.ddlJobs.SelectedIndex = Me.CK_Jobs.ToInteger
End Sub
I get no compiler/runtime errors, but the cookies aren't being set at all. I've also added 2 subs for easier setting/getting. I found this when researching online, but I don't think it's relevant. ANY help at all is GREATLY appreciated!
UPDATE
I was able to get the radiobuttonlist (rb) to retain state. I'm having issues with the dropdownlist (ddl) retaining state. It's worth noting that the dropdownlist is a custom control. Also, I changed the names to something less of consequence.
The dropdownlist implemented overridden method that I was accounting for. As soon as I figured this out, I was able to get the ddl to retain state.
I am debugging some code in an ASP.net web application project.
I have an If/Else statement nested in a Try/Catch block. Whenever an error occurs within the If block, rather than immediately jumping into the Catch block, it falls into the Else block.
I have stepped through the code repeatedly to witness this happening. When I throw an exception within the if block, I would expect logic to flow into the catch block, and I would never expect to see the if block get hit, and then the else block get hit, that seems to completely defeat the purpose of the if/else logic.
Here is the code in question:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
LoadDocument()
End Sub
Private Sub LoadDocument()
Dim taDocuments As New SecureTableAdapters.IndividualDocumentsTableAdapter
Dim dtDocuments As New Secure.IndividualDocumentsDataTable
Dim iDocumentID As Integer = CInt(Request.QueryString("iDocumentID"))
Dim sFileName As String
Dim isMac As Boolean = clsApplication.isMac(Request.Browser.Platform)
Dim bDownloaded As Boolean = False
Try
If taDocuments.FillBy_IndividualDocumentID(dtDocuments, iDocumentID) > 0 Then
Dim oRow As Secure.IndividualDocumentsRow = dtDocuments.Rows(0)
sFileName = "Statement-" & oRow.sFileNumber & ".pdf"
If oRow.sDocumentName.ToUpper.Contains("LEDES") Or oRow.sDocumentName.ToUpper.Contains("TEXT") Then
sFileName = sFileName.Replace("pdf", "txt")
End If
Dim b As Byte() = Nothing
If oRow.IsbExtractedNull = False AndAlso oRow.bExtracted Then
Dim sHost As String = "206.220.201.175"
Dim sPath As String = String.Format("/Legacy/{0}/{1}/{2}.pdf", oRow.iFirmID.ToString, "Individuals", oRow.iIndividualDocumentID.ToString)
b = DownloadDocument(sHost, sPath)
If b Is Nothing Then
'When this line is hit, logic jumps to the else block with the comment below
Throw New Exception("FTP Download Failed")
Else
bDownloaded = True
End If
Else
bDownloaded = False
End If
If bDownloaded = False Then
b = getImage(iDocumentID, "oPDF", "iIndividualDocumentID", "tblIndividualDocuments")
If b Is Nothing Then
Throw New Exception
End If
End If
If isMac Then
Response.ContentType = "application/x-macbinary"
Else
Response.ContentType = "application/octet-stream"
End If
Response.Expires = 0
Response.AddHeader("Content-Disposition", "attachment; filename=""" & sFileName & """")
Response.BinaryWrite(b)
Else
'--->When the exception occurs, logic jumps to this else block
Throw New Exception
End If
Catch ex As Exception
Response.Write("Sorry, that statement could not be located. Please try again, or call us at xxx.xxx.xxxx for further information.")
clsApplication.EmailError("An error occurred downloading a statement: " & vbCrLf & ex.Source & vbCrLf & ex.Message & vbCrLf & ex.StackTrace)
End Try
End Sub
How is this possible?
It sounds like you're using the debugger with Optimizations still turned on. This can cause the Step Traceing to act in seemingly illogical and even impossible ways. This is caused because after the optimizer moves the code and variables around and consolidates different statements, there is no longer a simple or straight-forward relationship between the lines of source-code and the executable instructions.
Sounds like the code you're debugging against might be out of sync with the code that's executing. Try rebuilding the whole solution.
I think you are probably mistaken:
Try the following in simple vb .net winforms program.
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
Dim doIt As Boolean = True
If doIt Then
Throw New Exception("throwing that stuff")
Else
MsgBox("in here - how did that happen?")
End If
Catch ex As Exception
MsgBox(String.Format("That makes sense. Exception is: {0}", ex))
End Try
End Sub
End Class
How do I set the LastLoginDate of the Membership user class to the UTC time instead of the server time?
The following code does not work even though LastLoginDate is a settable property.
Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
Dim user As MembershipUser = Membership.GetUser(Login1.UserName)
If user IsNot Nothing Then
If Membership.ValidateUser(Login1.UserName, Login1.Password) Then
user.LastLoginDate = DateTime.UtcNow()
e.Authenticated = True
End If
End If
End Sub
I also tried to do in Login1_LoggedIn and Login1_LoggingIn events and no luck.
Perhaps you need to make a call to UpdateUser to save the change
http://msdn.microsoft.com/en-us/library/system.web.security.membership.updateuser.aspx
Membership.UpdateUser(u)
You need to pass the modified user variable to MembershipUser.UpdateUser.
From the MSDN article on LastLoginDate:
You can also modify the last login date by setting the LastLoginDate property of a MembershipUser and passing the modified MembershipUser object to the UpdateUser method.
In your code:
If Membership.ValidateUser(Login1.UserName, Login1.Password) Then
user.LastLoginDate = DateTime.UtcNow()
MembershipUser.UpdateUser(user)
e.Authenticated = True
End If
I am using a WizardControl in .NET 2.0. On the first Step (which is set to StepType="Start") when the next button is clicked, I run server-side validation code. But, no matter what I do it keeps going to the next step. Here is my code:
Protected Sub Wizard1_NextButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.NextButtonClick
Dim oUser As New BE.User
Select Case Wizard1.ActiveStepIndex
Case 0
If Membership.FindUsersByName(UserName.Text).Count = 0 Then
oUser.UserName = UserName.Text
oUser.Password = Password.Text
oUser.Email = Email.Text
Wizard1.ActiveStepIndex = 1
Else
Wizard1.ActiveStepIndex = 0
ErrorMessage.Text = "user name already in use"
End If
Case 1
Case 2
End Select
End Sub
You can write e.Cancel=true
if you are working in any wizard event. Here "e" is an alias for WizardNavigationEventArgs
The Wizard control's NextButtonClick event has a
"WizardNavigationEventArgs" parameter that contains a "Cancel" property
help to cancel the current next navigation operation.
courtesy of
Steven Cheng Microsoft Online Support
As others have mentioned, you can use the Cancel property of the WizardNavigationEventArgs. Here's your code updated to reflect that:
Protected Sub Wizard1_NextButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.NextButtonClick
Dim oUser As New BE.User
Select Case Wizard1.ActiveStepIndex
Case 0
If Membership.FindUsersByName(UserName.Text).Count = 0 Then
oUser.UserName = UserName.Text
oUser.Password = Password.Text
oUser.Email = Email.Text
Wizard1.ActiveStepIndex = 1
Else
Wizard1.ActiveStepIndex = 0
ErrorMessage.Text = "user name already in use"
' Set the Cancel property to True here
e.Cancel = True
End If
Case 1
Case 2
End Select
End Sub