Posted by
chris on Jun 1st, 2007 in
Development |
0 comments
So what is this Active Directory thing? It’s Microsoft’s directory service implementation and is used to define domain-level computer network infrastructures for (mostly) corporate networks. Sometimes you might want to use .NET to check inside your Active Directory to see if an email address exists.
Why? Maybe you’re using a .NET application of some sort to create or edit users and you don’t want to try and assign someone an email address that already exists. The following function will return a boolean TRUE if the email address is already assigned to a user and FALSE if it doesn’t.
Public Function ConfirmEmailAddress(ByVal EmailAddress As String) As Boolean
Dim ConfirmEmailAddressResult As Boolean = False
Dim entry As System.DirectoryServices.DirectoryEntry = New System.DirectoryServices.DirectoryEntry(“LDAP://yourdomain.com”)
Dim mySearcher As System.DirectoryServices.DirectorySearcher = New System.DirectoryServices.DirectorySearcher(entry)
mySearcher.Filter = (“(objectClass=user)”)
For Each resEnt As System.DirectoryServices.SearchResult In mySearcher.FindAll()
Try
Dim de As System.DirectoryServices.DirectoryEntry = resEnt.GetDirectoryEntry()
If de.Properties(“Mail”).Value.ToString() = EmailAddress Then
ConfirmEmailAddressResult = True
Exit For
Else
ConfirmEmailAddress = False
End If
Catch ex As Exception
ConfirmEmailAddressResult = False
End Try
Next
entry.Close()
entry.Dispose()
mySearcher.Dispose()
Return ConfirmEmailAddressResult
End Function
An example of how to use it might be when asking a user to enter the requested email address into a Textbox control and you want to confirm that the email address doesn’t exist when they tab out of the Textbox.
<asp:TextBox runat=”server” id=”txtRequestedEmail” Width=”176px” AutoPostBack=”True” OnTextChanged=”RequestedEmailChanged” />
The RequestedEmailChanged method looks like this.
Public Sub RequestedEmailChanged(ByVal sender As Object, ByVal e As EventArgs)
If txtRequestedEmail.Text <> “” Then
If ConfirmEmailAddress(txtRequestedEmail.Text) Then
litEmailConfirm.Text = “Email address already in use”
Else
litEmailConfirm.Text = “”
End If
End If
End Sub
The ‘litEmailConfirm’ in the example above is an ASP.NET literal control within a table cell :
<td class=”formerror”><asp:Literal runat=”server” ID=”litEmailConfirm”></asp:Literal></td>
And here is the ‘formerror’ CSS class :
.formerror
{
color : Red;
font-size: 10px;
font-weight: bold;
font-family: Tahoma;
}
Easy huh?
Leave a Reply