vb.net conversion of c# cast to Literal - asp.net

I'm trying to use the password recovery using vb. I found the c# code online and am trying to convert it to vb. I'm getting "end of statement expected" error. Can anybody see the issue?
c# code:
protected void validateUserEmail(object sender, LoginCancelEventArgs e)
{
TextBox EmailAddressTB =
((TextBox)PWRecovery.UserNameTemplateContainer.FindControl("EmailAddressTB"));
Literal ErrorLiteral =
((Literal)PWRecovery.UserNameTemplateContainer.FindControl("ErrorLiteral"));
MembershipUser mu = Membership.GetUser(PWRecovery.UserName);
if (mu != null) // The username exists
{
if (mu.Email.Equals(EmailAddressTB.Text)) // Their email matches
{
ProfileCommon newProfile = Profile.GetProfile(PWRecovery.UserName);
HttpCookie appCookie = new HttpCookie("usernameCookie");
appCookie.Value = newProfile.FullName;
appCookie.Expires = DateTime.Now.AddMinutes(3);
Response.Cookies.Add(appCookie);
}
else
{
e.Cancel = true;
ErrorLiteral.Text = "Your username and password do not match";
}
}
else
{
e.Cancel = true;
ErrorLiteral.Text = "No such user found.";
}
}
vb code:
Protected Sub SubmitButton_Click(sender As Object, e As System.EventArgs)
Dim user As MembershipUser = Membership.GetUser(PasswordRecovery1.UserName)
Dim errorLiteral As Literal = (Literal)PasswordRecovery1.UserNameTemplateContainer.FindControl("FailureText")
If (user IsNot Nothing) Then
Dim password As String = user.GetPassword()
EmailPassword(user.Email, password, user.ToString())
Else
errorLiteral.Text = "No such user found."
End If
End Sub

Dim errorLiteral As Literal = (Literal)PasswordRecovery1.UserNameTemplateContainer.FindControl("FailureText")
can be just
Dim errorLiteral As Literal = PasswordRecovery1.UserNameTemplateContainer.FindControl("FailureText")
If you'd prefer, you can also use Ctype(object, type) or DirectCast(object, type) - example:
Dim errorLiteral As Literal = CType(PasswordRecovery1.UserNameTemplateContainer.FindControl("FailureText"), Literal)

Related

Why am I getting Expression Expected?

This is my simple CodeFile vb code for a username and password login form with a redirect to different 'members area' pages:
Public Class MyPage
Inherits Page
Private Structure Cred
Public Username As String
Public Password As String
Public RedirectUrl As String
Public Sub New(un As String, pw As String, Optional ru As String = "/admin/default.aspx")
Username = un
Password = pw
RedirectUrl = ru
End Sub
End Structure
Private ReadOnly _credentials As System.Collections.Generic.IEnumerable(Of Cred) = New Cred(){New Cred("userone", "passwordone"), New Cred("usertwo", "passwordtwo"), New Cred("userthree", "passwordthree", "/admin/custom.aspx")}
Public Sub Page_Load(sender As Object, e As EventArgs)
Dim user = _credentials.SingleOrDefault(Function(x) x.Username = UserName.Text AndAlso x.Password = Password.Text)
If user IsNot Nothing Then
Session("Admin") = True
Response.Redirect(user.RedirectUrl)
Else
Session("Admin") = False
LtlLogin.Text = "<p>Sorry, you have provided incorrect login details.</p>"
End If
End Sub
End Class
It's on the line:
Dim user = _credentials.SingleOrDefault(Function(x) x.Username = UserName.Text AndAlso x.Password = Password.Text)
Thanks very much.
David.
The problem is that you are using structure against class for Cred.
Be aware that structures are value types and classes are reference types.
So:
Dim user = _credentials.SingleOrDefault(Function(x) x.Username = UserName.Text AndAlso x.Password = Password.Text)
always return a structure (when nothing found then the members of the structure gets their default values).
You cannot compare a structure to Nothing as ti is not a reference type.
Change structure to class and you will be fine.
Or change the check with:
If Not user.Equals(New Cred) Then
Check this
UPDATE with examples
Class Cred
Imports System.Linq
Module StartupModule
Private ReadOnly _credentials As System.Collections.Generic.IEnumerable(Of Cred) = New Cred() {
New Cred("userone", "passwordone"),
New Cred("usertwo", "passwordtwo"),
New Cred("userthree", "passwordthree", "/admin/custom.aspx")}
Sub Main()
Dim userName As String = ""
Dim password As String = ""
Dim crd = _credentials.Where(Function(x) x.Username = userName AndAlso x.Password = password).SingleOrDefault
If crd Is Nothing Then
Console.WriteLine("user is nothing")
Else
Console.WriteLine("user is something")
End If
Console.ReadLine()
End Sub
Private Class Cred
Public Username As String
Public Password As String
Public RedirectUrl As String
Public Sub New(un As String, pw As String, Optional ru As String = "/admin/default.aspx")
Username = un
Password = pw
RedirectUrl = ru
End Sub
End Class
End Module
Structure Cred
Imports System.Linq
Module StartupModule
Private ReadOnly _credentials As System.Collections.Generic.IEnumerable(Of Cred) = New Cred() {
New Cred("userone", "passwordone"),
New Cred("usertwo", "passwordtwo"),
New Cred("userthree", "passwordthree", "/admin/custom.aspx")}
Sub Main()
Dim userName As String = ""
Dim password As String = ""
Dim crd = _credentials.Where(Function(x) x.Username = userName AndAlso x.Password = password).SingleOrDefault
If crd.Equals(New Cred) Then
Console.WriteLine("user is nothing")
Else
Console.WriteLine("user is something")
End If
Console.ReadLine()
End Sub
Private Structure Cred
Public Username As String
Public Password As String
Public RedirectUrl As String
Public Sub New(un As String, pw As String, Optional ru As String = "/admin/default.aspx")
Username = un
Password = pw
RedirectUrl = ru
End Sub
End Structure
End Module

