.NET sample LDAP query looking for a specific user name of (smith) and System.DirectoryServices namespace

Here is a sample query that would search for a specific user.  If you want an *GUI* tool to view LDAP and get the correct LDAP path, use ADSIEdit.msc  Its part of the support tools on the w2k/wk2k3 cd.  look for suptools.msi.  this will install some stuff, look for adsiedit.msc once installed.  Once ADSIEdit.msc is opened up.  Look under the domain partition, this is where all user info stuff would be stored.  (be careful in using this tool) on a production Domain Controller however


Imports System.DirectoryServices
Module Module1
    Sub Main()
        GetUserInfo()
    End Sub

 

    Sub GetUserInfo()
      
        Try
            ‘This is a LDAP path to a specific domain controller for LDAP
            ‘Dim enTry As DirectoryEntry = New DirectoryEntry(“LDAP://DC1/OU=MyUsers,DC=Steve,DC=Schofield,DC=com“)
 
            ‘This is a generic LDAP call, it would do a DNS lookup to find a DC in your AD site, scales better
            Dim enTry As DirectoryEntry = New DirectoryEntry(“LDAP://OU=MyUsers,DC=Steve,DC=Schofield,DC=com“)

 

            Dim mySearcher As DirectorySearcher = New
     DirectorySearcher(enTry)
            mySearcher.Filter = “(&(objectClass=user)(anr=smith))”
            Dim resEnt As SearchResult
            Dim rowcomputer As DataRow
            Try
                For Each resEnt In mySearcher.FindAll()
   Console.WriteLine(resEnt.GetDirectoryEntry.Properties.Item(“cn”).Value)
   Console.WriteLine(resEnt.GetDirectoryEntry.Properties.Item(“distinguishedName”).Value)
   Console.WriteLine(resEnt.GetDirectoryEntry.Properties.Item(“name”).Value) 
   Console.WriteLine(resEnt.GetDirectoryEntry.Properties.Item(“givenName”).Value)
   Console.WriteLine(resEnt.GetDirectoryEntry.Properties.Item(“displayName”).Value)
                Next
            Catch f As Exception
                Console.WriteLine(f.Message)
            End Try
        Catch f As Exception
            Console.WriteLine(f.Message)
        End Try
    End Sub
End Module

ADSI and .NET examples of creating AD Distribution Lists Groups and Adding Users to Groups in Active Directory 2003

I’ve not found too many examples of using .NET and ADSI.  I’m writing a .NET application that adds groups(distribution lists) and users to these lists in Active Directory using VS .NET 2003.  Here are few links that I found useful along with a couple of examples that create a group and then adds a user.  I will recommend one book Active Directory Cookbook for Windows Server 2003 and Windows 2000 by Robbie Allen (Author)

Methods in Active Directory by wwwcoder.com (Good examples!)
http://www.wwwcoder.com/main/parentid/272/site/2150/68/default.aspx


AuthenticationTypes Enumeration
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdirectoryservicesauthenticationtypesclasstopic.asp


ADSI LDAP Provider
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adsi/adsi/account_disabled.asp


HOW TO: Add a User to the Local System by Using Directory Services and Visual Basic .NET
http://support.microsoft.com/default.aspx?scid=kb;en-us;306271


BUG: Adding Group Memberships By Using the System.DirectoryServices Namespace Can Truncate Group Members
http://support.microsoft.com/?id=818031


    Sub VerifyDL(ByVal strDLName As String, ByVal strDLDesc As String, ByVal strDomain As String, ByVal strAuthID As String, ByVal strAuthPWD As String)
        Try
     ‘Put the ID and password to authenticate to the domain or pass into the sub from main()
     Dim strAuthID as string = ConfigurationSettings.Appsettings(“authID”)
     Dim strAuthPWS as string = ConfigurationSettings.Appsettings(“password”)
            Dim groupName As String = “MyGroup”
            Dim Description As String = “MyGroup Decription”
            Dim ADsContainer As New DirectoryEntry(“LDAP://DC1/OU=Email,DC=Steve,DC=Schofield,DC=com”)


            ADsContainer.AuthenticationType = AuthenticationTypes.Delegation
            ADsContainer.Username = strAuthID
            ADsContainer.Password = strAuthPWD
            Dim newGroup As DirectoryEntry = ADsContainer.Children.Add(“CN=” + groupName, “group”)
            With newGroup
                .Properties(“saMAccountname”).Value = groupName
                .Properties(“groupType”).Value = 2
                .Properties(“Description”).Value = Description
                .CommitChanges()
            End With
        Catch exp As Exception
            ErrorHandler(exp)
        End Try
    End Sub


    Sub AddUserToDL(ByVal strDLName As String, ByVal strNewUser As String, ByVal strDomain As String, ByVal strAuthID As String, ByVal strAuthPWD As String)
        Try
     ‘Put the ID and password to authenticate to the domain or pass into the sub from main()
     Dim strAuthID as string = ConfigurationSettings.Appsettings(“authID”)
     Dim strAuthPWS as string = ConfigurationSettings.Appsettings(“password”)


            Dim oGrp As DirectoryEntry = New DirectoryEntry(“LDAP://DC1/CN=MySecurtyGroup,OU=Email,DC=Steve,DC=Schofield,DC=com”)
            oGrp.AuthenticationType = AuthenticationTypes.Delegation
            oGrp.Username = strAuthID
            oGrp.Password = strAuthPWD


     ‘BUG: Adding Group Memberships By Using the System.DirectoryServices Namespace Can Truncate Group Members
     ‘http://support.microsoft.com/?id=818031

            oGrp.Invoke(“Add”, New Object() {“LDAP://CN=ANewUser,OU=MyUsers,DC=Steve,DC=Schofield,DC=com”)
            oGrp.CommitChanges()
        Catch exp As Exception
            ErrorHandler(exp)
        End Try
    End Sub

VS .net 2005 – day 3 of using for my content engine project and misc items

I first posted my first impressions of VS.NET on saturday .  Since posting that article a lot of good things has happened.  The only bad news to report is my laptop pretty much can be used to code in VS.NET 2005, not to be used for regular stuff like sending email or posting stuff in .Text blogs.  My IE browser is acting pretty flakey, but is usable.  Enough bad news,  the great thing is my project is coming along and actually can do stuff now.  Compared to vs.net 2002 pre-beta builds, I could never get things to quite work.  With VS 2005 things are coming along nicely, I have two web pages (one in-line code page, one code behind) that do the same thing but allowed me to explore the new default of inline page code vs using *new* code behinds. I have to say, inline code pages remind me of the early 1.0 beta days.  This has a nice comfort feel but does mix code and presentation layer.  I have to admit I don’t like this now. Having things separated is nicer.   Both webpages submit data to the database and the data actually gets there.  Ran into one flakey *feature* in the code behind.  Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load  Notice the Handles Me.Load section, this caused the webpage to post itself twice which was causing two records to be written to the database.  I used the debugger to step through and discovered this nice feature. 


Other things that i’ve gotten used to is the *little web server* that is integrated into vs.net. G. Andrew Duthrie pointed out a great reason to keep this feature, this allows a developer to run as a non-admin on his/her developer machine.  I think this web server is what morfed from cassini, the free web server that is available as part of web matrix.  Not sure if there is way to shutdown these resources after VS.NET is closed or crashed.  Wish they could tie this event so I’d not have to go back and clean up.  Maybe that is targeted for future builds of VS.NET 2005.    I do have a favorable feeling about this feature.


Additional items that have been added are a dropdownlist box, this selects data from a lookup table in the database.  Another cool thing is the freetextbox control is working very seemlessly and rocks personally!   I think in the next day or two the data model will have all the fields I want to capture so I can start to importing production data.  One of the last items i’m adding is dynamic error handling that records errors to the db.  Some of the things that continue to pop up is when I try to add *new items* to the project.  These items just disappear.  I’m glad this project will only have 3 or 4 webpages total.   This will complete phase 1 of getting the data into the database.  Phase 2 will have a windows service that will, on demand or scheduled republish the site.  Other links that I’ve discovered over the last couple of days.


In closing, there is a really good section in MSDN magazine that covers various languages enhancements in vs.net 2005.  As much as I’ve learned over the last few years, it never stop’s amazing how humbled I can feel ready material on various items.  There is one article section on C# 2.0 and generics.  I have NO idea where I would ever use this technique.  Maybe its my VB or scripter background but I’ve read that article at least 5 times and throw the magazine down complaining everytime why I can’t grasp this concept.  As I’ve done in the past, as impatient as I am, my persistance will pay off and eventually when every other developer on the planet uses them.  Only then will i understand this concept and why something like this would be used in my limited world.  Hopefully over the next week there will be pictures of phase 1 w/code samples.


Visual Studio 2005 Developer Center
http://msdn.microsoft.com/vs2005/ 


ASP.NET v2.0: Code-Beside Replaces Code-Behind by Paul Wilson
http://aspalliance.com/244

Whidbey VS.NET 2005 – first impressions – ok beta’s are painful but fun. Its what being a *true* geek is about!

ok i’m a little bit late in jumping on the whidbey bandwagon.  Figured it was time to get going and see what exciting things I’m missing.  Considering my past with the .NET framework,  ASPFree.com was the first website to run the .NET framework back in july 2000 in the pre-pdc release. No visual studio, no intellisense, no web matrix just visual notepad, a lot of reading docs and a command line compiler to get stuff work, people used to call me crazy!.  VS.NET 2002 beta was coming along at the time but was a real pile in pre-alpha days.  Man were those painful but exciting days.  I was really blind to all the pain being in a pre-beta or pre-alpha was all about.  That is quickly coming back but man o man VS.NET 2005 pre-alpha release is pretty decent but still is causing quite a bit of grief.  Learning new ways can be painful but hey, wouldn’t be fun if it just worked. 


I’m going to really complain and say it took me four years to be converted to use those stupid code-behind pages in VS.NET , now MS goes back and gets rid of them by default.  For the purist who actually knows what generic’s are and all the other really complicated stuff most newbie developers don’t (me included). I do agree with separating presentation from actual code.  I used to be one of those people who said code behind was joke, created extra files and was a PITA to migrate from one machine to another.  Now what does MS do,  they go back to a more inline code samples.  Now re-learning what I used to like really sucks, as it stands now i’m trying to do a simple dropdownlist box to a look up table in sql 2000 database. I can’t even get that to work.  OK for those going oh steve, just do a search or look in help.  The help isn’t exactly working, I think that is some fix but it’ll get installed later.  This has the same feeling as my early days, bugs galore but I’m not going to even blame MS. They CLEARLY state, ONLY install VS build on a machine that can be re-formatted and installed from scratch.  To my ignorance or really high hopes my machine wouldn’t be affected,  i installed on my laptop and now my outlook express is fried, will read mail but won’t send emails.  I can’t post stuff to my blog, for those wondering, i remote desktop to another machine and post this stuff.  


I really like what VS.NET has done as far as publishing webpages. For those who know me, I’m an administrator or try to be somewhat a security guy.  One of the biggest holes for security is frontpage extensions (IMO).  My first impression of VS.NET 2002 was, ok you have this great tool but all I can do to publish is use these stupid frontpage extensions.   Sure I’m going to install Frontpage extensions on a internet facing production web server, NOT!.  Give me this great developer tool but still rely on 40 year old technology to publish great code that was done in VS.NET.  They did also provide mapping UNC paths but ok sure, I want all my developers to publish via UNC path to several development web servers.  OK sure! That ain’t real scable in the real world.  Along with the really insecure frontpage methods of publishing webpages, VS 2005 FINALLY include FTP publishing similiar to homesite and macromedia editors among others. Brovo MS, this is a HUGE improvment in publishing works.  Even includes SSL support.  There are many other items but this feature includes the stuff that Web Matrix has built in!  Thanks MS…I’m sure someone on the MS team who does Frontpage extensions truely hates my opinion on frontpage extensions. Nothing personal! :)


Another *interesting feature* of VS .NET 2005 is these *little* web servers that are built into VS.NET.  not sure if these are going to be useful or not.  There are a lot of issues integrating *local* copies of a website into IIS that comes with WinXP or W2k3.  I tried viewing one of the webpages that I was developing and had a few of these annoying little sessions in my task bar.  The jury is still out on this feature but on a scale of 1 to 10, this rates about a 3 in annoying factor.   I haven’t played enough to give a strong opinion either way so its cool for now!


In conclusion, it might appear that my first experience is really rocky with VS .NET 2005.  Of course its going to be, but I’m clearly aware of the pain it can cause along with all the time rebuilding machines.  I really like the new items such as, whiz-bang website templetes is done to have a database driven website in minutes.  VS.NET 2005 isn’t even in beta 1 yet, but things are looking promising.  Its 1000 times better than the early betas of VS.NET 2002.  For now, i’m going to continue playing around trying to get my “content generator” program up and going.  For those who can just review products without having something real to work on, I envy you.  This content generator is going to allow me to have a web-frontend, create articles and store them in a database.  With a little .NET service yet to be written, will pull the content from the database and create a static website.  All I have to do then is maintain the database of content. With a *magic* button re-create the website back to static pages.    For those who want real articles written by professionals Check out these links.


http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/codecompilation.asp 
( written by a real developer G. Andrew Duthie)


http://msdn.microsoft.com/asp.net/whidbey/idechanges.aspx 
( written by Michiel van Otegem genius who runs ASPNL.com)

ADSI .NET references and sample code using the LDAP provider

There are some resources on the internet that finally address using .NET and connecting to resources using ADSI.  Here are a few links that I recently used for writing an application that will query Active Directory using the .NET and the LDAP provider.  As the data is queried, I put the data into an in memory datatable and finally commited to a database.   This is my first experience with the LDAP provider, since I really need to get under the hood on dealing with this provider vs the older WinNT provider because of the active directory work i’m doing..   This sample code is something I came up with. It recurses the entire directory starting at my fake domain name called Steve.Schofield.com  Check out the MS link listed below, this will give you more examples of how to use the .Filter property.   This isn’t anything real hard but thought I’d share, once this is entirely completed I’ll post up what has been completed.  This entire exercise querys the Win32_NetworkAdapterConfiguration WMI class.   Note this code doesn’t show it but here is the WMI query I’m returning.  “SELECT DNSHostName, DefaultIPGateway, DNSServerSearchOrder, DNSDomainSuffixSearchOrder, IPAddress, IPSubnet, MACAddress, WINSPrimaryServer, WINSSecondaryServer FROM Win32_NetworkAdapterConfiguration Where IPEnabled = True”  The real hard thing dealing with this Win32 Class is many of these items datatype are string of array.


Imports System.Management
Imports System.DirectoryServices
Imports System.Net
Imports System.Text


Module Module1
    Sub Main()
        Dim strUID As String = “domainuserid”
        Dim strPWD As String = “password”
        ListComputers(strUID, strPWD)
    End Sub


    Sub ListComputers(ByVal strUID As String, ByVal strPWD As String)
        Dim strPath As String = “LDAP://DC=Steve,DC=Schofield,DC=com“
        Try
            Dim objDomain As DirectoryEntry = New DirectoryEntry(strPath)
            Dim objOU As DirectoryEntries = objDomain.Children
            Dim objOUName As DirectoryEntry
            Dim strSubPath As String


            For Each objOUName In objOU
                strSubPath = objOUName.Name.ToString() & “,DC=Steve,DC=Schofield,DC=com”
                GetServerName(strSubPath)
            Next
            objDomain.Dispose()
        Catch f As Exception
            Console.WriteLine(f.Message)
        End Try
    End Sub


    Sub GetServerName(ByVal strPath As String)
        Try
            Dim enTry As DirectoryEntry = New DirectoryEntry(“LDAP://” & strPath)
            Dim mySearcher As DirectorySearcher = New DirectorySearcher(enTry)
            mySearcher.Filter = “(&(objectClass=computer))”
            Dim resEnt As SearchResult
            Dim rowcomputer As DataRow
            Try
                For Each resEnt In mySearcher.FindAll()
                    Console.Writeline(resEnt.GetDirectoryEntry.Properties.Item(“cn”).Value)
                    Console.WriteLine(resEnt.GetDirectoryEntry().Path.ToString())
                    Console.WriteLine(resEnt.GetDirectoryEntry.Properties.Item(“operatingSystem”).Value)
                Next
            Catch f As Exception
                Console.WriteLine(f.Message)
            End Try
        Catch f As Exception
            Console.WriteLine(f.Message)
        End Try
    End Sub
End Module


Listing All Computers in Active Directory
http://www.vbdotnetheaven.com/Code/May2003/1004.asp


Directory Searcher Class
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdirectoryservicesdirectorysearcherclasstopic.asp


ADSI Scripts resource
http://cwashington.netreach.net/depo/default.asp?topic=adsifaq

Executing an EXE inside a VBScript file that has spaces in the path.

I’ve done quite a bit of scripting but ran across something that baffles me.  Trying to execute a file in a directory with a spaces in the path would bomb.  I googled and found a thing that has me put [] inside to fix it but it didn’t work.  Here is what i was trying to do, if there is no spaces in the path to the EXE including any directories, the script works fine.   Here is an example to a path for an EXE c:winntsystem32Ica PassThroughpn.exe.  Here is the script code


Set wshShell = WScript.CreateObject (“WSCript.shell”)
wshshell.run “c:winntsystem32Ica PassThroughpn.exe”, 6, True
set wshshell = nothing


Of course, this code would BOMB!  The script would return an error complaining it couldn’t find the file.    Thanks to quick posting in the news://msnews.microsoft.public.windows.server.scripting newsgroup. 


Al Dunbar, world famous fellow MVP posted the answer to my prayers!


Your .run command is trying to run something called “C:winntsystem32ica” and pass it a parameter called “PassThroughpn.exe”. This is the same thing you would get if you typed the following at a command prompt:

    c:winntsystem32Ica PassThroughpn.exe

If the name of the file to run is actually “c:winntsystem32Ica PassThroughpn.exe”, you would enter it at the command prompt as:

    “c:winntsystem32Ica PassThroughpn.exe”

The double quotes in your code do not form part of the filename string being passed to the .run method, they are required to indicate a literal string.
You can prove this is the case by changing your script to look like this:

> Set wshShell = WScript.CreateObject (“WSCript.shell”)
> wshshell.run c:winntsystem32Ica PassThroughpn.exe, 6, True
> set wshshell = nothing


Which will throw a syntax error (for rather obvious reasons). You need to pass a string that actually contains the quoted filename, which can be done this way:

> wshshell.run “””c:winntsystem32Ica PassThroughpn.exe”””, 6, True

Within a literal string, a single double-quote character is represented by two double-quote characters.   Notice the Three double quotes around the string,  This worked!  Thought I’d pass this tip along.

Connect to a remote server with different user/password using .NET/WMI

I’ve seen various posts in the newsgroups how to use .NET to connect to a remote server to collect WMI information. 


Dim options As New ConnectionOptions()
options.Username = “DomainUserId”
options.Password = “password”

Dim scope As New ManagementScope(“\ServerNamerootcimv2″, options)
Dim strSVCquery As String = ConfigurationSettings.AppSettings(“NICquery”)

Dim objNICQuery As New WqlObjectQuery(strSVCquery)
Dim objNICsearcher As New ManagementObjectSearcher(scope, objNICQuery)

Dim envVar As New ManagementObject()

Dim objNICItem As PropertyData
Dim strNICColName As String

scope.Connect()
For Each envVar In objNICsearcher.Get
        For Each objNICItem In envVar.Properties
            strNICColName = objNICItem.Name
            If Not IsArray(objNICItem.Value) Then
                Console.WriteLine(“Item is NOT an array — ” & strNICColName)
            Else
                Console.WriteLine(“Item is an array — ” & strNICColName)
            End If
        Next
Next

AWebMonitorService

A Web Monitor Server


This is my own project that I recently did to learn how to write Windows Services using .NET.  This is drop-dead simple using the framework.  Current .25 release # This project is called AWEBMONITORSERVICE. This is written in C# that is designed currently to monitor a single website. This service will email, write to the Event Log or write to a SQL database.

Download source!

Windows 2003 Active Directory anyone!

I spent Sunday afternoon (yes it was 10 degrees where i’m at), reading an ebook from netpro.   This is a six chapter series on Active Directory Troubleshooting.  Good read for those who are doing server admin with Active Directory.  This ebook targets windows 2000 active directory but apply’s to Windows 2003 as well.  My favorite chapter was #4, this chapter covers performance counters to use to help tune and monitor AD along with server counters.  http://www.netpro.com/ebook/index.cfm  is the homepage  These are free however you have to register.    I’d highly recommend anyone to download this good resource. 

Secondly, download the Windows 2003 server resource kit.  http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en  The resource kit is rich in utilities, one of my favorite is called getmac, this gets the MAC address of remote machines, you can even pass credentials.   http://www.microsoft.com/windowsserver2003/techinfo/reskit/resourcekit.mspx  has more info also (IIS 6 resource kit!).


Lastly this is my favorite geek toy of the month!  Microsoft released Services for Unix 3.5 recently w/o an license restrictions or cost.  Download today at http://www.microsoft.com/windows/sfu/downloads/default.asp