Site Search:
Sign in | Join | Help
4Penny.net

ASP.NET

Notes, Tricks and Tips on ASP.NET Coding
  • Querying Active Directory From .NET

    On a recent project, I needed to query Active Directory to get a list of people in a specific group.  I didn't find much sample code for this so i thought i'd post what I figured out. 

    This function returns the users in the current active directory group.  It does this by getting a list of all the users and checking what group they are in.

    The group itself lists what users are in it, but it stores the display name not the user name.

    This code may not be scalable, but it worked for us. I read, but haven't tested, that ldap queries limit to 1000 results so this may be a problem if there are more than 1000 users.

     

    Imports System
    Imports System.Web.Security
    Imports System.Collections.Generic
    Imports System.DirectoryServices
    
    
    
    ....
    
    
     Public Function GetUsersInRole(ByVal roleName As String) As String()
    
    
        Dim entry As New DirectoryEntry("LDAP://domainControllerName/DC=domain,DC=com")
        Dim search As New DirectorySearcher(entry)
    
    
        'Selecting the properties to load is for performance.
        search.PropertiesToLoad.Add("UserPrincipalName")
        search.PropertiesToLoad.Add("MemberOf")
    
    
    
        Dim users As New List(Of String)
    
    
        Dim result As SearchResultCollection = search.FindAll()
    
    
        For Each i As SearchResult In result
            Dim props_col As ResultPropertyCollection
            props_col = i.Properties
    
    
            'not all of the results are users.  We only want properties that
            'have a username.  This could probably be fixed with a better 
            'initial query, but it works :)
            If props_col.Item("UserPrincipalName").Count > 0 Then
    
    
                'get the username
                'It looks like corey@devshed.local
                'We want everything before the @
                Dim username As String = CType(props_col.Item("UserPrincipalName")(0), String).Split("@")(0)
                Dim usergroups As New List(Of String)
    
    
                For Each j In props_col.Item("MemberOf")
                    'the property looks like 
                    'CN=Domain Admins,CN=Users,DC=devshed,DC=local
                    'We want to get just what the first CN is, Domain Admins
    
    
                    usergroups.Add(j.ToString().Split(",")(0).Substring(3))
    
    
                Next
    
    
                'if the user is a member of the group, add them to the list
                If usergroups.Contains(roleName) Then
                    users.Add(username)
                End If
    
    
            End If
    
    
        Next
    
    
        Return users.ToArray()
    
    
     
    
    
    End Function

  • Sending Email from a Contact Page

    We set up many basic websites for people and have found ourselves reproducing the same code many times.  Typically we are given a basic html website created by our artists with a non-functional "contact us" page.

    We would then copy all of the files into a visual studio solution and create a new contact page.  In the code behind, we would pull the individual form fields and build an email message.  We would then send it through our local mail server.

    To speed up development time a bit, we created a dll that will send the email in one line of code.  Add this to the load event of the contact page:

    If IsPostBack Then
        Dim mail As New SendMail(Request, Response, "to-address@email.com", "from-address@website.com", "emailServerName", "thankyou.html")
    End If

    We pass the Request object so that the dll can get the form fields, ie Request.Form("FirstName").  The Response object is passed so that the dll can redirect to the thankyou page.

    Here is the code for the dll:

     Imports System.Web
    Imports System.Web.UI.Page
    Imports System.Collections.Specialized
    Imports System.Collections.Generic
    Imports System.Net.Mail
    
    
    Public Class SendMail
    
    
        'remove access to the default constructor
        Private Sub New()
    
    
        End Sub
    
    
        Public Sub New(ByVal r As HttpRequest, ByVal resp As HttpResponse, ByVal ToAddress As String, ByVal FromAddress As String, ByVal EmailServer As String, ByVal RedirectLocation As String)
    
    
            Dim fields As List(Of String) = LoadFormFields(r.Form)
            sendEmail(BuildEmail(ToAddress, FromAddress, "Website Form", fields), EmailServer)
    
    
            resp.Redirect(RedirectLocation)
    
    
        End Sub
    
    
        Public Function LoadFormFields(ByVal nvc As NameValueCollection) As List(Of String)
            Dim fields As New List(Of String)
            If nvc.Count > 0 Then
                For Each s As String In nvc.AllKeys
                    If s <> "__VIEWSTATE" Then
                        fields.Add(s + ": " + nvc(s))
                    End If
                Next
            End If
            Return fields
        End Function
    
    
        Public Function BuildEmail(ByVal ToAddress As String, ByVal FromAddress As String, ByVal Subject As String, ByVal fields As List(Of String)) As MailMessage
            Dim m As New MailMessage(FromAddress, ToAddress)
            m.Subject = Subject
            For Each s As String In fields
                m.Body = m.Body + s + vbCrLf
            Next
            Return m
        End Function
    
    
        Public Sub sendEmail(ByVal m As MailMessage, ByVal EmailServer As String)
            Dim serv As New SmtpClient(EmailServer)
            serv.Send(m)
        End Sub
    
    
    End Class
    
    
    
     

     

  • Sample data access class

    Here is sample code for creating a data access class. It's not ground breaking code <smiles>, it's just handy to have it here when I start a new project

     Imports System.Data
    Imports Microsoft.ApplicationBlocks.Data
    Imports System.Data.SqlClient
    Public Class facIV00300
        Dim m_cs As String
        Public Property ConnectionString() As String
            Get
                Return m_cs
            End Get
            Set(ByVal value As String)
                m_cs = value
            End Set
        End Property
        Sub New(ByVal connectionString As String)
            m_cs = connectionString
        End Sub
        Sub New()
        End Sub
    
    
    
        Function IV00300_SEL_byItem(ByVal strItemNumber As String, ByVal strLocationCode As String) As SqlDataReader
    
    
            Return SqlHelper.ExecuteReader(m_cs, CommandType.StoredProcedure, "_4P_myProc", _
                    New SqlParameter("@Itemnmbr", strItemNumber), _
                    New SqlParameter("@locncode", strLocationCode))
    
    
        End Function
    
    
     
    
    
    
    End Class

More Posts Next page »