# Saturday, 27 March 2010

I need to take a CSV file of logins with their emails and verify if these logins exist in our Active Directory.  This can be done several different ways including with powershell but for one reason or another I want/need to do it with .Net.

I will be using an open source library called FileHelpers to make the parsing of the CSV file a snap.  I’m going to skip over the code that uses FileHelpers and focus on the AD lookup.  Check out my previous post on FileHelpers to see how easy FileHelpers makes parsing.

I’m going to use the System.DirectoryServices namespace to lookup AD information.

Let’s look at the AD Lookup class I created to compare the login in the CSV file to AD.

using System;
using System.Collections.Generic;
using System.DirectoryServices;

namespace VerifyUsers
{
    public class ADLookup
    {
        private DirectorySearcher _directoryToSearch;

        public ADLookup()
        {
            DirectoryEntry root = new DirectoryEntry("LDAP://rootDSE");
            string rootName = "LDAP://" + root.Properties["defaultNamingContext"].Value.ToString();
            DirectoryEntry searchRoot = new DirectoryEntry(rootName);
            _directoryToSearch = new DirectorySearcher(searchRoot);
            _directoryToSearch.PageSize = 100;
            _directoryToSearch.SearchScope = SearchScope.Subtree;
            _directoryToSearch.PropertiesToLoad.Add("displayName");
        }

        public bool IsUserInAD(string login)
        {
            _directoryToSearch.Filter = string.Format("(&(sAMAccountName={0})(objectClass=Person))", login);
            SearchResultCollection personFound = _directoryToSearch.FindAll();

            return personFound.Count > 0;
        }
    }
}

I’m using the DirectorySearcher class to look in AD for user information.  In the class constructor I setup the connection information to the LDAP store and set some of the basic properties.

The SearchScope property is important to set to what you need.  I set it to Subtree (which is the default) to have search include the base and it’s children.  If for example, your AD environment has subfolders then you want this set in order to search the subfolders.

In the IsUserInAD method call I setup the query to look for the login name better known as the sAMAccountName in LDAP and I only want it to search Person objects.

Note – If you are creating your own project you will need to add a reference to System.DirectoryServices.

Now let’s get the code running in a console:

using System;
using System.Collections.Generic;

namespace VerifyUsers
{
    class Program
    {
        static void Main(string[] args)
        {
            Parser userParser = new Parser("Users.csv");
            DisplayUsersNotInAD(userParser.Parse());

            Console.ReadLine();
        }

        static void DisplayUsersNotInAD(User[] list)
        {
            ADLookup lookup = new ADLookup();
            foreach (User u in list)
                if (lookup.IsUserInAD(u.login) == false)
                    Console.WriteLine("{0} was not found in AD.", u.login);
        }
    }
}

First, we parse the CSV file using the FileHelpers library.  Then we iterate over the list and display the entries not found in our directory.

The CSV file I am using has three entries and the first two are bogus accounts that don’t exist in AD.  The third entry does.  If the code works correctly we should only have the first two entries reported as not found.

When you run the code you should see:

image

The last entry, kdog, was found in AD.  We can do whatever we need to with the two entries that aren’t in AD.

Download the C# source or VB Source.

Read my previous post on using the open source FileHelpers library to parse CSV files.

Happy Coding!

Posted 03.27.2010  #    Comments [0]  | 
# Saturday, 20 March 2010

Need to parse a text file or perhaps a stream?  Tired of writing parsing code to do this?  Well, for only $19.95….  Ha, ha,  just kidding.  I ran across FileHelpers earlier this week and was impressed.

FileHelpers are a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.
The idea is pretty simple:

You can strong type your flat file (fixed or delimited) simply describing a class that maps to each record and later read/write your file as an strong typed .NET array

The Library also has support for import/export data from differents storages like Excel, Access, SqlServer, etc. – Home page of FileHelpers.com

Setting it up and getting started is very easy.  I’ll walk you through a sample.

I have a CSV file with usernames and email addresses in it.  I need to parse that file and I need to verify the information in the CSV against another data store.  I won’t go into verifying to the other data store for this example.

For the purpose of the exercise, create a new C# console project named FileHelpersSample.

Download version 2.0 and reference the FileHelpers library in your project.

Here’s how our CSV looks:

joeuser,joeuser@email.com
awinter,awinter@summer.com
jdoe,jdoe@welcome.org

HINT - If you are following along and creating this project from scratch be sure to create a file named Users.csv with the above entries in it and put it in your debug/release bin folders.