ASP IF Logic not fully functioning

I have a login form that checks for roles and when the credentials are met, the user is directed to a specific page. My issue is that when the username or password is incorrect, my logic fails to prompt the user via a label that I have in the design. I even tried implementing it via a Try/Catch and still the same result.
The Design:
<div><asp:Label ID="lblinfo" runat="server" Width="374px" CssClass="blktext"></asp:Label></div>
The code in behind the (button event-handler):
Try
Dim con As New SqlConnection(GetConnectionString())
con.Open()
Dim cmd As New SqlCommand("Check_Users", con)
cmd.CommandType = CommandType.StoredProcedure
Dim p1 As New SqlParameter("Login_name", username.Text)
Dim p2 As New SqlParameter("Login_Pwd", password.Text)
cmd.Parameters.Add(p1)
cmd.Parameters.Add(p2)
Dim rd As SqlDataReader = cmd.ExecuteReader()
'check the Role of the user logging in'
While (rd.Read())
Session("numrecord") = rd.GetValue(0).ToString()
rd.GetValue(11).ToString()
If rd.HasRows Then
If rd.GetValue(11).ToString() = 1 Then
rd.Read()
lblinfo.Text = "You are Authorized."
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/SecurePage.aspx")
Else
lblprompt.Text = "Invalid username or password."
End If
If rd.GetValue(11).ToString() = 2 Then
rd.Read()
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/newShipment.aspx")
Else
lblprompt.Text = "Invalid username or password."
End If
End If
End While
Catch ex As Exception
lblprompt.Text = "Invalid username or password."
End Try
Could I get some help as to what am failing to do here?
At the very least, please write a basic POCO object to encapsulate the values from the data layer.
Use your datareader to POPULATE the Poco object, and insert some basic logic on the Poco object.
Use the datareader quickly, then get rid of it.
Then you could actually reuse the object and your logic.
Something like this.
Then (in the presentation layer) ~respond to the values in the Poco with the redirects and such.
public enum RedirectTypeEnum
{
Unknown = 0,
SecurePage = 1,
NewShipment = 2,
}
public class LoginAttemptResult
{
public LoginAttemptResult()
{
this.NumRecord = 0;
this.ResultNumberAkaColumn11 = 0;
}
public int NumRecord { get; set; }
public int ResultNumberAkaColumn11 { get; set; }
public RedirectTypeEnum RedirectType
{
get
{
RedirectTypeEnum returnValue = RedirectTypeEnum.Unknown;
if (this.ResultNumberAkaColumn11 == 1)
{
returnValue = RedirectTypeEnum.SecurePage;
}
if (this.ResultNumberAkaColumn11 == 2)
{
returnValue = RedirectTypeEnum.NewShipment;
}
return returnValue;
}
}
public bool IsAuthorized
{
get
{
if (this.ResultNumberAkaColumn11 == 1)
{
return true;
}
if (this.ResultNumberAkaColumn11 == 2)
{
return false; /* ?? */
}
return false;
}
}
}
Then you'll have one place where you populate this object, and someone can see clearly what the biz logic is by looking at the POCO object.
One issue that I see is that you are response.redirect'ing in a Try...Catch block. Unless you put , False (which allows the code to finish executing instead of aborting) after the URL, you will throw a Thread is aborting error every time it attempts to redirect.
As for the message not showing, you show how lblinfo is created, but what about lblprompt? Perhaps you have its visible property set to false? If this is the case, make sure to change it to true in the code. Also, make sure you are not clearing its value on events such as page_load.
I have also cleaned up the code a little bit and implemented a datatable object instead of the reader:
Try
Dim cmd As New SqlCommand("Check_Users", New SqlConnection(GetConnectionString()))
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter("Login_name", username.Text))
cmd.Parameters.Add(New SqlParameter("Login_Pwd", password.Text))
Dim sqlDataAdapter As New SqlClient.SqlDataAdapter(cmd)
Dim dtResults As New DataTable
sqlDataAdapter.Fill(dtResults)
lblprompt.Text = "Invalid username or password."
'check the Role of the user logging in'
If dtResults.Rows.Count > 0 Then
With dtResults.Rows(0)
Session("numrecord") = .Item(0).ToString()
If .Item(11).ToString() = 1 Then
lblprompt.Text = ""
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/SecurePage.aspx", False)
ElseIf .Item(11).ToString() = 2 Then
lblprompt.Text = ""
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/newShipment.aspx", False)
End If
End With
End If
Catch ex As Exception
lblprompt.Text = "An error has occurred." & ex.Message
End Try

