vb.net send mail is failing - asp.net

What am I missing in the code below? I am getting a failure sending email message.
Private Sub sendTestEmail()
Dim EmailBody As String
EmailBody = "This is a test *****************"
Dim TestEmail As New System.Net.Mail.MailMessage("webserver#companyname.com", "Smilinglily#companyname.com", "TestEmail", EmailBody)
Dim EmailServer As New System.Net.Mail.SmtpClient("localhost")
EmailServer.SendAsync(TestEmail, Me)
End Sub

Looks like your code came from here
It is probably that your SMTP server is not installed or configured on localhost.
It could also be a security problem stopping your localhost SMTP server from forwarding the mail.

I Have written the class which can perform this task easyly.
Imports System.Net.Mail
Public Class GGSMTP_GMAIL
Dim Temp_GmailAccount As String
Dim Temp_GmailPassword As String
Dim Temp_SMTPSERVER As String
Dim Temp_ServerPort As Int32
Dim Temp_ErrorText As String = ""
Dim Temp_EnableSSl As Boolean = True
Public ReadOnly Property ErrorText() As String
Get
Return Temp_ErrorText
End Get
End Property
Public Property EnableSSL() As Boolean
Get
Return Temp_EnableSSl
End Get
Set(ByVal value As Boolean)
Temp_EnableSSl = value
End Set
End Property
Public Property GmailAccount() As String
Get
Return Temp_GmailAccount
End Get
Set(ByVal value As String)
Temp_GmailAccount = value
End Set
End Property
Public Property GmailPassword() As String
Get
Return Temp_GmailPassword
End Get
Set(ByVal value As String)
Temp_GmailPassword = value
End Set
End Property
Public Property SMTPSERVER() As String
Get
Return Temp_SMTPSERVER
End Get
Set(ByVal value As String)
Temp_SMTPSERVER = value
End Set
End Property
Public Property ServerPort() As Int32
Get
Return Temp_ServerPort
End Get
Set(ByVal value As Int32)
Temp_ServerPort = value
End Set
End Property
Public Sub New(ByVal GmailAccount As String, ByVal GmailPassword As String, Optional ByVal SMTPSERVER As String = "smtp.gmail.com", Optional ByVal ServerPort As Int32 = 587, Optional ByVal EnableSSl As Boolean = True)
Temp_GmailAccount = GmailAccount
Temp_GmailPassword = GmailPassword
Temp_SMTPSERVER = SMTPSERVER
Temp_ServerPort = ServerPort
Temp_EnableSSl = EnableSSl
End Sub
Public Function SendMail(ByVal ToAddressies As String(), ByVal Subject As String, ByVal BodyText As String, Optional ByVal AttachedFiles As String() = Nothing) As Boolean
Temp_ErrorText = ""
Dim Mail As New MailMessage
Dim SMTP As New SmtpClient(Temp_SMTPSERVER)
Mail.Subject = Subject
Mail.From = New MailAddress(Temp_GmailAccount)
SMTP.Credentials = New System.Net.NetworkCredential(Temp_GmailAccount, Temp_GmailPassword) '<-- Password Here
Mail.To.Clear()
For i As Int16 = 0 To ToAddressies.Length - 1
Mail.To.Add(ToAddressies(i))
Next i
Mail.Body = BodyText
Mail.Attachments.Clear()
If AttachedFiles IsNot Nothing Then
For i As Int16 = 0 To AttachedFiles.Length - 1
Mail.Attachments.Add(New Attachment(AttachedFiles(i)))
Next
End If
SMTP.EnableSsl = Temp_EnableSSl
SMTP.Port = Temp_ServerPort
Try
SMTP.Send(Mail)
Return True
Catch ex As Exception
Me.Temp_ErrorText = ex.Message.ToString
Return False
End Try
End Function
End Class
Its the way, how to use class:
Dim GGmail As New GGSMTP_GMAIL("MyFromAddress1#gmail.com", "AccPassword", )
Dim ToAddressies As String() = {"ToAddress1#gmail.com", "ToAddress2#gmail.com"}
Dim attachs() As String = {"d:\temp_Excell226.xlsx", "d:\temp_Excell224.xlsx", "d:\temp_Excell225.xlsx"}
Dim subject As String = "My TestSubject"
Dim body As String = "My text goes here ...."
Dim result As Boolean = GGmail.SendMail(ToAddressies, subject, body, attachs)
If result Then
MsgBox("mails sended successfully", MsgBoxStyle.Information)
Else
MsgBox(GGmail.ErrorText, MsgBoxStyle.Critical)
End If
Hope this helps. Good coding

Related

Microsoft Translator for multiple textbox?

