Web Design, Programming, Tutorials
Tutorial
Cricket.Net: Part 2 – Design Discussion
Oct 13th
Summary
Cricket.Net is a new open source project that I’ve started on Codeplex. It will be a web application that will be used for tracking software bugs. Cricket.Net will be written in C# using HTML5, ASP.NET MVC 3, Entity Framework 4.1 Code First, StructureMap, and the Onion Architecture. This project will be an example application to demonstrate how to use these technologies together to build a web application from the ground up.
I’ll also be going through using Mercurial both on my system and pushing changes to the Codeplex site.
Cricket.Net Series:
- Part 1: Setting up the initial project
- Part 2: Design Discussion
Part 3: Unit Testing
What will the application do?
I’m going to take a step back before continuing with the code and look at what this application is suppose to do. I don’t need to determine everything up front, instead I’m going to use an Agile approach and lay down some basic requirements for what the system is suppose to do and if those change as the development progresses, that is fine.
Ususally the first thing I do is think about what information the application needs to store. Cricket.Net is a bug tracking program, so it will need to store information on a specific bug and what application the bug occurred in. I’m also going to want to track dates for when the bug was created and resolved, the version of the application the bug occurred in and maybe a list of one or more assignees who are working on resolving the bug.
Next, I’m going to open up Visio and separate these ideas into objects on a database model diagram. Since I’ve already created my solution folder, I’m going to add a folder within it called !Design. I’ll place all of my design files here to keep them with the solution when I update the Mercurial repository.
You don’t necessarily need to create a diagram of the database, you could just write-up the code using Entity Framework: Code First, but it is nice for non-programmers to have something to look at. Also, complex databases with many relationships can be difficult to work with if you don’t have a diagram to look at.
Onion Architecture and StructureMap
Now I’d like to talk for a minute about the Onion Architecture. Structuring an application in this way separates the business logic from the web and infrastructure components in a way that limits their dependencies on each other. Take a look at the following diagram:
The blue boxes represent a project within the solution. The arrows point to their dependencies. Notice how all projects depend on Core. This is where the business logic classes and interfaces are found. Also, notice how the Web project (in this case will be MVC 3) does not depend on Infrastructure (where the database repositories reside). There is an indirect dependency through the DependencyInjection project. This is where StructureMap (or another IoC framework) lives. StructureMap will wire-up the dependencies between the Web and Infrastructure frameworks using the interfaces found in the Core project.
Why go through all this work to setup your project this way? Encapsulation of components that could be replacable in the future makes it easy to upgrade an application to those new componenets. With Onion Architecture you could switch the entire application over to a different database server and only have to modify the database classes found in the Infrastructure project. As long as the interfaces do not change for those classes, the reset of the application will work as it did previously. This can save much time over rewriting the entire application because the db code is embedded everywhere.
The UI component could be changed as well (in this case the Web project) for a console application. The Core and Infrastructure will function the same, but the application would appear totally different.
Projects Summary:
- UnitTests – As the name implies, it contains all unit testing code. The Moq mocking framework will be used here.
- Web – This is the user interface project. This contains the controllers, views, view models, and wrapper classes around MVC or web specific operations.
- Core – This contains all interfaces for the application and business logic including: the domain model and service classes.
- DependencyInjection - This contains the classes needed by StructureMap. StructureMap will register all interfaces and concrete classes used in the application.
- Infrastructure – This contains any IO wrappers or classes using 3rd party projects (including our own common projects).
Unit Testing
When starting a project, I try to get in the habbit of coding a Unit Test first, before anything else. This helps me think about how I want to use a method before I worry about how the method works. This tends to lead to an overall better design of the application. I also try to adhere to the SOLID principles, DRY, and YAGNI by only coding what is needed at the time.
Unit Tests should also be very simple. Test for one condition to be met and pass or fail.
Requirements
- Allow users to manage Applications (including adding different versions for each).
- Allow users to manage their issues.
- Allow users to be managed by users.
- (Managing each of these includes listing, adding, creating, editing, and deleting).
Visit the project site at: http://cricket.codeplex.com.
Download the source code from this post at: http://cricket.codeplex.com/SourceControl/changeset/changes/a115ce901573
Cricket.Net: Part 1 – Setting up the initial project
Oct 12th
Summary
Cricket.Net is a new open source project that I’ve started on Codeplex. It will be a web application that will be used for tracking software bugs. Cricket.Net will be written in C# using HTML5, ASP.NET MVC 3, Entity Framework 4.1 Code First, StructureMap, and the Onion Architecture. This project will be an example application to demonstrate how to use these technologies together to build a web application from the ground up.
I’ll also be going through using Mercurial both on my system and pushing changes to the Codeplex site.
Cricket.Net Series:
- Part 1: Setting up the initial project
- Part 2: Design Discussion
- Part 3: Unit Testing
Prerequisites
To get started, I’ll be using Visual Studio 2010 SP1Rel and ASP.NET MVC 3 Tools Update. Later, I’ll be using Entity Framework 4.1 Update 1 so that I can use Code First. You can either download and install Entity Framework, or we’ll attempt to install this from the Nuget package first.
Creating A New Project
Initially, I’m going to start with the basic MVC package created by Visual Studio. After this package is created, I’m going to create the Mercurial repository so that I can send the code to Codeplex.
- Open Visual Studio 2010.
- Click the File menu, then New, Project.
- In the New Project window, under Installed Templates, expand Visual C# and choose Web. Select the template called “ASP.NET MVC 3 Web Application.” The Name field will be the default name and namespace of your initial project, the Location will be the folder on your C:\ drive where to store your solution, and the Solution Name is the name of your solution folder (if you wish it to be different).

