query string is throwing exception for being null when its not - asp.net

Here is whats happening , If the user is logged in - this is called directly from Page_Load
Protected Sub EnterNewTransInDb()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("connstring").ConnectionString)
Dim comm As New SqlCommand("INSERT INTO tblRegisterRedirect (RegID , UserID, EventID, TimeStamp) VALUES (#RegID, #UserID, #EventID , getdate()) ;", conn)
Dim RegID As Guid
RegID = Guid.NewGuid()
Dim GIUDuserid As Guid
GIUDuserid = New Guid(HttpContext.Current.Request.Cookies("UserID").Value.ToString())
Dim GIUDevnetid As New Guid(HttpContext.Current.Request.QueryString("id").ToString())
comm.Parameters.AddWithValue("#RegID", RegID)
comm.Parameters.AddWithValue("#UserID", GIUDuserid)
comm.Parameters.AddWithValue("#EventID", GIUDevnetid)
Try
conn.Open()
Dim i As Integer = comm.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
Dim errors As String = ex.ToString()
End Try
Dim URL As String = Request.QueryString("url").ToString()
Response.Redirect(URL + "?aid=854&rid=" + RegID.ToString())
End Sub
This works great, but if their not logged in , then they enter their log-in credentials - this happens on Button_Click event, in the click event I call this function EnterNewTransInDb() , When I run it this time , after logging in - SAME CODE , it throws an exception - Object reference is null - referring to the querystring
Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click
'took out code SqlConnection onnection and SqlDataReader Code
dbCon.Open()
'If Email and PW are found
If dr.Read Then
Dim appCookie As New HttpCookie("UserID")
appCookie.Value = dr("GUID").ToString()
appCookie.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie)
Dim appCookie1 As New HttpCookie("UserName")
appCookie1.Value = dr("UserName").ToString
appCookie1.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie1)
Dim appCookie2 As New HttpCookie("UserEmail")
appCookie2.Value = txtEmail.Text.ToLower()
appCookie2.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie2)
Dim appCookie3 As New HttpCookie("Lat")
appCookie3.Value = dr("GeoLat").ToString()
appCookie3.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie3)
Dim appCookie4 As New HttpCookie("Long")
appCookie4.Value = dr("GeoLong").ToString()
appCookie4.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie4)
Dim appCookie5 As New HttpCookie("City")
appCookie5.Value = dr("City").ToString()
appCookie5.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie5)
Dim appCookie6 As New HttpCookie("State")
appCookie6.Value = dr("State").ToString
appCookie6.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie6)
HttpContext.Current.Response.Cookies("EO_Login").Expires = Now.AddDays(30)
HttpContext.Current.Response.Cookies("EO_Login")("EMail") = txtEmail.Text.ToLower()
Dim sUserData As String = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserID").Value) & "|" & HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserName").Value) & "|" & HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserEmail").Value)
' Dim sUserData As String = "dbcf586f-82ac-4aef-8cd0-0809d20c70db|scott selby|scottselby#live.com"
Dim fat As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
dr("UserName").ToString, DateTime.Now, _
DateTime.Now.AddDays(6), True, sUserData, _
FormsAuthentication.FormsCookiePath)
Dim encTicket As String = FormsAuthentication.Encrypt(fat)
HttpContext.Current.Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
'If Email and Pw are not found
Else
dr.Close()
dbCon.Close()
End If
'Always do this
dr.Close()
sSql = "UPDATE eo_Users SET LastLogin=GETUTCDATE() WHERE GUID=#GUID; "
cmd = New SqlCommand(sSql, dbCon)
cmd.Parameters.AddWithValue("#GUID", HttpContext.Current.Session("UserID"))
cmd.ExecuteNonQuery()
dbCon.Close()
EnterNewTransInDb()
'Dim URL As String = Request.QueryString("url").ToString()
'Response.Redirect(URL + "?aid=854&rid=" + RegID.ToString())
End Sub

Assuming you only want this code to run if there is a valid QueryString, you could put a guard clause at the beginning of the method to simply check if QueryString is null and then perform some other action if this page is called without a QueryString.