I get problem when use Microsoft Bing translator for show output on 3 labels for different languages.
Here is my code :
Imports System
Imports System.Collections.Generic
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml.Linq
Public Class AdmAccessToken
Public Property access_token() As String
Get
Return m_access_token
End Get
Set(ByVal value As String)
m_access_token = value
End Set
End Property
Private m_access_token As String
Public Property token_type() As String
Get
Return m_token_type
End Get
Set(ByVal value As String)
m_token_type = value
End Set
End Property
Private m_token_type As String
Public Property expires_in() As String
Get
Return m_expires_in
End Get
Set(ByVal value As String)
m_expires_in = value
End Set
End Property
Private m_expires_in As String
Public Property scope() As String
Get
Return m_scope
End Get
Set(ByVal value As String)
m_scope = value
End Set
End Property
Private m_scope As String
End Class
Partial Class translated
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Button1.Click += New EventHandler(Button1_Click1)
End Sub
Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim clientID As String = "*******"
Dim clientSecret As String = "************"
Dim strTranslatorAccessURI As String = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
Dim strRequestDetails As String = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret))
Dim webRequest As System.Net.WebRequest = System.Net.WebRequest.Create(strTranslatorAccessURI)
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.Method = "POST"
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(strRequestDetails)
webRequest.ContentLength = bytes.Length
Using outputStream As System.IO.Stream = webRequest.GetRequestStream()
outputStream.Write(bytes, 0, bytes.Length)
End Using
Dim webResponse As System.Net.WebResponse = webRequest.GetResponse()
Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(AdmAccessToken))
Dim token As AdmAccessToken = DirectCast(serializer.ReadObject(webResponse.GetResponseStream()), AdmAccessToken)
Dim headerValue As String = "Bearer " + token.access_token
Dim txtToTranslate As String = TextBox1.Text
Dim uri As String = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=es"
Dim translationWebRequest As System.Net.WebRequest = System.Net.WebRequest.Create(uri)
translationWebRequest.Headers.Add("Authorization", headerValue)
Dim response As System.Net.WebResponse = Nothing
response = translationWebRequest.GetResponse()
Dim stream As System.IO.Stream = response.GetResponseStream()
Dim encode As System.Text.Encoding = System.Text.Encoding.GetEncoding("utf-8")
Dim translatedStream As New System.IO.StreamReader(stream, encode)
Dim xTranslation As New System.Xml.XmlDocument()
xTranslation.LoadXml(translatedStream.ReadToEnd())
Label1.Text = "Your Translation is: " + xTranslation.InnerText
End Sub
End Class
Can anyone give some advice?
I just need to know how I can get translated text to 3 different label language: label 1 for dutch language, label 2 for english language, and label 3 for indonesian language.
The final chunk of code in your example does the translation from English to Spanish. (The part that starts with Dim txtToTranslate...)
You will have to just use that 3 times (put it in a function) with once doing a translation from your target language to Dutch, once to English, once to Indonesian.
The part where the translation is specified is this:
Dim uri As String = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=es"
From=en means 'from English'
To=es means 'to Spanish'
So just amend that for the languages you need...

Access sessions in asp.net handler