- After clicking OK, the New ASP.NET MVC 3 Project window pops up. I’m going to choose Internet Application so that the tooling will allow me to go ahead and create a Unit Test project also. I’m going to change the name of the Unit Test project to Cricket.UnitTests.

- After Visual Studio finishes creating the project, it should look like the image below. The Internet Application template that we had chosen in the previous step has added some files that will may or may not use, but for now we’ll leave these in the solution and move on to creating the Mercurial repository.

Setting up the Mercurial Repository
If you are unfamiliar with Mercurial, it is a source control application that is very fast and pretty easy to use. Before you can continue with this tutorial, you will need to install at least TortoiseHg to manage the Mercurial repository from Windows Explorer. If you’d also like to work with it from within Visual Studio, you will need VisualHg. If you’d like to know more about what Mercurial can do, check out this video from tekpub.com.
- If you still have your new solution open in Visual Studio, go to the File menu and choose Close Solution.
- Next, browse to the folder where your solution folder is located. (In my case, I need to go to the C:\Users\cjackson\Documents\All Projects\ folder)
- Right-click on the Cricket.Net folder and expand the TortoiseHg context menu and choose Create Repository Here.
- TortoiseHg will display an Init window. Click the Create button to create the repository.
- After the repository has been created, a green check mark icon will appear over the Cricket.Net folder icon.
- Open the Cricket.Net folder and then edit the .hgignore file. This file will tell the repository to ignore certain files/folders that are used by Visual Studio and do not need to be version controlled. Paste the text below into the file and save it.
# use glob syntax syntax: glob *.obj *.pdb *.user *.aps *.pch *.vspscc *.vssscc *_i.c *_p.c *.ncb *.suo *.tlb *.tlh *.bak *.cache *.ilk *.log *.lib *.sbr *.scc [Bb]in [Dd]ebug*/ obj/ [Rr]elease*/ _ReSharper*/ [Tt]humbs.db [Tt]est[Rr]esult* [Bb]uild[Ll]og.* *.[Pp]ublish.xml *.resharper
Next, I’ll save the initial project into the Mercurial repository.
- Return to the folder where your solution is stored. (C:\Users\cjackson\Documents\All Projects\ folder)
- Right-click on the Cricket.Net folder and choose Hg Commit…
- The Cricket.Net commit window will pop up. On the left pane, click the check box at the top to select all files then in the top-right pane, type in a comment for the commit. After you enter whatever comments you wish, click the Commit button to save the current state of the solution.