database Image not getting displayed asp.net

trying to display an image from database in an image control... third day...no luck so far...
Displaybutton on Employee.aspx
Protected Sub DisplayButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DisplayButton.Click
bind()
GridView1.Visible = "True"
If EmployeeIDTextBox.Text = "" Then
MsgBox("Please enter EmployeeID!")
Else
Image1.ImageUrl = "~/HttpHandler.ashx?EmployeeID=" & EmployeeIDTextBox.Text
End If
End Sub
This is the handler:
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/plain"
'context.Response.Write("Hello World!")
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"
' You can retrieve this also from the database
context.Response.BinaryWrite(imageData)
End Sub
this is the image control (on Employee.aspx) in which i wanna display the image
<asp:Image ID="Image1" runat="server" imageUrl="HttpHandler.ashx?EmployeeID=7" />
got a lotta help... seems wasnt enough...
These can be helpful. Scenario is similar and can be achieved for your situation:
Display image from a datatable in asp:image in code-behind
Showing an image in listview from datatable
This is in c# but will help someone.
public void ProcessRequest(HttpContext context)
{
string querystring = context.Request.QueryString.ToString();
try
{
if (querystring != null && querystring.Trim().Length == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
string DocCode = querystring;
DataTable dt = GetDocumentInfo(DocCode); //Get Image From Database. I encapsulated it in other method.Implement it,
if (dt.Rows.Count == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.MinValue);
context.Response.ContentType = MimeMapping.GetMimeMapping(System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.AddHeader("content-disposition", "inline; filename=" + System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.BinaryWrite((Byte[])dt.Rows[0]["DocumentFile"]);
context.Response.Flush();
}
catch (Exception ex)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
context.Response.End();
}

Getting error in ASP.Net page

Can you please let me know why the following piece of code is not working, I am getting the error message when the debugger past the variable "strStatus". The error message is: "Object reference not set to an instance of an object." Can you please help. Thanks - Yagya
protected void Button1_Click(object sender, EventArgs e)
{
if (Y0130_chkNew.Checked == true)
{
bool isChecked = true; // This is required for later retrieval.
string strAction = "Reporting";
string strFromRole = ddSelectRole.SelectedValue;
string TxtBoxID = myProject.getTextBox(strAction, strPath);
TextBox txtb = new TextBox();
txtb = (TextBox)Page.FindControl(TxtBoxID);
string strStatus = txtb.Text;
string ddID = myProject.getDropDown(strAction, strPath);
DropDownList ddLst = new DropDownList;
ddLst = (DropDownList)Page.FindControl(ddID);
string strForwardRole = ddLst.SelectedValue;
// Call the function now
my.updateXML(strFromRole, strAction, strStatus, strForwardRole, strPath);
}
}
Page.FindControl(TxtBoxID); returns null what is the reason for your exception. FindControl does not search controls recursively, only in the given NamingContainer.
If the control is not nested in another NamingContainer on the page(f.e. a GridViewRow), there's no reason at all to use FindControl since you could reference it directly:
string strStatus = TextBox1.Text; // assuming TextBox1 is declared on the aspx
If you're using MasterPages the NamingContainer of controls in the ContentPage is not the page but the ContenPlaceHolder:
Cannot find TextBox on Page
You are finding a control using a function and possibly its returning a textbox id which doesnt existin on page . Please try to debug and see what textbox id you are getting from myProject.getTextBox function and if that exist on page .
Final Code:
if (Y0130_chkNew.Checked == true)
{
string TxtBoxID = "Y0140_txtStatus";
TextBox txtb = new TextBox();
txtb = (TextBox)Page.Master.FindControl("ContentPlaceHolder1").FindControl(TxtBoxID);
string strStatus = txtb.Text;
string ddID = "Y0150_ddOwnerRoleAssignment";
DropDownList ddLst = new DropDownList();
ddLst = (DropDownList)Page.Master.FindControl("ContentPlaceHolder1").FindControl(ddID);
string strForwardRole = ddLst.SelectedValue;
}

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