Try setting the breakpoints before the call and make sure the variables are assigned values.

Have you tried putting a breakpoint on Dim URL As String = Request.QueryString("url").ToString() line in your code? Maybe you just need to evaluate first the querystring for the 'url' parameter, if it exists; before converting it to a string.

Related

Duplicate records created on page load vb.net

I trying to figure out why my code in inserting two records into the database when it executes? the CreateEnrollment Sub executes fine, however the results insert 2 sometimes 3 records ranging from 1-10 seconds apart, depending on remote server load. I first thought it might be the IsPostBack problem but adding the If Not Page.IsPostBack Then did not resolve.
Dim FailedMessage As String = "This COPDI (On-Line) user failed: "
Dim PassedMessage As String = "This COPDI (On-Line) user passes: "
Dim ClassName As String = "COPDI (FAILED)"
Dim SendMailAddress As String = "myEmailAddress.com"
Dim SubsiteConnString As String = "Subsite_appSettings"
Dim MainsiteConnString As String = "SubsiteConn"
Dim RecordsReturned As Integer = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim UserName As String = User.Identity.Name()
Dim userID As Integer = GetUID(UserName)
Dim ClassDate As Date = DateTime.Now.AddHours(3).ToShortDateString
Dim ClassTime As String = DateTime.Now.AddHours(3). ToShortTimeString
If Not Page.IsPostBack Then
If Request.QueryString("code") = 1111 Then
RecordsReturned = RecordExist(UserName)
CreateEnrollment(UserName, ClassDate, ClassTime, ClassName, userID)
UpdateLastActivityDate(UserName)
If RecordsReturned < 3 Then
Response.Redirect("~/transcript.aspx" & "?code=" & RecordsReturned)
Else
Response.Redirect("~/transcript.aspx" & "?code=" & "more_than_three")
End If
End If
End If
End Sub
Public Sub CreateEnrollment(ByVal UserName As String, ByVal ClassDate As Date, ByVal ClassTime As String, ByVal ClassName As String, ByVal UID As Integer)
Dim connStr As String = ConfigurationManager.AppSettings.Get(SubsiteConnString)
Dim conn As New Data.OleDb.OleDbConnection(connStr)
Try
conn.Open()
Dim sql As String = "INSERT INTO EnrollmentsTbl (" & _
"[UserName],[SubmitTime],[ClassTime],[ClassDate],[Enrolled],[ClassName],[Instructor],[DateCompleted],[Completed],[WaitListed],[UID]) " & _
"VALUES (#UserName, #SubmitTime, #ClassTime, #ClassDate, #Enrolled, #ClassName, #Instructor, #DateCompleted, #Completed, #WaitListed, #UID) "
Dim comm As New Data.OleDb.OleDbCommand(sql, conn)
comm.Parameters.AddWithValue("#UserName", UserName)
comm.Parameters.AddWithValue("#SubmitTime", DateTime.Now.AddHours(3).ToString())
comm.Parameters.AddWithValue("#ClassTime", ClassTime)
comm.Parameters.AddWithValue("#ClassDate", ClassDate)
comm.Parameters.AddWithValue("#Enrolled", True)
comm.Parameters.AddWithValue("#ClassName", ClassName)
comm.Parameters.AddWithValue("#Instructor", "On-line")
comm.Parameters.AddWithValue("#DateCompleted", DateTime.Now.AddHours(3).ToString)
comm.Parameters.AddWithValue("#Completed", False)
comm.Parameters.AddWithValue("#WaitListed", False)
comm.Parameters.AddWithValue("#UID", UID)
Dim result As Integer = comm.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
Finally
conn.Close()
End Try
End Sub
Public Function RecordExist(ByVal username As String) As Integer
Dim connStr As String = ConfigurationManager.AppSettings.Get(SubsiteConnString)
Dim conn As New Data.OleDb.OleDbConnection(connStr)
Dim sql As String = "SELECT COUNT(*) FROM EnrollmentsTbl " & _
"WHERE [UserName] = """ & username & """ AND ClassName LIKE """ & ClassName & """ AND [Completed] = 0 AND [Enrolled] = -1"
Dim DBCommand As New Data.OleDb.OleDbCommand(sql, conn)
Try
conn.Open()
Dim RecordCount As Integer = CInt(DBCommand.ExecuteScalar())
conn.Close()
Return RecordCount
Catch ex As Exception
Response.Write(ex)
Finally
conn.Close()
End Try
End Function
Public Function GetUID(ByVal username As String) As Integer
Dim xUserName As String = User.Identity.Name()
If (Not xUserName="") Then
Dim objConn As Data.OleDb.OleDbConnection
Dim objCmd As Data.OleDb.OleDbCommand
Dim objRdr As Data.OleDb.OleDbDataReader
Dim userAN As String
Dim strConnection As String = ConfigurationManager.ConnectionStrings("TechTrainingConn").ToString
objConn = New Data.OleDb.OleDbConnection(strConnection)
objCmd = New Data.OleDb.OleDbCommand("SELECT * FROM UsersDataTbl WHERE [UserName] = """ & xUserName & """", objConn)
Try
objConn.Open()
objRdr = objCmd.ExecuteReader()
While objRdr.Read()
userAN = objRdr.Item("UID")
End While
objRdr.Close()
objConn.Close()
Session("userID") = userAN
Return userAN
'Response.Write(Session("userAN") & " - " & xUserName)
Catch ex As Exception
Response.Write(ex)
Finally
objConn.Close()
End Try
End If
End Function
What aspx page is this supporting? I noticed you have a redirect to transcript.aspx, is this code for that page? If so that would explain the multiple page loads. Response.Redirect is not a postback so it's going to fall into recordReturned and CreateEnrollment methods again, especially if you are passing the &code=1111 in the URL querystring

VB.Net Code not executing when value is not nullorempty

I'm trying to make fb login for my website. So I put condition if user already exist then it will do login & if not then it perform insert user data.
In following code if string is Not Null Or Empty then I am trying to execute code but by putting breakpoint on my statement I see that if string has value then rest code not executing. What could be the reason? Is I am doing something wrong? My first block of code is working fine(users data fetching from facebook). Problem is in second block where I am checking condition.
Private Sub login_Load(sender As Object, e As EventArgs) Handles Me.Load
FaceBookConnect.API_Key = "XXXXXXX"
FaceBookConnect.API_Secret = "XXXXXXX"
If Not IsPostBack Then
If Request.QueryString("error") = "access_denied" Then
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('User has denied access.')", True)
Return
End If
Dim code As String = Request.QueryString("code")
If Not String.IsNullOrEmpty(code) Then
Dim data As String = FaceBookConnect.Fetch(code, "me")
Dim faceBookUser As FaceBookUser = New JavaScriptSerializer().Deserialize(Of FaceBookUser)(data)
faceBookUser.PictureUrl = String.Format("https://graph.facebook.com/{0}/picture", faceBookUser.Id)
pnlFaceBookUser.Visible = True
lblId.Text = faceBookUser.Id
lblUserName.Text = faceBookUser.UserName
lblName.Text = faceBookUser.Name
lblEmail.Text = faceBookUser.Email
ProfileImage.ImageUrl = faceBookUser.PictureUrl
btnLogin.Enabled = False
End If
End If
If IsPostBack Then
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 50000
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Response.Write("User Already Exist")
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
dr.Close()
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Response.Write("User Added")
Catch ex As Exception
Response.Write(ex)
End Try
End If
con.Close()
End If
End If
End Sub
End Class

cannot display image in image control

Its my handler (.ashx)
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else Throw New ArgumentException("No parameter specified") End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Everything is working fine.Only the imageData length is 0 so the image is unable to display.
#Sean: its elsewhr.. here the querystring correctly takes the employeeid passed...
heres the code for db access:
Public Sub bind()
Dim ds1 As New DataSet()
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
con.Open()
Dim query As String = "select * from EmployeeTable"
Dim cmd As New SqlCommand()
Dim da1 As New SqlDataAdapter(query, con)
da1.Fill(ds1, "EmployeeTable")
GridView1.DataSource = ds1.Tables("EmployeeTable")
GridView1.DataBind()
con.Close()
End Sub
You're loading a load of data into the GridView but nothing is being loaded into your imageData variable. So we'll just connect to the database and pull that data out. I'm assuming your image column is called imageData but please change as appropriate.
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring
Using con As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
Using cmd As New SqlCommand("SELECT imageData FROM EmployeeTable WHERE EmployeeID = #EmployeeID", con) 'select imageData column, change column name as appropriate
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID)
Try
con.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
If rdr.Read() Then
imageData = CType(rdr("imageData"), Byte()) 'convert imageData column from result set to byte array and assign to variable
End If
End Using
Catch ex As Exception
'do any error handling here
End Try
End Using
End Using
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Changed the code in the handler to this:
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim Image() As Byte = {}
' get the image data from the database using the employeeId Querystring
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
Dim cmd As New SqlCommand("SELECT Image FROM EmployeeTable WHERE EmployeeID = #EmployeeID", con)
'select imageData column, change column name as appropriate
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID)
Try
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Image = CType(rdr("Image"), Byte())
'convert imageData column from result set to byte array and assign to variable
End While
Catch ex As Exception
'do any error handling here
End Try
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(Image)
End Sub
Worked for me, may be it will work for you too...

How to Use a parameter within SQL in Vb 2010 (web developer)

I am trying to work out SQL code in VB but I am having problems I have a simple database with the table admin with the columns UserName and Password.
I want to be able to read data from a text box and then input it into a SQL string… the SQL string works (I've tested it) and I can get it to output with a simple SELECT statement but I can't seem to get the SQL to read my Parameter.
Help?
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call Password_Check(txtTestInput.Text)
End Sub
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", Answer)
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
in your code above:
--> Dim parameter As New SqlParameter("#Username", Answer)
Can I suggest two options:
Dim parameter As New SqlParameter("#Username", sqldbtype.nvarchar)
parameter.value = Answer
or
cmd.CommandText = string.format("SELECT Password FROM Admin WHERE (UserName = {0})", Answer)
Full Code:
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", SqlDbType.NVarChar)
parameter.Value = Answer
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
Regarding to your Database system it is possible that it does not support parameter names. Have you tried ? Wat DB System you used?
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = ?)"

AD Password About to Expire check

I am trying to write some code to check the AD password age during a user login and notify them of the 15 remaining days. I am using the ASP.Net code that I found on the Microsoft MSDN site and I managed to add a function that checks the if the account is set to change password at next login. The login and the change password at next login works great but I am having some problems with the check for the password age.
This is the VB.Net code for the DLL file:
Imports System
Imports System.Text
Imports System.Collections
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.Reflection 'Needed by the Password Expiration Class Only -Vince
Namespace FormsAuth
Public Class LdapAuthentication
Dim _path As String
Dim _filterAttribute As String
'Code added for the password expiration added by Vince
Private _domain As DirectoryEntry
Private _passwordAge As TimeSpan = TimeSpan.MinValue
Const UF_DONT_EXPIRE_PASSWD As Integer = &H10000
'Function added by Vince
Public Sub New()
Dim root As New DirectoryEntry("LDAP://rootDSE")
root.AuthenticationType = AuthenticationTypes.Secure
_domain = New DirectoryEntry("LDAP://" & root.Properties("defaultNamingContext")(0).ToString())
_domain.AuthenticationType = AuthenticationTypes.Secure
End Sub
'Function added by Vince
Public ReadOnly Property PasswordAge() As TimeSpan
Get
If _passwordAge = TimeSpan.MinValue Then
Dim ldate As Long = LongFromLargeInteger(_domain.Properties("maxPwdAge")(0))
_passwordAge = TimeSpan.FromTicks(ldate)
End If
Return _passwordAge
End Get
End Property
Public Sub New(ByVal path As String)
_path = path
End Sub
'Function added by Vince
Public Function DoesUserHaveToChangePassword(ByVal userName As String) As Boolean
Dim ctx As PrincipalContext = New PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain)
Dim up = UserPrincipal.FindByIdentity(ctx, userName)
Return (Not up.LastPasswordSet.HasValue)
'returns true if last password set has no value.
End Function
Public Function IsAuthenticated(ByVal domain As String, ByVal username As String, ByVal pwd As String) As Boolean
Dim domainAndUsername As String = domain & "\" & username
Dim entry As DirectoryEntry = New DirectoryEntry(_path, domainAndUsername, pwd)
Try
'Bind to the native AdsObject to force authentication.
Dim obj As Object = entry.NativeObject
Dim search As DirectorySearcher = New DirectorySearcher(entry)
search.Filter = "(SAMAccountName=" & username & ")"
search.PropertiesToLoad.Add("cn")
Dim result As SearchResult = search.FindOne()
If (result Is Nothing) Then
Return False
End If
'Update the new path to the user in the directory.
_path = result.Path
_filterAttribute = CType(result.Properties("cn")(0), String)
Catch ex As Exception
Throw New Exception("Error authenticating user. " & ex.Message)
End Try
Return True
End Function
Public Function GetGroups() As String
Dim search As DirectorySearcher = New DirectorySearcher(_path)
search.Filter = "(cn=" & _filterAttribute & ")"
search.PropertiesToLoad.Add("memberOf")
Dim groupNames As StringBuilder = New StringBuilder()
Try
Dim result As SearchResult = search.FindOne()
Dim propertyCount As Integer = result.Properties("memberOf").Count
Dim dn As String
Dim equalsIndex, commaIndex
Dim propertyCounter As Integer
For propertyCounter = 0 To propertyCount - 1
dn = CType(result.Properties("memberOf")(propertyCounter), String)
equalsIndex = dn.IndexOf("=", 1)
commaIndex = dn.IndexOf(",", 1)
If (equalsIndex = -1) Then
Return Nothing
End If
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1))
groupNames.Append("|")
Next
Catch ex As Exception
Throw New Exception("Error obtaining group names. " & ex.Message)
End Try
Return groupNames.ToString()
End Function
'Function added by Vince
Public Function WhenExpires(ByVal username As String) As TimeSpan
Dim ds As New DirectorySearcher(_domain)
ds.Filter = [String].Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))", username)
Dim sr As SearchResult = FindOne(ds)
Dim user As DirectoryEntry = sr.GetDirectoryEntry()
Dim flags As Integer = CInt(user.Properties("userAccountControl").Value)
If Convert.ToBoolean(flags And UF_DONT_EXPIRE_PASSWD) Then
'password never expires
Return TimeSpan.MaxValue
End If
'get when they last set their password
Dim pwdLastSet As DateTime = DateTime.FromFileTime(LongFromLargeInteger(user.Properties("pwdLastSet").Value))
' return pwdLastSet.Add(PasswordAge).Subtract(DateTime.Now);
If pwdLastSet.Subtract(PasswordAge).CompareTo(DateTime.Now) > 0 Then
Return pwdLastSet.Subtract(PasswordAge).Subtract(DateTime.Now)
Else
Return TimeSpan.MinValue
'already expired
End If
End Function
'Function added by Vince
Private Function LongFromLargeInteger(ByVal largeInteger As Object) As Long
Dim type As System.Type = largeInteger.[GetType]()
Dim highPart As Integer = CInt(type.InvokeMember("HighPart", BindingFlags.GetProperty, Nothing, largeInteger, Nothing))
Dim lowPart As Integer = CInt(type.InvokeMember("LowPart", BindingFlags.GetProperty, Nothing, largeInteger, Nothing))
Return CLng(highPart) << 32 Or CUInt(lowPart)
End Function
'Function added by Vince
Private Function FindOne(ByVal searcher As DirectorySearcher) As SearchResult
Dim sr As SearchResult = Nothing
Dim src As SearchResultCollection = searcher.FindAll()
If src.Count > 0 Then
sr = src(0)
End If
src.Dispose()
Return sr
End Function
End Class
End Namespace
And this is the Login.aspx page:
sub Login_Click(sender as object,e as EventArgs)
Dim adPath As String = "LDAP://DC=xxx,DC=com" 'Path to your LDAP directory server
Dim adAuth As LdapAuthentication = New LdapAuthentication(adPath)
Try
If (True = adAuth.DoesUserHaveToChangePassword(txtUsername.Text)) Then
Response.Redirect("passchange.htm")
ElseIf (True = adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text)) Then
Dim groups As String = adAuth.GetGroups()
'Create the ticket, and add the groups.
Dim isCookiePersistent As Boolean = chkPersist.Checked
Dim authTicket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups)
'Encrypt the ticket.
Dim encryptedTicket As String = FormsAuthentication.Encrypt(authTicket)
'Create a cookie, and then add the encrypted ticket to the cookie as data.
Dim authCookie As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
If (isCookiePersistent = True) Then
authCookie.Expires = authTicket.Expiration
End If
'Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie)
'Retrieve the password life
Dim t As TimeSpan = adAuth.WhenExpires(txtUsername.Text)
'You can redirect now.
If (passAge.Days = 90) Then
errorLabel.Text = "Your password will expire in " & DateTime.Now.Subtract(t)
'errorLabel.Text = "This is"
'System.Threading.Thread.Sleep(5000)
Response.Redirect("http://somepage.aspx")
Else
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, False))
End If
Else
errorLabel.Text = "Authentication did not succeed. Check user name and password."
End If
Catch ex As Exception
errorLabel.Text = "Error authenticating. " & ex.Message
End Try
End Sub
`
Every time I have this Dim t As TimeSpan = adAuth.WhenExpires(txtUsername.Text) enabled, I receive "Arithmetic operation resulted in an overflow." during the login and won't continue.
What am I doing wrong? How can I correct this? Please help!!
Thank you very much for any help in advance.
Vince
Ok I tried to use a different approach.
Here are the functions converted from C#:
Public Function PassAboutToExpire(ByVal userName As String) As Integer
Dim passwordAge As TimeSpan
Dim currentDate As DateTime
Dim ctx As PrincipalContext = New PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain)
Dim up = UserPrincipal.FindByIdentity(ctx, userName)
'Return (Not up.LastPasswordSet.HasValue)
'returns true if last password set has no value.
Dim pwdLastSet As DateTime = DateTime.FromFileTime(LongFromLargeInteger(up.LastPasswordSet))
currentDate = Now
passwordAge = currentDate.Subtract(pwdLastSet)
If passwordAge.Days > 75 Then
'If pwdLastSet.Subtract(passwordAge).CompareTo(DateTime.Now) > 0 Then
'Dim value As TimeSpan = pwdLastSet.Subtract(passwordAge).Subtract(DateTime.Now)
'If (value.Days > 75) Then
Return passwordAge.Days
'End If
Else
Return False
'already expired
End If
End Function
Private Function LongFromLargeInteger(ByVal largeInteger As Object) As Long
Dim type As System.Type = largeInteger.[GetType]()
Dim highPart As Integer = CInt(type.InvokeMember("HighPart", BindingFlags.GetProperty, Nothing, largeInteger, Nothing))
Dim lowPart As Integer = CInt(type.InvokeMember("LowPart", BindingFlags.GetProperty, Nothing, largeInteger, Nothing))
Return CLng(highPart) << 32 Or CUInt(lowPart)
End Function
And here is the code snippet from the logon.aspx page:
sub Login_Click(sender as object,e as EventArgs)
Dim adPath As String = "LDAP://DC=xzone,DC=com" 'Path to your LDAP directory server
Dim adAuth As LdapAuthentication = New LdapAuthentication(adPath)
Try
If (True = adAuth.DoesUserHaveToChangePassword(txtUsername.Text)) Then
Response.Redirect("http://mypass.nsu.edu")
ElseIf (adAuth.PassAboutToExpire(txtUsername.Text) > 0) Then
Response.Redirect("http://www.yahoo.com")
Now when I try to login I receive the exception error: Error authenticating. Method 'System.DateTime.HighPart' not found.
and I don't know why. Anyone has any idea?
I would use the DateDiff function to determine the remaining number of days rather than using currentDate.Subtract
Dim passwordAge As Integer = (CInt)DateDiff(DateInterval.Day, Now, up.LastPasswordSet))
That will return an integer representing the number of days between now and when the password will need to be set.

Resources