In your project create a new class called User.  This class will be used to map the CSV file.

using System;
using FileHelpers;

namespace FileHelpersSample
{
    [DelimitedRecord(",")]
    public class User
    {
        public string username;
        public string email;
    }
}

Now create a new class and call it Parser.  This class will invoke the FileHelpers engine to parse the file.  It should look like this:

using System;
using System.Collections.Generic;
using FileHelpers;

namespace FileHelpersSample
{
    public class Parser
    {
        private string _filePath;
        public Parser(string filePath)
        {
            _filePath = filePath;
        }

        public User[] Parse()
        {
            FileHelperEngine engine = new FileHelperEngine();
            return engine.ReadFile(_filePath);
        }
    }
}

The FileHelperEngine uses generics to accept the mapping class.  When the ReadFile method is called on the object it uses the mapping to return an array of User objects.

It’s that easy to parse a CSV file.

Now, let’s complete the sample.  Open the Program.cs file and copy the code below:

using System;
using System.Collections.Generic;

namespace FileHelpersSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Parser userParser = new Parser("Users.csv");
            DisplayUsers(userParser.Parse());

            Console.ReadLine(); 
        }

        static void DisplayUsers(User[] list)
        {
            foreach (User u in list)
                Console.WriteLine("{0} {1}", u.username, u.email);   
        }
    }
}

Run the project and you should see:

image 

That was easy! 

The library can do a lot more than this simple example shows.  Be sure to read their quick starts and samples.  The library can ignore the first and last X number of lines as well as empty lines.  It can ignore/process records based on conditions you set along with many other options.  It even has a tool to create your mapping class.

Download this sample in C# or VB.

Happy Coding!

C# | Open Source | Parsing | Programming | VB
Posted 03.20.2010  #    Comments [0]  | 
# Saturday, 06 March 2010

It’s been almost two years since StackOverflow went live.  The brain child of Jeff Atwood and Joel Spolsky, StackOverflow has fast become the top programming Q & A site and it’s free!

The site is incredibly easy to use, their reputation engine is perfect for ensuring you know you are getting a good or bad answer since the entire community rates both the question and answers.  Answers come fast and the best one is identified very fast as well.  It’s like having a top gun coder in your back pocket for any topic you can think of!  We can’t know everything (unless your Jon Skeet). 

I have found SO to be a great resource for finding answers.  I also frequent it to help answer questions for others.

Happy Coding!

Posted 03.06.2010  #    Comments [0]  | 

cancun

Ah, relaxing in Cancun.  What a trip.  It was like a second honeymoon for my wife and I to slip away for a week to celebrate our 10 year anniversary.  That was a nice time. 

We’re a few years beyond that and I am happy to report our love for each other has grown even more!  We have been blessed with two wonderful children and a host of family support in our hometown of Flagstaff, Arizona.

We are a Christ centered family.  This comes first in our house. "As for me and my house we will serve the Lord" – Joshua 24:15. 

For the last 11+ years I have worked as a developer for Coconino County and the last 3 as team manager.  I do freelance work as well when the right project comes around and time permits.  I am a CIS/CSE graduate of NAU and have been happy to call Flagstaff home for the past 16 years.  It’s a great town to raise a family and if you love the outdoors and all the seasons like I do, it can’t be beat! It may be Arizona but Flagstaff’s elevation is higher than the mile high city (Denver) and we have a mountain range with it’s top peak over 12,000 feet and a ski resort. Living in Flagstaff is great for us. We have a very strong family base and extended church family.  Family is important to us.

I believe I am fortunate when it comes to a career.  That’s because I deeply enjoy software development.  It’s constant challenge is a great outlet for me and I have a strong desire to improve myself and pursue a real craftsmanship in developing software.

I don’t just live and breathe code 24x7.  From a young age my Father instilled in me a love for the outdoors.  Camping, hiking, skiing, rock climbing, etc.  I also like to play disc golf, paintball and I enjoy fishing and archery.  If it involves the outdoors I probably like it.

I decided to create this blog in late 2009 for three reasons.  First, I wanted to share my knowledge and experiences in the hopes it would help someone else as so many blogs have done for me.  Second, it’s an outlet.  I am not shy to talk about what I am passionate about.  Third, I want to be a better writer.  You can’t get better without practice.

As Click and Clack would say, "You’ve wasted another perfectly good hour listening to me".  Thanks and enjoy!