I am trying to upload images using generic handler as shown below and I have a normal aspx page where I am showing all the uploaded images after uploading.Everything is working fine.
<%# WebHandler Language="VB" Class="Upload"%>
Imports System
Imports System.Web
Imports System.Threading
Imports System.Web.Script.Serialization
Imports System.IO
Public Class Upload : Implements IHttpHandler, System.Web.SessionState.IRequiresSessionState
Public Class FilesStatus
Public Property thumbnail_url() As String
Public Property name() As String
Public Property url() As String
Public Property size() As Integer
Public Property type() As String
Public Property delete_url() As String
Public Property delete_type() As String
Public Property [error]() As String
Public Property progress() As String
End Class
Private ReadOnly js As New JavaScriptSerializer()
Private ingestPath As String
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim r = context.Response
ingestPath = context.Server.MapPath("~/UploadedImages/")
r.AddHeader("Pragma", "no-cache")
r.AddHeader("Cache-Control", "private, no-cache")
HandleMethod(context)
End Sub
Private Sub HandleMethod(ByVal context As HttpContext)
Select Case context.Request.HttpMethod
Case "HEAD", "GET"
ServeFile(context)
Case "POST"
UploadFile(context)
Case "DELETE"
DeleteFile(context)
Case Else
context.Response.ClearHeaders()
context.Response.StatusCode = 405
End Select
End Sub
Private Sub DeleteFile(ByVal context As HttpContext)
Dim filePath = ingestPath & context.Request("f")
If File.Exists(filePath) Then
File.Delete(filePath)
End If
End Sub
Private Sub ServeFile(ByVal context As HttpContext)
If String.IsNullOrEmpty(context.Request("f")) Then
ListCurrentFiles(context)
Else
DeliverFile(context)
End If
End Sub
Private Sub UploadFile(ByVal context As HttpContext)
Dim statuses = New List(Of FilesStatus)()
Dim headers = context.Request.Headers
If String.IsNullOrEmpty(headers("X-File-Name")) Then
UploadWholeFile(context, statuses)
Else
UploadPartialFile(headers("X-File-Name"), context, statuses)
End If
WriteJsonIframeSafe(context, statuses)
End Sub
Private Sub UploadPartialFile(ByVal fileName As String, ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
If context.Request.Files.Count <> 1 Then
Throw New HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request")
End If
Dim inputStream = context.Request.Files(0).InputStream
Dim fullName = ingestPath & Path.GetFileName(fileName)
Using fs = New FileStream(fullName, FileMode.Append, FileAccess.Write)
Dim buffer = New Byte(1023) {}
Dim l = inputStream.Read(buffer, 0, 1024)
Do While l > 0
fs.Write(buffer, 0, l)
l = inputStream.Read(buffer, 0, 1024)
Loop
fs.Flush()
fs.Close()
End Using
statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fileName, .url = "Upload.ashx?f=" & fileName, .name = fileName, .size = CInt((New FileInfo(fullName)).Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & fileName, .delete_type = "DELETE", .progress = "1.0"})
End Sub
Private Sub UploadWholeFile(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
For i As Integer = 0 To context.Request.Files.Count - 1
Dim file = context.Request.Files(i)
file.SaveAs(ingestPath & Path.GetFileName(file.FileName))
Thread.Sleep(1000)
Dim fname = Path.GetFileName(file.FileName)
statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fname, .url = "Upload.ashx?f=" & fname, .name = fname, .size = file.ContentLength, .type = "image/png", .delete_url = "Upload.ashx?f=" & fname, .delete_type = "DELETE", .progress = "1.0"})
Next i
End Sub
Private Sub WriteJsonIframeSafe(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
context.Response.AddHeader("Vary", "Accept")
Try
If context.Request("HTTP_ACCEPT").Contains("application/json") Then
context.Response.ContentType = "application/json"
Else
context.Response.ContentType = "text/plain"
End If
Catch
context.Response.ContentType = "text/plain"
End Try
Dim jsonObj = js.Serialize(statuses.ToArray())
context.Response.Write(jsonObj)
End Sub
Private Sub DeliverFile(ByVal context As HttpContext)
Dim filePath = ingestPath & context.Request("f")
If File.Exists(filePath) Then
context.Response.ContentType = "application/octet-stream"
context.Response.WriteFile(filePath)
context.Response.AddHeader("Content-Disposition", "attachment, filename=""" & context.Request("f") & """")
Else
context.Response.StatusCode = 404
End If
End Sub
Private Sub ListCurrentFiles(ByVal context As HttpContext)
Dim files = New List(Of FilesStatus)()
Dim names = Directory.GetFiles(context.Server.MapPath("~/UploadedImages/"), "*", SearchOption.TopDirectoryOnly)
For Each name In names
Dim f = New FileInfo(name)
files.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & f.Name, .url = "Upload.ashx?f=" & f.Name, .name = f.Name, .size = CInt(f.Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & f.Name, .delete_type = "DELETE"})
Next name
context.Response.AddHeader("Content-Disposition", "inline, filename=""files.json""")
Dim jsonObj = js.Serialize(files.ToArray())
context.Response.Write(jsonObj)
context.Response.ContentType = "application/json"
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Now I want to add a session variable by generating a random string and add the uploaded images to the newly created random string.
1.I have seen this Question on SO to use System.Web.SessionState.IRequiresSessionState for sessions and how do I create a folder with that and add my images to that folder after doing that how do I access this session variable in my normal aspx page.
2.(Or) the better way is create session variable in aspx page and pass that to handler?If so how can I do that?
3 .I am trying to find the control from my handler.Is that possible?If anyone knows how to get this then also my problem will get resolved so that I am trying to create a session from m aspx page.
Can anyone explain the better way of handling this situation.
I completely agree with jbl's comment.
You can get and set session using HttpContext.Current.Session anywhere on your project.
No matter where you create the session. Just make sure that the session exists before you access it.
Not sure what exactly you are asking here(need some more explanation).
Here is an example, where I used session on HttpHandler. However, it is on c#(hope you can understand).
This is not really an answer but #Knvn wrote a C# example which I couldn't understand so I used a converter to convert it to VB. Posted it here in case it helps someone in the future.
Public Class HttpHandler
Implements IHttpHandler
Implements IRequiresSessionState
Public Sub New()
End Sub
Public Sub ProcessRequest(context As HttpContext)
Dim Request As HttpRequest = context.Request
Dim Response As HttpResponse = context.Response
If SessionHandler.Current.UserID = 0 Then
Response.Redirect("~/Default.aspx")
Else
Try
If Request.Path.EndsWith(".pdf") Then
Dim client As New WebClient()
Dim buffer As [Byte]() = client.DownloadData(HttpContext.Current.Server.MapPath(Request.Path))
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", buffer.Length.ToString())
Response.BinaryWrite(buffer)
Else
Using reader As New StreamReader(HttpContext.Current.Server.MapPath(Request.Path))
Response.Write(reader.ReadToEnd())
End Using
End If
Catch
Response.Redirect("~/Default.aspx")
End Try
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean
' To enable pooling, return true here.
' This keeps the handler in memory.
Get
Return False
End Get
End Property
End Class

The specified string is not in the form required for an e-mail address

i have a problem in this code
Imports Microsoft.VisualBasic
Imports System.Net.Mail
Public Class SendEmail
Private _Mailto As String = ""
Public Property Mailto() As String
Get
Return _Mailto
End Get
Set(ByVal value As String)
_Mailto = value
End Set
End Property
Private _MailSub As String = ""
Public Property MailSub As String
Get
Return _MailSub
End Get
Set(ByVal value As String)
_MailSub = value
End Set
End Property
Private _MailBody As String = ""
Public Property MailBody As String
Get
Return _MailBody
End Get
Set(ByVal value As String)
_MailBody = value
End Set
End Property
Private _Msg As String = ""
Public ReadOnly Property Msg As String
Get
Return _Msg
End Get
End Property
Public Sub email()
Try
Dim mail As New MailMessage()
Dim SmtpServer As New SmtpClient("smtp.gmail.com")
mail.From = New MailAddress("email#gmail.com")
mail.[To].Add(_Mailto)
mail.Subject = _MailSub
mail.Body = _MailBody
' mail.Headers.Add("In-Reply-To", 1)
SmtpServer.Port = 587
SmtpServer.Credentials = New System.Net.NetworkCredential("email#gamil.com", "password")
SmtpServer.EnableSsl = True
SmtpServer.Send(mail)
_Msg = " Check Your Mail "
Catch ex As Exception
_Msg = ex.Message
End Try
End Sub
End Class
and the exception is :The specified string is not in the form required for an e-mail address.: any soultion??
It looks like you're initializing _MailTo to an empty string (""), then setting the "To" email address to that value. Unless you're setting the value of that field to some valid email address, the email sender won't recognize an empty string as a valid email address.
(If you are setting the MailTo property from outside the given code, you'll need to provide code to show where you're setting it and what the value is.)

Cookie being deleted unexpectedly by the application

I am having an issue with a cookie that keeps getting deleted by the application. When you go into the application, if the cookie does not exist, it gets created. This works fine and everything in the cookie is stored correctly.
When I click on a link to go to another page, once everything loads completely, the cookie gets deleted from the file system. Even stranger than that, the values from the cookie remain until the browser is closed. That is the application appears to be retaining the values even though the cookie does not exist on the local file system. The next time you enter the application, the cookie is recreated so any values stored are lost.
Now, I have done some tweaking on the code to see what could be causing it. I found that I am adding the cookie to the Response object any time I make a change to the cookie. The cookie is also being added to the Response object when the page load is completed. My initial thought was that adding the cookie multiple times to the Response object could be causing the issue. I commented out the code in the page load complete event and the cookie hung around until the next postback. Then I put in some logic to keep the application from putting the cookie into the Response object more than once, and then I lost the cookie again at the same point as before.
All of the code for handling cookies is in my "base page" that all pages inherit from. The page that seems to be loosing the cookie is my search page. I am including the code from both of those pages.
BasePage.vb
Public Class BasePage
Inherits Page
#Region "attributes"
Private _cookie As HttpCookie
Private _savedCookie As Boolean
Private Const COOKIE_NAME As String = "KDOELog"
Private Const COOKIE_COLUMNS As String = "cols"
Private Const COOKIE_SEARCH_BRANCH As String = "b"
Private Const COOKIE_SEARCH_COLLECTOR As String = "c"
Private Const COOKIE_SEARCH_CONF_NUMBER As String = "a"
Private Const COOKIE_SEARCH_NA_NUMBER As String = "n"
Private Const COOKIE_SEARCH_CUST_NUMBER As String = "u"
Private Const COOKIE_SEARCH_INV_NUMBER As String = "i"
Private Const COOKIE_SEARCH_CONTRACT As String = "t"
Private Const COOKIE_SEARCH_ORDER_TYPE As String = "y"
Private Const COOKIE_SEARCH_DSR_NUMBER As String = "r"
Private Const COOKIE_SEARCH_DSM_NUMBER As String = "m"
Private Const COOKIE_SEARCH_EXCEPTION As String = "e"
Private Const COOKIE_SEARCH_START_DATE As String = "s"
Private Const COOKIE_SEARCH_END_DATE As String = "d"
Private Const COOKIE_PAGE_INDEX As String = "pg"
Private Const COOKIE_SORT_COLUMN As String = "sc"
Private Const COOKIE_SORT_DIRECTION As String = "sd"
Private Const SESSION_USER As String = "user"
#End Region
#Region "constructor"
Public Sub New()
_savedCookie = False
End Sub
#End Region
#Region "events"
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
' determines whether or not to show the link for Node Search
Dim myMaster As Food = DirectCast(Me.Master, Food)
If AuthenticatedUser.IsCorporateAdmin Or AuthenticatedUser.IsBranchAdmin Then
myMaster.ShowNodeItemLink = True
Else
myMaster.ShowNodeItemLink = False
End If
End If
End Sub
Private Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
If _savedCookie = False Then Response.Cookies.Add(_cookie)
End Sub
Private Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
If IsNothing(Request.Cookies(COOKIE_NAME)) Then
_cookie = New HttpCookie(COOKIE_NAME)
_cookie.Expires = New Date(2999, 12, 31)
_cookie.Values.Add(COOKIE_COLUMNS, GetDefaultColumnList())
_cookie.Values.Add(COOKIE_SEARCH_BRANCH, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_COLLECTOR, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_CONF_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_NA_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_CUST_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_INV_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_CONTRACT, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_ORDER_TYPE, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_DSR_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_DSM_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_EXCEPTION, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_START_DATE, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_END_DATE, String.Empty)
_cookie.Values.Add(COOKIE_PAGE_INDEX, 0)
_cookie.Values.Add(COOKIE_SORT_COLUMN, "eback_datetime")
_cookie.Values.Add(COOKIE_SORT_DIRECTION, SORT_DIRECTION_ASC)
SaveCookie()
Else
_cookie = Request.Cookies(COOKIE_NAME)
End If
If IsNothing(Session(SESSION_USER)) Then Session(SESSION_USER) = New User(Context.User.Identity.Name)
End Sub
#End Region
#Region "methods"
Protected Function GetColumnList() As String()
Return Server.HtmlEncode(_cookie(COOKIE_COLUMNS)).Split(",")
End Function
Private Function GetDefaultColumnList() As String
' set the default list of columns
Dim columnList As New StringBuilder()
columnList.Append(COL_COLLECTOR).Append(",")
columnList.Append(COL_CONF_NUM).Append(",")
columnList.Append(COL_NODE_NUM).Append(",")
columnList.Append(COL_ORDER_TYPE).Append(",")
columnList.Append(COL_CUST_NUM).Append(",")
columnList.Append(COL_ERROR_IND).Append(",")
columnList.Append(COL_DSR_NUM).Append(",")
columnList.Append(COL_DSR_NAME).Append(",")
columnList.Append(COL_DSM_NUM).Append(",")
columnList.Append(COL_CONTRACT).Append(",")
columnList.Append(COL_NA_NUM).Append(",")
columnList.Append(COL_NA_SUB).Append(",")
columnList.Append(COL_INV_NUM).Append(",")
columnList.Append(COL_CONF_DATE).Append(",")
columnList.Append(COL_LINE_ITEMS).Append(",")
columnList.Append(COL_DELV_DATE).Append(",")
columnList.Append(COL_SALES_AMT).Append(",")
columnList.Append(COL_BRANCH)
Return columnList.ToString()
End Function
Protected Function HasSearchValues() As Boolean
Return CBool(_cookie(COOKIE_SEARCH_BRANCH) > String.Empty Or _
_cookie(COOKIE_SEARCH_COLLECTOR) > String.Empty Or _
_cookie(COOKIE_SEARCH_CONF_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_NA_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_CUST_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_INV_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_CONTRACT) > String.Empty Or _
_cookie(COOKIE_SEARCH_ORDER_TYPE) > String.Empty Or _
_cookie(COOKIE_SEARCH_DSR_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_DSM_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_EXCEPTION) > String.Empty Or _
_cookie(COOKIE_SEARCH_START_DATE) > String.Empty Or _
_cookie(COOKIE_SEARCH_END_DATE) > String.Empty)
End Function
Protected Sub ResetSearchValues()
_cookie(COOKIE_SEARCH_BRANCH) = String.Empty
_cookie(COOKIE_SEARCH_COLLECTOR) = String.Empty
_cookie(COOKIE_SEARCH_CONF_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_NA_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_CUST_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_INV_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_CONTRACT) = String.Empty
_cookie(COOKIE_SEARCH_ORDER_TYPE) = String.Empty
_cookie(COOKIE_SEARCH_DSR_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_DSM_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_EXCEPTION) = String.Empty
_cookie(COOKIE_SEARCH_START_DATE) = String.Empty
_cookie(COOKIE_SEARCH_END_DATE) = String.Empty
_cookie(COOKIE_PAGE_INDEX) = 0
_cookie(COOKIE_SORT_COLUMN) = "eback_datetime"
_cookie(COOKIE_SORT_DIRECTION) = SORT_DIRECTION_ASC
SaveCookie()
End Sub
Protected Sub SaveCookie()
If _savedCookie = False Then
Response.Cookies.Add(_cookie)
_savedCookie = True
End If
End Sub
Protected Sub SetColumnList(ByVal ColumnList As String)
_cookie(COOKIE_COLUMNS) = ColumnList
SaveCookie()
End Sub
#End Region
#Region "properties"
Public ReadOnly Property AuthenticatedUser() As User
Get
If IsNothing(Session(SESSION_USER)) Then Session(SESSION_USER) = New User(Context.User.Identity.Name)
Return DirectCast(Session(SESSION_USER), User)
End Get
End Property
Public ReadOnly Property UserName() As String
Get
Return Context.User.Identity.Name
End Get
End Property
Public Property SearchBranch() As String
Get
Return _cookie(COOKIE_SEARCH_BRANCH)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_BRANCH) = value
End Set
End Property
Public Property SearchCollector() As String
Get
Return _cookie(COOKIE_SEARCH_COLLECTOR)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_COLLECTOR) = value
End Set
End Property
Public Property SearchConfirmationNumber() As String
Get
Return _cookie(COOKIE_SEARCH_CONF_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_CONF_NUMBER) = value
End Set
End Property
Public Property SearchNationalAccountNumber() As String
Get
Return _cookie(COOKIE_SEARCH_NA_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_NA_NUMBER) = value
End Set
End Property
Public Property SearchCustomerNumber() As String
Get
Return _cookie(COOKIE_SEARCH_CUST_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_CUST_NUMBER) = value
End Set
End Property
Public Property SearchInvoiceNumber() As String
Get
Return _cookie(COOKIE_SEARCH_INV_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_INV_NUMBER) = value
End Set
End Property
Public Property SearchContract() As String
Get
Return _cookie(COOKIE_SEARCH_CONTRACT)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_CONTRACT) = value
End Set
End Property
Public Property SearchOrderType() As String
Get
Return _cookie(COOKIE_SEARCH_ORDER_TYPE)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_ORDER_TYPE) = value
End Set
End Property
Public Property SearchDsrNumber() As String
Get
Return _cookie(COOKIE_SEARCH_DSR_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_DSR_NUMBER) = value
End Set
End Property
Public Property SearchDsmNumber() As String
Get
Return _cookie(COOKIE_SEARCH_DSM_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_DSM_NUMBER) = value
End Set
End Property
Public Property SearchErrorType() As String
Get
Return _cookie(COOKIE_SEARCH_EXCEPTION)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_EXCEPTION) = value
End Set
End Property
Public Property SearchStartDate() As String
Get
Return _cookie(COOKIE_SEARCH_START_DATE)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_START_DATE) = value
End Set
End Property
Public Property SearchEndDate() As String
Get
Return _cookie(COOKIE_SEARCH_END_DATE)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_END_DATE) = value
End Set
End Property
Public Property PageIndex() As String
Get
Return _cookie(COOKIE_PAGE_INDEX)
End Get
Set(ByVal value As String)
_cookie(COOKIE_PAGE_INDEX) = value
End Set
End Property
Public Property SortColumn() As String
Get
Return _cookie(COOKIE_SORT_COLUMN)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SORT_COLUMN) = value
End Set
End Property
Public Property SortDirection() As String
Get
Return _cookie(COOKIE_SORT_DIRECTION)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SORT_DIRECTION) = value
End Set
End Property
#End Region
End Class
Search.aspx.vb
Public Partial Class Search
Inherits BasePage
#Region "attributes"
#End Region
#Region "events"
Private Sub btnColumnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnColumnSave.Click
Dim columns As New StringBuilder
If chkCollector.Checked Then columns.Append(COL_COLLECTOR).Append(",")
If chkAckNumber.Checked Then columns.Append(COL_CONF_NUM).Append(",")
If chkNodeNumber.Checked Then columns.Append(COL_NODE_NUM).Append(",")
If chkOrderType.Checked Then columns.Append(COL_ORDER_TYPE).Append(",")
If chkCustNumber.Checked Then columns.Append(COL_CUST_NUM).Append(",")
If chkCustName.Checked Then columns.Append(COL_CUST_NAME).Append(",")
If chkOrderExceptions.Checked Then columns.Append(COL_ERROR_IND).Append(",")
If chkDsrNumber.Checked Then columns.Append(COL_DSR_NUM).Append(",")
If chkDsrName.Checked Then columns.Append(COL_DSR_NAME).Append(",")
If chkDsmNumber.Checked Then columns.Append(COL_DSM_NUM).Append(",")
If chkDsmName.Checked Then columns.Append(COL_DSM_NAME).Append(",")
If chkContract.Checked Then columns.Append(COL_CONTRACT).Append(",")
If chkNationalAcct.Checked Then columns.Append(COL_NA_NUM).Append(",")
If chkNatAcctSub.Checked Then columns.Append(COL_NA_SUB).Append(",")
If chkInvoiceNumber.Checked Then columns.Append(COL_INV_NUM).Append(",")
If chkAckDateTime.Checked Then columns.Append(COL_CONF_DATE).Append(",")
If chkLineItem.Checked Then columns.Append(COL_LINE_ITEMS).Append(",")
If chkDeliveryDate.Checked Then columns.Append(COL_DELV_DATE).Append(",")
If chkSalesAmount.Checked Then columns.Append(COL_SALES_AMT).Append(",")
If chkBranch.Checked Then columns.Append(COL_BRANCH).Append(",")
' remove the last comma from the list
columns = columns.Remove(columns.Length - 1, 1)
SetColumnList(columns.ToString())
SaveCookie()
ManageGridColumns()
End Sub
Private Sub btnEndDate_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnEndDate.Click
calEndDate.Visible = Not calEndDate.Visible
If calEndDate.Visible Then
Try
calEndDate.SelectedDate = Date.Parse(txtEndDate.Text)
Catch
calEndDate.SelectedDate = Now
End Try
End If
modSearch.Show()
End Sub
Private Sub btnSearchReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchReset.Click
ddlBranch.SelectedIndex = 0
SearchBranch = ddlBranch.SelectedValue
ddlCollectorType.SelectedIndex = 0
SearchCollector = ddlCollectorType.SelectedValue
ddlOrderType.SelectedIndex = 0
SearchOrderType = ddlOrderType.SelectedValue
ddlErrorCode.SelectedIndex = 0
SearchErrorType = ddlErrorCode.SelectedValue
SearchConfirmationNumber = String.Empty
SearchNationalAccountNumber = String.Empty
SearchCustomerNumber = String.Empty
SearchInvoiceNumber = String.Empty
SearchContract = String.Empty
SearchDsrNumber = String.Empty
'SearchDsmNumber = String.Empty
SetDsmInfo()
SearchStartDate = Now.ToShortDateString()
SearchEndDate = Now.ToShortDateString()
SaveCookie()
SetSearchWindow()
modSearch.Show()
End Sub
Private Sub btnSearchSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchSearch.Click
SearchBranch = ddlBranch.SelectedValue
SearchCollector = ddlCollectorType.SelectedValue
SearchConfirmationNumber = txtAckNumber.Text
SearchCustomerNumber = txtCustomerNumber.Text
SearchInvoiceNumber = txtInvoiceNumber.Text
SearchDsrNumber = txtDsrNumber.Text
SearchDsmNumber = txtDsmNumber.Text
SearchNationalAccountNumber = txtNationalAccountNumber.Text
SearchContract = txtContract.Text
SearchErrorType = ddlErrorCode.SelectedValue
SearchOrderType = ddlOrderType.SelectedValue
SearchStartDate = txtStartDate.Text
SearchEndDate = txtEndDate.Text
SaveCookie()
PageIndex = 0
dgResults.CurrentPageIndex = 0
BindResults()
End Sub
Private Sub btnStartDate_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnStartDate.Click
calStartDate.Visible = Not calStartDate.Visible
If calStartDate.Visible Then
Try
calStartDate.SelectedDate = Date.Parse(txtStartDate.Text)
Catch
calStartDate.SelectedDate = Now
End Try
End If
modSearch.Show()
End Sub
Private Sub calEndDate_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles calEndDate.SelectionChanged
txtEndDate.Text = calEndDate.SelectedDate.ToShortDateString()
calEndDate.Visible = False
modSearch.Show()
End Sub
Private Sub calStartDate_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles calStartDate.SelectionChanged
txtStartDate.Text = calStartDate.SelectedDate.ToShortDateString()
calStartDate.Visible = False
modSearch.Show()
End Sub
Private Sub dgResults_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles dgResults.PageIndexChanged
PageIndex = e.NewPageIndex
dgResults.CurrentPageIndex = e.NewPageIndex
BindResults()
End Sub
Private Sub dgResults_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles dgResults.SortCommand
If SortColumn.Equals(e.SortExpression) Then
If SortDirection = SORT_DIRECTION_ASC Then
SortDirection = SORT_DIRECTION_DESC
Else
SortDirection = SORT_DIRECTION_ASC
End If
Else
SortColumn = e.SortExpression
SortDirection = SORT_DIRECTION_ASC
End If
PageIndex = 0
dgResults.CurrentPageIndex = 0
BindResults()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
SetDsmInfo()
txtStartDate.Text = Now.ToShortDateString()
txtEndDate.Text = Now.ToShortDateString()
BindBranches()
BindCollectorTypes()
BindTransmissionTypes()
BindErrorCodes()
SetupColumnWindow()
ManageGridColumns()
If HasSearchValues() Then
SetSearchWindow()
dgResults.CurrentPageIndex = CInt(PageIndex)
BindResults()
Else
modSearch.Show()
End If
End If
End Sub
#End Region
#Region "methods"
Private Sub BindBranches()
If AuthenticatedUser.IsCorporateAdmin Then
Dim branches As New BranchCollection
branches.Load()
ddlBranch.DataSource = branches
ddlBranch.DataTextField = "BranchDescription"
ddlBranch.DataValueField = "BranchName"
ddlBranch.DataBind()
Else
Dim myBranch As New Branch(AuthenticatedUser.Division)
ddlBranch.Items.Clear()
ddlBranch.Items.Add(New ListItem(myBranch.BranchDescription, myBranch.BranchName))
ddlBranch.Enabled = False
End If
End Sub
Private Sub BindCollectorTypes()
Dim types As New OrderTypeCollection
types.Load()
ddlCollectorType.DataSource = types
ddlCollectorType.DataTextField = "eb_order_description"
ddlCollectorType.DataValueField = "eb_order_type"
ddlCollectorType.DataBind()
End Sub
Private Sub BindErrorCodes()
Dim codes As New KDOE_Library.BusinessLayer.ErrorTypeCollection
codes.Load()
ddlErrorCode.DataSource = codes
ddlErrorCode.DataTextField = "eb_error_desc"
ddlErrorCode.DataValueField = "eb_error_type"
ddlErrorCode.DataBind()
End Sub
Private Sub BindResults()
Dim results As New ConfirmationHeaderCollection()
results.Search(SearchCollector, SearchConfirmationNumber, SearchBranch, SearchCustomerNumber, SearchInvoiceNumber, _
SearchDsrNumber, SearchDsmNumber, SearchNationalAccountNumber, SearchContract, SearchErrorType, _
SearchOrderType, SearchStartDate, SearchEndDate)
results.SortExpression = TranslateSortExpression(SortColumn)
results.SortDirection = IIf(SortDirection.Equals(SORT_DIRECTION_ASC), _
ConfirmationHeaderCollection.SortOrder.Ascending, _
ConfirmationHeaderCollection.SortOrder.Descending)
results.Sort(results)
dgResults.DataSource = results
dgResults.DataBind()
lblResultCount.Text = String.Format("{0} records found", results.Count.ToString("#,###,###"))
End Sub
Private Sub BindTransmissionTypes()
Dim transTypes As New TransTypeCollection
transTypes.Load()
ddlOrderType.DataSource = transTypes
ddlOrderType.DataTextField = "eb_trans_desc"
ddlOrderType.DataValueField = "eb_trans_type"
ddlOrderType.DataBind()
End Sub
Private Sub HideAllColumns()
For i As Integer = 0 To dgResults.Columns.Count - 1
dgResults.Columns(i).Visible = False
Next
End Sub
Private Sub ManageGridColumns()
HideAllColumns()
Dim columns() As String = GetColumnList()
For i As Integer = 0 To columns.Length - 1
Try
dgResults.Columns(CInt(columns(i))).Visible = True
Catch
' do nothing if an error is detected because it indicates a dirty cookie
End Try
Next
End Sub
Private Sub SetupColumnWindow()
Dim columns() As String = GetColumnList()
For i As Integer = 0 To columns.Length - 1
Try
Select Case CInt(columns(i))
Case COL_COLLECTOR
chkCollector.Checked = True
Case COL_CONF_NUM
chkAckNumber.Checked = True
Case COL_NODE_NUM
chkNodeNumber.Checked = True
Case COL_ORDER_TYPE
chkOrderType.Checked = True
Case COL_CUST_NUM
chkCustNumber.Checked = True
Case COL_CUST_NAME
chkCustName.Checked = True
Case COL_ERROR_IND
chkOrderExceptions.Checked = True
Case COL_DSR_NUM
chkDsrNumber.Checked = True
Case COL_DSR_NAME
chkDsrName.Checked = True
Case COL_DSM_NUM
chkDsmNumber.Checked = True
Case COL_DSM_NAME
chkDsmName.Checked = True
Case COL_CONTRACT
chkContract.Checked = True
Case COL_NA_NUM
chkNationalAcct.Checked = True
Case COL_NA_SUB
chkNatAcctSub.Checked = True
Case COL_INV_NUM
chkInvoiceNumber.Checked = True
Case COL_CONF_DATE
chkAckDateTime.Checked = True
Case COL_LINE_ITEMS
chkLineItem.Checked = True
Case COL_DELV_DATE
chkDeliveryDate.Checked = True
Case COL_SALES_AMT
chkSalesAmount.Checked = True
Case COL_BRANCH
chkBranch.Checked = True
Case Else
' do nothing
End Select
Catch
' do nothing because the entry is not an actual column number
' i.e. the cookie has dirty data
End Try
Next
End Sub
Private Sub SetDsmInfo()
If AuthenticatedUser.IsDsm Then
Dim theService As New DsmService.DsmService
theService.PreAuthenticate = True
theService.Credentials = New System.Net.NetworkCredential("someuser", "somepassword", "somedomain")
Dim myDsm As DsmService.Dsm = theService.GetDsmByName(AuthenticatedUser.FirstName, AuthenticatedUser.LastName)
If IsPostBack Then
SearchDsmNumber = myDsm.DsmNumber
Else
txtDsmNumber.Text = myDsm.DsmNumber
End If
txtDsmNumber.Enabled = False
Else
'txtDsmNumber.Text = String.Empty
SearchDsmNumber = String.Empty
txtDsmNumber.Enabled = True
End If
End Sub
Private Sub SetSearchWindow()
Try
ddlBranch.SelectedValue = SearchBranch
ddlCollectorType.SelectedValue = SearchCollector
txtAckNumber.Text = SearchConfirmationNumber
txtNationalAccountNumber.Text = SearchNationalAccountNumber
txtCustomerNumber.Text = SearchCustomerNumber
txtInvoiceNumber.Text = SearchInvoiceNumber
txtContract.Text = SearchContract
ddlOrderType.SelectedValue = SearchOrderType
txtDsrNumber.Text = SearchDsrNumber
txtDsmNumber.Text = SearchDsmNumber
ddlErrorCode.SelectedValue = SearchErrorType
txtStartDate.Text = SearchStartDate
calStartDate.SelectedDate = CDate(SearchStartDate)
txtEndDate.Text = SearchEndDate
calEndDate.SelectedDate = CDate(SearchEndDate)
Catch
' do nothing because an error would be caused by dirty data from the cookie
End Try
End Sub
Private Function TranslateSortExpression(ByVal SortExpression As String) As ConfirmationHeaderCollection.SortColumn
Dim retVal As ConfirmationHeaderCollection.SortColumn = ConfirmationHeaderCollection.SortColumn.eback_datetime
Select Case SortExpression
Case "ebcollector"
retVal = ConfirmationHeaderCollection.SortColumn.ebcollector
Case "eback"
retVal = ConfirmationHeaderCollection.SortColumn.eback
Case "ebnode"
retVal = ConfirmationHeaderCollection.SortColumn.ebnode
Case "ebordertype"
retVal = ConfirmationHeaderCollection.SortColumn.ebordertype
Case "ebcust"
retVal = ConfirmationHeaderCollection.SortColumn.ebcust
Case "CustomerName"
retVal = ConfirmationHeaderCollection.SortColumn.CustomerName
Case "eberror"
retVal = ConfirmationHeaderCollection.SortColumn.eberror
Case "ebslm"
retVal = ConfirmationHeaderCollection.SortColumn.ebslm
Case "DsrName"
retVal = ConfirmationHeaderCollection.SortColumn.DsrName
Case "DsmNumber"
retVal = ConfirmationHeaderCollection.SortColumn.DsmNumber
Case "DsmName"
retVal = ConfirmationHeaderCollection.SortColumn.DsmName
Case "ebcontract"
retVal = ConfirmationHeaderCollection.SortColumn.ebcontract
Case "ebna"
retVal = ConfirmationHeaderCollection.SortColumn.ebna
Case "ebnasub"
I think that I have found the answer. The cookie hasn't been removed in a while, so this looks like it. I tried several other things trying to find the issue, and I had finally given up on finding the solution by tweaking my code, so I took to the internet. It was on MS's website that I found this little gem.
If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client computer. For example, non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk.
http://msdn.microsoft.com/en-us/library/ms178194.aspx
So the issue here is the fact that the cookie has an expiration date when the cookie is initially created. However, reading the cookie from the Request object does not include the expiration date. So, I fixed it by setting the expiration date before adding the cookie back to the Response object.

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