- Next, for new untracked files, a window may pop up asking to add untracked files. Click Add.
To save the current repository to Codeplex, follow these instructions:
- Return to the folder where your solution is stored. (C:\Users\cjackson\Documents\All Projects\ folder)
- Right-click on Cricket.Net and expand the TortoiseHG context menu and choose Synchronize.
- Under Remote Repository, change the drop down to HTTPS and enter the name of the repository so the URL looks like this (http://hg01.codeplex.com/cricket)
- Click on the
icon to push changes to Codeplex. - Enter your Codeplex username and password when prompted and the files will be uploaded to Codeplex.
Visit the project site at: http://cricket.codeplex.com.
Download the source code from this post at: http://cricket.codeplex.com/SourceControl/changeset/changes/1569d75e695b#
SharePoint 2010: Verify that the Activity Feed Timer Job is enabled
Jan 18th
Here is another warning message that I received after installing SharePoint 2010. To fix this issue, follow these steps:
- Go to Central Administration.
- Click on “Monitoring.”
- Click on “Review job definitions” under “Timer Jobs.”
- Scroll down and click on “User profile service application – activity feed job.”
- Click “Enable.”
Now, you can go back to Central Administration and view the warning message. Click “Reanalyze Now” and after some time the message should go away.
SharePoint 2010: The Unattended Service Account Warning
Jan 18th
After installing SharePoint 2010, you may notice warnings appear from the Health Analyzer after the system has been running for a while.
“The Unattended Service Account Application ID is not specified or has an invalid value.”
To fix this issue:
- Open the Central Administration page.
- Under “Application Management,” click on “Manage service applications.”
- Click on “Secure service application.”
- Next, in the ribbon at the top of the page, click on “Generate New Key.”
- Enter a pass phrase and click OK.
- Now, in the ribbon, click “New.”
- For the Target Application ID, enter a unique identifier such as: TARGET_APPLICATION_ID
- For the Display Name, enter some descriptive name such as: Target Application ID
- Enter your email address.
- Make sure to change the Target Application Type to GROUP.
- Click Next.
- Keep the defaults for the next screen and click Next.
- Enter in your administrator account into the Target Application Administrators and Members fields.
- Click OK.
- Next, go to the Central Administration page.
- Under “Application Management,” click on “Manage service applications.”
- Scroll down and click on “Visio Graphics Service.”
- Click on “Global Settings.”
- Down at the bottom of the page, enter your target ID (TARGET_APPLICATION_ID) into the Application ID field and click OK.
Now, you can go back to your Central Administration page and view the warning messages once again. Open the “Unattended Service Account” message and click “Reanalyze Now.” After some time, the message should go away.
Opening PDF files in SharePoint 2010
Jan 14th
One problem you may be facing if you are new to SharePoint 2010 is how to open PDF files. There are a couple different problems you may have noticed. One: the PDF files do not show a file type icon like the Word or Excel files do, and Two: when you click on a PDF file to open it, you are presented with a dialog box asking you to Save or Cancel.
By default, SharePoint does not recognize PDF files, so we will have to tell it how to recognize the files to display the pretty icon.
The reason the PDF does not open is because of a new header called X-Download-Options that is passed into your browser and if you are using IE 8, a new security feature will block the file from opening.
While we are setting up PDF files, lets go ahead and configure SharePoint’s search engine so that it can crawl the contents of PDF files as well.
Opening PDFs
First, let’s tackle the easiest to fix issue. A SharePoint web application has two modes that it uses to handle browser files: Permissive and Strict. The default mode is Strict and will cause SharePoint to send the X-Download-Options header.
To turn off the header:
- Open your SharePoint Central Administration.
- Click on “Manage web applications.”
- Click on “SharePoint – 80.”
- In the ribbon at the top of the page, click “General Settings.”
- Scroll down the pop up window until you find “Browser file handling” and change the selected value from “Strict” to “Permissive.”
- Click OK to save changes.
Setting Up The Search Engine To Crawl PDFs
- Download Adobe PDF iFilter 9 for 64 bit platforms from Adobe.
- Install iFilter on your SharePoint server (or the server that is running the search service).
- Accept all defaults.
Showing the PDF Icon
- Visit Adobe’s site to download an image of their PDF icon. Save a copy of the 17 x 17 image size to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES\ on your SharePoint server.
- Edit the C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML\DOCICON.XML file on your SharePoint server.
- Scroll down to the <ByExtension> tag and enter the following between the <ByExtension> and </ByExtension> tags:
<Mapping Key=”pdf” Value=”pdficon_small.gif” OpenControl=”" />
* If you want to keep the file organized, check the other keys and enter it in alphabetical order. - Save the XML file.
- Next, open the SharePoint Central Administration site.
- Under “Application Management”, click “Manage service applications.”
- Scroll down the list of applications and click on “Search service application.”
- In the left-hand menu, click “File types.”
- Click “New file type.”
- Enter “pdf” into the “File extension” box and click OK.
- Now, you should be able to scroll down and find your PDF icon.
Now, we’ll need to restart IIS by opening the command prompt on your SharePoint server as Administrator. Type into the command prompt: “iisreset” and IIS will be stopped and restarted.
Running A Full Crawl
- From the Central Administration, under “Application Management”, click on “Manage service applications.”
- Scroll down and click on “Search service application.”
- From the left-hand menu, click “Content Sources.”
- Hover your mouse over the “Local SharePoint sites” record and click the down arrow for more options.
- Select “Start full crawl”
Now, you should be able to open PDF files, see adobe icons next to them in library web parts, and be able to search the contents using SharePoint’s search engine.
Installing SharePoint 2010
Jan 13th
Here is the installation process that I used for setting up SharePoint 2010 using MSSQL 2005 as the backend database.
First, you must make sure if you are going to use SQL 2005 instead of 2008, that your SQL server is patched to a compatible level for SharePoint.
Updating Microsoft SQL 2005
First thing you need to do is make sure your SQL server is patched up. I ended up using the SQL 2005 SP3 Update 6 found on Microsoft’s site. You need to make sure you select the 64 bit version. To do that, you must click on the “Show hotfixes for all platforms and languages (14)” link above the list of files. This will display all the files available.
Check the one marked “SQL_Server_2005_SP3_Cumulative_Update_6″ with the x64 platform type. Enter your email and submit the form to have the download link sent to you. The link will contain a password protected self-extracting program, so make sure to get the password from the email.
Copy this patch over to your server and install it. The SQL server will need to be restarted afterwards, so do so at a time when you can down it for a few minutes.
After patching my SQL server, the version now shows 9.0.4266 in the SQL Server Management Studio Express.
Setting Up A Service Account
SharePoint 2010 will ask for a service account that it uses to communicate with the database. So, you can go ahead and create your service account in Active Directory, I used svc_sharepoint, and configure SQL 2005 for the new user.
- From the SQL Server Management Studio Express, connect to your database server and open up the Security\Logins folders in the tree.
- Right-click on the Logins folder and choose “New Login”
- For the “Login Name”, enter DOMAINNAME\USERNAME
- Click “Server Roles” on the left-hand side and put a checkmark next to “dbcreator” and “securityadmin”.
- Click OK.
Installing SharePoint 2010
Enter the SharePoint disc into your CD/DVD drive on your server. If it does not start automatically, execute the “Splash.hta” file to see the splash page.
Software Prerequisites
- Click on “Install Software Prerequisites”.
- Accept the default values and start the installation of the secondary programs needed to run SharePoint.
- Click Finish when everything has been installed.
Installation
- Click “Install SharePoint Server.
- Enter your product key. Continue.
- When asked for Standalone or Server Farm, choose Server Farm if this is a production server.
- Next, Mark the circle next to Complete and click Install Now.
- Once everything has finished installing, make sure the “Run the SharePoint Products and Technologies Configuration Wizard now” box is checked and click Close.
Configuring SharePoint
When the configuration wizard starts, you will be asked if services can be started or reset. Choose yes.
- Click “Create a new server farm” if this is your first server, otherwise choose “Connect to an existing server farm.”
- On the next screen, you will need to enter in the name of your database server, as well as the username/password for the service account you had created earlier. I used svc_sharepoint. If your database has not been patched up to a compatible level, you will be stopped right here.
- The next screen will ask you for a passphrase. This is an important password that you will need if you want to add another server to this server farm. So, don’t lose it.
- Next, you’ll be asked to configure the Central Administration web application. You can specify a port number that the admin portion of SharePoint will use. I would use something easy to remember, like 9999. Keep NTLM selected and hit Next.
- If everything looks good on the next page, click Finish.
Farm Configuration
Now, a web page should open up and continue the server farm configuration from there. You will be asked if you want to help make sharepoint better. Make a choice and hit OK.
- Select “Walk me through the settings using the wizard” and hit Next.
- On the next screen, select “use existing managed account” and make sure your service account is selected.
- Scroll down the page and make sure all services are checked with exception of the Lotus Notes Connector. Click Next.
- The web page will process these settings for a little while. Once finished, you will be asked to enter the title and description for your main SharePoint site. Also, you can select a template at the bottom. I would stick with the default “Team Site” template.
- Once this has finished, you will get a summary page telling you what services have been enabled. Click Finish.
Changing Your Site URL
After everything has been configured, you will be sent to the Central Administration page. If you look at your URL, it will show the server name and not the domain address that you would, no doubt, like to use. For this to work, of course, you need to make sure you have added an ALIAS entry in your DNS server that points your domain name to your SharePoint server name.
- Under the left-hand menu, click on “Application Management.”
- Under “Web Applications”, click on “Configure alternate access mappings.”
- In the content area, at the top-right side of the page there is a drop down box next to “Alternate access mapping collection.” Click this drop down and select “Change alternate access mapping collection.”
- Choose one of the sites displayed (SharePoint – 80 or Central Administration).
- Click “Add Internal URLs”
- Enter the URL of your domain name (ex. http://my.domainname.com:port). If this is the Central Administration, you will need to add the port as well. It can be ommitted if it is your port 80 site.
- Choose a zone, such as Intranet, if it applies to what your SharePoint server is used for.
- Click Save.
- Run through the same steps to add the URL for the other site.
Now that SharePoint has been installed and configured, you can continue by setting permissions, creating sites and web parts, and building content.
Using the Visual Studio 2010 Remote Debugger with ASP.NET MVC
Nov 4th
Visual Studio Remote Debugging Monitor
To use the remote debugger with ASP.NET MVC applications, you first must run the Visual Studio Remote Debugger Monitor on the server or remote computer.
There are two ways you can do this:
- Copy the monitor’s files to the server or remote computer
- Create a shared folder on your developer client and run the monitor on the server from the share.
I will go through the shared folder method. Share out this folder:
C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\Remote Debugger
If you server is running a 64-bit OS, use the x64 folder. For the 32-bit OS, use the x86 folder.
Setting up the server
- Log into the server and navigate to the shared folder on your developer PC.
- Go into the correct folder for your server’s OS (x86 or x64).
- Run the msvsmon.exe file. If your server’s OS is Windows 2008, you will need to right-click on the file and run as Administrator.
- Open Tools -> Permissions. Make sure that your developer client user is listed here. If not, add the user and click OK. Click Yes to allow the user to debug.
- Copy the name of the server (listed on the first line of the Visual Studio Remote Debugging Monitor).
- Return to your developer client.
Debugging remotely
- Make sure the latest version of your application is published to the server (so your source code will be the same as the executed code).
- From Visual Studio 2010, click Debug -> Attach to process.
- Change the value of the Qualifier field to the name of the server on the Visual Studio Remote Debugging Monitor and click Refresh.
- Under the Available Processes, select “w3wp.exe” and click Attach. If you do not see this process listed, then open a web browser and run your application. After your application has loaded, click the Refresh button and you should see the process.
* If you receive any error messages, you may need to:
- Click Build -> Clean Solution
- Click Build -> Rebuild Solution
- Republish your application to the server
- Click Debug -> Attach To Process
Configuring IIS 6 and ASP.NET MVC
Jan 28th
By default, IIS 6 does not work with ASP.NET MVC and needs to be configured to use wild-card mapping to get MVC’s routing and clean URLs to work correctly. Unfortunately, IIS 6 does take a performance hit because all requests are processed by ASP.NET. Static files, such as images, CSS, and JavaScript are processed as a dynamic page instead of a static one.
Install ASP.NET MVC
Follow the first two steps of the instructions for installing ASP.NET MVC. The third step can be ignored since Visual Studio will not be installed on the server.
Configuring ASP.NET 2.0
First thing to do is open the IIS Manager ->expand your server ->Web Service Extensions folder. Right-click on the white space under the list of Web Service Extensions and select to Add a new Web service extension…
The New Web Service Extension window will pop open. Enter “ASP.NET v2.0.50727″ as the Extension Name and click the Add button. Browse to the C:\Windows\Microsoft.Net\Framework\v2.0.50727 folder and select the aspnet_isapi.dll file. Make sure to check the “Set extension status is Allowed” button before clicking OK.
This will allow your programs to run ASP.NET 2.0, 3.0, and 3.5 versions of the .NET framework.
Configuring Your Web Application
The next thing to do is open the properties of the Web Site where your web application is. Select the ASP.NET tab and select 2.0.50717 in the ASP.NET version drop down box.
Next, click on the Home Directory tab. Click on the Configuration button. Under the Wild-card application maps area, click the Insert button. Browse to the C:\Windows\Microsoft.Net\Framework\v2.0.50727 folder and select the aspnet_isapi.dll file. Uncheck the “Verify that file exists” before clicking OK. Save your changes and your site should now be able to run ASP.NET MVC and use the routes setup by your application.
ASP.NET MVC Using Forms Authentication With LDAP
Oct 23rd
If you are using ASP.NET MVC and you want to authenticate your users against Active Directory using LDAP, you need to do a little work to get everything set up. It is pretty easy to authenticate users with Active Directory using the <Authorize()> attribute, but I ran into some problems when I wanted to authorize a user based on a Windows Group.
Here are the steps I took to be able to authenticate active directory users and authorize their use of actions based on being members to user groups.
Web.Config
Find the authentication tag and change it to the following:
<authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" /> </authentication>
The LoginUrl points to the Controller/Action where the login function is.
UserRepository
This is the class object that does the communication with Active Directory via LDAP. The project where this class resides should also add a reference to the System.DirectoryServices DLL.
Imports System.DirectoryServices
Public Class UserRepository
Private _server As String
Public Sub New(ByVal server As String)
_server = server
End Sub
Public Function GetUser(ByVal userName As String) As Data.User
Dim root As DirectoryEntry = New DirectoryEntry("LDAP://" + _server)
Dim search As DirectorySearcher = New DirectorySearcher(root)
search.SearchScope = SearchScope.Subtree
search.Filter = "(sAMAccountName=" + userName.Substring(userName.IndexOf("\") + 1) + ")"
Dim results As SearchResultCollection = search.FindAll()
Return _GetUser(results(0).Path)
End Function
Public Function GetUserByFullName(ByVal fullName As String) As Data.User
Dim root As DirectoryEntry = New DirectoryEntry("LDAP://" + _server)
Dim search As DirectorySearcher = New DirectorySearcher(root)
search.SearchScope = SearchScope.Subtree
search.Filter = "(displayName=" + fullName + ")"
Dim results As SearchResultCollection = search.FindAll()
Return _GetUser(results(0).Path)
End Function
Public Function GetMembers(ByVal groupPath As String) As IQueryable(Of Data.User)
Dim root As DirectoryEntry = New DirectoryEntry("LDAP://" + _server)
Dim search As DirectorySearcher = New DirectorySearcher(root)
Dim members As List(Of Data.User) = New List(Of Data.User)()
search.SearchScope = SearchScope.Subtree
search.Filter = "(memberOf=" + groupPath + ")"
Dim results As SearchResultCollection = search.FindAll()
For Each result As SearchResult In results
members.Add(_GetUser(result.Path))
Next
root.Close()
Return members.AsQueryable
End Function
Public Function Authenticate(ByVal userName As String, ByVal password As String) As Data.User
Dim root As DirectoryEntry = New DirectoryEntry("LDAP://" + _server, userName, password)
Dim search As DirectorySearcher = New DirectorySearcher(root)
Dim user As User = Nothing
search.SearchScope = SearchScope.Subtree
search.Filter = "(sAMAccountName=" + userName + ")"
Dim results As SearchResultCollection = search.FindAll()
If (Not (results Is Nothing)) Then
user = _GetUser(results(0).Path)
End If
Return user
End Function
Private Function _GetUser(ByVal userPath As String) As Data.User
Dim entry As DirectoryEntry = New DirectoryEntry(userPath)
Dim user As Data.User = New Data.User()
user.UserName = entry.Properties("sAMAccountName").Value
user.FirstName = entry.Properties("givenname").Value
user.LastName = entry.Properties("sn").Value
user.Email = entry.Properties("mail").Value
For Each group In entry.Properties("memberOf")
user.Groups.Add(_GetGroup(group))
Next
entry.Close()
Return user
End Function
Private Function _GetGroup(ByVal path As String) As String
Dim value As String = ""
Dim index1 As Integer = path.IndexOf("=", 1)
Dim index2 As Integer = path.IndexOf(",", 1)
If (Not (index1 = -1)) Then
value = path.Substring((index1 + 1), (index2 - index1) - 1)
End If
Return value
End Function
End Class
User
This class hold the user information that we want to work with from Active Directory. Here I am storing the username, first and last names, email address, and the list of groups the user is a member of.
This class is in my Data project and that is why you will see Data.User in the UserRepository. If you want everything to be in one project, you could create the Data namespace around the User class. I did run into problems with MVC getting confused between my User class and a built in one if I did not specify the namespace. You could also simply rename the User class to something else.
Public Class User
Private _userName As String
Private _firstName As String
Private _lastName As String
Private _email As String
Private _groups As List(Of String)
Public Property UserName() As String
Get
Return _userName
End Get
Set(ByVal value As String)
_userName = value
End Set
End Property
Public Property FirstName() As String
Get
Return _firstName
End Get
Set(ByVal value As String)
_firstName = value
End Set
End Property
Public Property LastName() As String
Get
Return _lastName
End Get
Set(ByVal value As String)
_lastName = value
End Set
End Property
Public Property Email() As String
Get
Return _email
End Get
Set(ByVal value As String)
_email = value
End Set
End Property
Public Property Groups() As List(Of String)
Get
Return _groups
End Get
Set(ByVal value As List(Of String))
_groups = value
End Set
End Property
Public Sub New()
Me.UserName = ""
Me.FirstName = ""
Me.LastName = ""
Me.Email = ""
Me.Groups = New List(Of String)()
End Sub
Public Function GetFullName() As String
Dim s As System.Text.StringBuilder = New System.Text.StringBuilder()
If (Not (Me.FirstName = "")) Then
s.Append(Me.FirstName)
s.Append(" ")
End If
s.Append(Me.LastName)
Return s.ToString()
End Function
Public Function SerializeGroups() As String
Dim text As String = ""
For Each item In Groups
If (text = "") Then
text = item
Else
text = text + "|" + item
End If
Next
Return text
End Function
End Class
AccountController
Next is the controller that handles signing in and out of the application. I’ve simplified this controller code for the sake of simplicity. Under normal circumstances, I would have the controller communicate to a service class that then interacts with the repository. The service class could do validation on the login form before attempting to authenticate empty user and password strings.
Imports System.Globalization
Imports System.Security.Principal
Imports S3.Data
<HandleError()> _
Public Class AccountController
Inherits System.Web.Mvc.Controller
'data members.
Private _userRepository as UserRepository
Private _formsAuthentication As IFormsAuthentication
Public Sub New()
_userRepository = New UserRepository(ConfigurationManager.AppSettings("LDAPServer")
_formsAuthentication = New FormsAuthentication()
End Sub
'GET: /Account/LogOn
Public Function LogOn() As ActionResult
Return View("LogOn")
End Function
'POST: /Account/LogOn
<AcceptVerbs(HttpVerbs.Post)> _
Public Function LogOn( _
ByVal userName As String, _
ByVal password As String, _
ByVal rememberMe As Boolean, _
ByVal returnUrl As String) As ActionResult
Dim result As ActionResult = View("LogOn")
Dim user As User = _userRepository.Authenticate(userName, password)
If (Not (user Is Nothing)) Then
_formsAuthentication.SignIn(user, rememberMe)
If (returnUrl Is Nothing) Then
result = RedirectToAction("Index", "Home")
Else
result = Redirect(returnUrl)
End If
End If
Return result
End Function
Public Function LogOff() As ActionResult
_formsAuthentication.SignOut()
Return RedirectToAction("Index", "Home")
End Function
End Class
FormsAuthentication
The next class is the FormsAuthentication class. The main reason that I made this code a class of its own is for the sake of unit testing my project. During unit testing, the commands that deal with writing and clearing the cookie would error out. To get around this, I created an empty FormsAuthenticationTest class that does nothing for the SignIn and SignOut methods. Note: The example code does not show the interfaces. Check out the repository pattern and factory pattern to see how to setup services and repositories for unit testing.
After a user has been authenticated by the UserRepository, the controller passes the returned user into the SignIn method of the FormsAuthentication. This method then stores the user’s full name and serialized groups in a cookie. The list of groups is serialized by creating a string with each group name separated by a “|” character. This serialization takes place in the User object.
Imports System.Web.Security
Public Class FormsAuthentication
Public Sub SignIn(ByVal user As Data.User, ByVal createPersistentCookie As Boolean)
Dim authTicket As System.Web.Security.FormsAuthenticationTicket = _
New System.Web.Security.FormsAuthenticationTicket( _
1, _
user.GetFullName(), _
Now, _
Now.AddMinutes(60), _
createPersistentCookie, _
user.SerializeGroups())
Dim encryptedTicket As String = System.Web.Security.FormsAuthentication.Encrypt(authTicket)
Dim authCookie As HttpCookie = New HttpCookie( _
System.Web.Security.FormsAuthentication.FormsCookieName, _
encryptedTicket)
If (createPersistentCookie) Then
authCookie.Expires = authTicket.Expiration
End If
HttpContext.Current.Response.Cookies.Add(authCookie)
End Sub
Public Sub SignOut()
System.Web.Security.FormsAuthentication.SignOut()
End Sub
End Class
Global.asax
With the previous code, you should be able to use Forms Authentication to log into your application and authenticate a user against the Active Directory via LDAP. The <Authorize()> attribute will allow you to secure your controller or actions. There’s just one problem. Now, if you want to use <Authorize(Roles:=”GroupName”), your user does not get authorization to the action or controller.
There’s just one change left that we need to make. ASP MVC makes the current logged in user available by accessing the Context.User. When you log into the application MVC is setting the user as authenticated, but no roles or groups have been added to that user. We need to modify the Global.asax file and use the AuthenticationRequest event.
The following code will fire each time an authentication request is triggered. The code will check if the authentication cookie exists and if it does, reads the user’s name and groups from it and stores them in the Context.User so MVC can access the groups.
Private Sub MvcApplication_AuthenticateRequest(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.AuthenticateRequest
Dim cookieName As String = System.Web.Security.FormsAuthentication.FormsCookieName
Dim authCookie As HttpCookie = Context.Request.Cookies(cookieName)
If (Not (authCookie Is Nothing)) Then
Dim authTicket As System.Web.Security.FormsAuthenticationTicket = Nothing
Try
authTicket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value)
If (Not (authTicket Is Nothing)) Then
Dim groups As String() = authTicket.UserData.Split(New Char() {"|"})
Dim id As System.Security.Principal.GenericIdentity = _
New System.Security.Principal.GenericIdentity(authTicket.Name, "LdapAuthentication")
Dim principal As System.Security.Principal.GenericPrincipal = _
New System.Security.Principal.GenericPrincipal(id, groups)
Context.User = principal
End If
Catch ex As Exception
'Do nothing.
End Try
End If
End Sub
And that should be all you need to use FormsAuthentication with LDAP and group authorization.
How to setup CodeIgniter
Jun 30th
Introduction
This article explains the process I go through to setup the CodeIgniter framework and how to configure it so that I can start developing an application.
What is CodeIgniter?
If you don’t already know, CodeIgniter is an MVC framework built on PHP. There are many features and built in functions that make building a web application fairly easy. You can download the current version, 1.7.1, from CodeIgniter.com. Also, check out the very well documented User Guide.
If you are interested in using the Zend library of tools with CodeIgniter, please check out How to use Zend_Search_Lucene with CodeIgniter.
Step-By-Step
For this tutorial, I’m using a WAMP Server running on my local Windows computer. You could just as easily perform these same actions on a web server running PHP, although the paths may be different depending on if you are using Windows or a Linux based server.
Step 1
Download the latest version of CodeIgniter (1.7.1).
Before extracting the files to your server, let’s talk about where to put the files. For security purposes, it is recommended to place the CodeIgniter files outside the path of your web server so those files cannot be accessed by typing in a URL. So, if I access my web server by typing in http://localhost and the web server loads the website at C:\wamp\www\, then I want to place the System folder of CodeIgniter inside the C:\wamp\ folder. Go ahead and extract the System folder from the download package to the C:\wamp\ folder. You can place the System folder in the C:\wamp\www\ folder if you desire. Just make sure to adjust the path name later on.
Step 2
Next, I have decided that I may want to use CodeIgniter for several applications that I develop. To save on hosting space, I can setup all CodeIgniter applications to use the same core framework. First, we need to move some files around from their default locations.
Open the C:\wamp\system\application\ folder. You should see several folders listed here. The default CodeIgniter application is setup for a single application. We will be changing it to run multiple applications. Create a new folder called baseApplication_1234 or something unique. Make a copy of the index.html file and paste it inside baseApplication_1234. Next, move all of the folders located at C:\wamp\system\application\ into C:\wamp\system\application\baseApplication_1234\.
We will configure this base application with all of our default settings that we want to use for all CodeIgniter applications. Then, when you want to make a new application, you can simply copy the baseApplication_1234 and rename it.
Step 3
Next, we will configure the CodeIgniter application files.
Browse to C:\wamp\system\application\baseApplication_1234\config\ and open the following:
autoload.php
Modify line 42 to show:
$autoload['libraries'] = array('database', 'session');
config.php
Modify line 14 to show (change localhost to your domain name):
$config['base_url'] = "http://localhost/";
Modify line 26 to show:
$config['index_page'] = "index.php?";
This line will be very important for the way our URLs are displayed later on.
Modify line 44 to show:
$config['uri_protocol'] = "QUERY_STRING";
Modify line 57 to show (this is optional if you want a .html to be shown on the end of your URLs):
$config['url_suffix'] = ".html";
Modify line 220 to show (add your own unique value within the quotes):
$config['encryption_key'] = "12345";
Modify lines 234 – 241 to show:
$config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_encrypt_cookie'] = TRUE; $config['sess_use_database'] = TRUE; $config['sess_table_name'] = 'ci_sessions'; $config['sess_match_ip'] = TRUE; $config['sess_match_useragent'] = TRUE; $config['sess_time_to_update'] = 300;
This will require that we have a database and a table within called ci_sessions. This table will need to have certain fields that CodeIgniter will be attempting to write session data to for each users who visits your site. I’ll explain more later on.
database.php
Modify lines 41 – 45 to show:
$db['default']['username'] = "dbuser"; $db['default']['password'] = "mypassword"; $db['default']['database'] = "mydbname"; $db['default']['dbdriver'] = "mysql"; $db['default']['dbprefix'] = "dev_";
You will need to enter your correct username, password, database name, and prefix if you wish to use one. If you use a prefix, you will need to have a table called dev_ci_session instead of ci_session.
routes.php
For the base application, the routes.php file is probably OK. There are two lines that need to be modified when you build an application.
$route['default_controller'] = "welcome"; $route['scaffolding_trigger'] = "12345";
Again, use some unique value for the scaffolding_trigger. If you use a value that is hackable or nothing at all, your application will have a possible security hole. The default controller name can be changed here as well.
Step 4
There are two helper files that I add to my projects that help translate the URLs the way I like them (http://localhost/controller/action/id.html).
MY_form_helper.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('form_open'))
{
function form_open($action = '', $attributes = '', $hidden = array())
{
$CI =& get_instance();
if ($attributes == '')
{
$attributes = 'method="post"';
}
//Modify ->site_url to ->item('base_url').$action
$action = ( strpos($action, '://') === FALSE) ? $CI->config->item('base_url').$action : $action;
$form = '<form action="'.$action.'"';
$form .= _attributes_to_string($attributes, TRUE);
$form .= '>';
if (is_array($hidden) AND count($hidden) > 0)
{
$form .= form_hidden($hidden);
}
return $form;
}
}
?>
MY_url_helper.php
<?php
function redirect($uri = '', $method = 'location', $http_response_code = 302)
{
$CI =& get_instance();
switch($method)
{
case 'refresh' : header("Refresh:0;url=".site_url($uri));
break;
default : header("Location: ".$CI->config->item('base_url').$uri, TRUE, $http_response_code);
break;
}
exit;
}
?>
Create these files and save them to C:\wamp\system\application\baseApplication_1234\helpers\. These functions will override the original CodeIgniter functions and fix some URL rewriting issues.
Step 5
Enabling URL rewriting may depend if your server supports it. Apache has a rewrite_module that must be enabled before this will work. Most hosting providers should already have enabled URL rewriting.
Create a new text file called .htaccess and paste the following code into it:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?$1 [L]
This will redirect all requests on your domain back to the index.php file, unless the actual path does happen to exist, then the server will serve up whatever file/directory is at that location.
Notice the ? behind index.php. The web server is rewriting the pretty URL into a QUERY_STRING that CodeIgniter is expecting and passes in the controller and action as variables such as index.php?var1=this&var2=that.
The .htaccess file should be stored in the C:\wamp\www\ folder or the root of your web site.
Step 6
Next, the database will need to be created and the ci_sessions table created to store the user sessions to.
After you create the MySQL database, run the following SQL and it will create the table for you:
CREATE TABLE `dev_ci_sessions` ( `session_id` varchar(32) NOT NULL, `ip_address` varchar(15) NOT NULL, `user_agent` text NOT NULL, `last_activity` datetime NOT NULL, PRIMARY KEY (`session_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Make sure to remove the “dev_” if you did not setup a dbprefix.
Step 7
Next, for testing purposes, we’ll setup the baseApplication_1234 web application and attempt to run it.
Find the index.php file that came with the CodeIgniter 1.7.1 download. It should be located in the same folder as the system folder and user_guide folder. Copy this file into your web site root at C:\wamp\www\.
Modify line 26 as shown:
$system_folder = "c:/wamp/system";
Modify line 43 as shown:
$application_folder = "application/baseApplication_1234";
This is the line that specifies which application to load.
This index.php file is the main entry point for the application. It will use these modifications to find the C:\wamp\system\ folder and run the correct web application. The only other files that need to be in the C:\wamp\www\ folder are files that HTML needs to be able to access via URLs such as images and JavaScript.
Conclusion
That should be everything. You can now try to open your web application by going to the URL, http://localhost. The default controller is Welcome and the default action is Index, so you can also test http://localhost/welcome/index.html to verify URL rewriting works. Remember the “.html” can be used to hide that PHP is running your web site. In reality, index is an action of the welcome controller and doesn’t need the “.html” to be there at all.
If you run into problems, you can add this line to an action or the controller’s constructor for further information:
$this->output->enable_profiler(TRUE);
Be sure to shut this down when not needed, or it could give your users information you may not wish them to have.