Posted 03.06.2010  #    Comments [0]  | 
# Friday, 05 March 2010

Want to learn ASP.Net MVC?  Perhaps you already started learning it.  I decided to take a side project of mine that I started in Web Forms and completely start over with .Net MVC.  I wanted to document what I did and the resources I found in the hopes that it may help you.  I still have much to learn and master with .Net MVC but so far I am impressed and am happy I decided to branch out and learn something new.  It has made me a better developer and a more well informed developer.  Both good things!

Not sure what ASP.Net MVC is?  Check out this intro video and this overview and then hurry on back.

How I started:

ASP.Net MVC Tutorials and many, many blog posts from Scott Guthrie, Phil Haack, Rob Conery, Jimmy Bogard, Jeffrey Palermo, Eric Hexter, Steven Sanderson, Stephen Walther and these are just the ones I remember.

Books:

I started with ASP.Net MVC In Action and quickly realized that many of it’s topic were over my head.  So I put it down and read ASP.Net MVC Framework Unleashed and Pro ASP.Net MVC Framework and then went back to MVC In Action. 

TIP #1 - When I am learning a new technology I tend to do the examples in the book from scratch.  It takes longer than just downloading their sample code but it helps me absorb it more. 

TIP #2 – Almost all the material I read on ASP.Net MVC touch on or go into detail on Unit Testing, Test Driven Development, Dependency Injection, Inversion Of Control and many other design principles.  If you are not sure what these are you might want to research them a little bit.  The books I recommend do give overviews of these.  One of MVC’s main design goals is for giving control of the application back to the developer and ease of testing.  If you find this even the least bit interesting then keep going!

Samples/Tutorials:

ASP.Net MVC Tutorials – I watched these to get a feel for MVC.  They have a lot of video’s and sample code you can run through.  They did a great job of covering the basics.  Stay here a while, fire up your IDE and peck away on the keyboard with these tutorials.

Nerd Dinner – Perhaps a cult classic or a right of passage?  I for the most part skipped it…. Oooppsss.  No wonder I struggled so hard with MVC in the beginning.  Just kidding.    It was one of the first books and sample apps out.  I skipped it only because I didn’t have it in my Safari Books Online.  I did however take advantage of their free chapter and source code.

Rob Conery – Rob Conery published a set of video’s documenting the development of an eCommerce storefront called MVC StoreFront.  I watched these video’s carefully and read his code carefully.  He then renamed the project to Kona and added a few more screencasts.  Check these out.  I poured through his code to see some of the possibilities that MVC has.  I still don’t understand some of it but Rob’s a much smarter guy than I am. :-)

Starter kits – Check out their Northwind MVC project, period.

Tip #3 – Check out the ASP.Net MVC Tutorials and the MVC storefront screencasts at least! 

Cheat sheets – Elijah Manor published several cheat sheets on MVC that are great to put on your wall or at least keep close at hand while you are learning MVC.

50 ASP.Net MVC Tips – Stephen Walther, author of ASP.Net MVC Framework Unleashed published these nice tips on his blog.

MVC Contrib Project – A bit more advanced but the wizards over at Headspring created this little open source gem.  The ASP.Net MVC In Action’s sample project uses MVC Contrib.  The project is great and I am still digesting a lot of what is in the project.  I especially dig the TestHelper library.  It just makes my job of testing routes a breeze.

I mentioned I used a side project to learn ASP.Net MVC.  I know now that had I not done that I would still be sitting here thinking about learning it.  Why?  I found many things I took for granted with Web Forms were gone in ASP.Net MVC.  Viewstate for example.  I had certainly grown accustom to it.  Another gotcha for me was filling a dropdown list the right way (not directly in the controller).  I truly did have some frustrating points with ASP.Net MVC but only because I had to retrain myself to how the internet really works (Web Forms took care of this for me).  I really am better for it now.  

Tip #4 – Take a tangible project and do it in ASP.Net MVC.  Stick with it.  It is very different from Web Forms if this is where you are coming from.  Please read my post on Confessions of a Web Form Guy Learning ASP.Net MVC if you want a little insight into some of the "aha" moments I had. 

MVC is moving fast, as of this writing they are already on of MVC2 RC2.  A lot of new features are coming our way that make MVC that much sweeter. 

I hope this helps you in your journey!  If you know of some other good resources for ASP.Net MVC please comment on it.

Happy Coding!

Posted 03.05.2010  #    Comments [0]  |