Web Design, Programming, Tutorials
Chris Jackson
This user hasn't shared any biographical information
Homepage: http://www.cmjackson.net
Posts by Chris Jackson
Cricket.Net: Part 3 – Unit Testing
Dec 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
Unit Testing Thoughts
The idea behind unit testing is to write a very simple piece of code to test your business logic for one condition. The test either passes or fails. As you build your application, you may have hundreds or thousands of these tests. By keeping them very simple, and not running any time intensive operations such as I/O, these tests will be able to execute very quickly and give you an indication that your program is working correctly.
Unit Tests become most useful when your application has been completed for a number of months and then a required change is needed. As you modify your code, you can re-run your unit tests to make sure your new modifications have not broken your program in some other area.
The difficult part of unit testing is thinking of all the different angles to test your piece of code.
As you write your tests and develop your application, you will undoubtedly break some of the tests that you had previously written. These will then need to be revised. This is the process you will go through to fully flesh out your application and develop it from a user (of the code) perspective.
I usually begin by writing all my tests against the Controllers since that is the entry point to the things my application will do. I also try to write tests against the requirements of the application only. If you test all of an application’s requirements, then you are making sure the application is doing what your customer wants it to do. There is no need to test 100% of the code you write. As mentioned above, you will break unit tests as you develop your application and continually have to revise them. Revising tests that cover 100% of your code could be very time-consuming.
Unit Test Controller Shell
Since we’ll be testing Requirements, the first thing I do is create a new folder in the Unit Test project called Requirements. There is currently a Controllers folder that we will remove later on.
Next, create a new Class item called ApplicationControllerRequirements.
The new class will need to be modified for unit testing. Below is the basic shell for a unit testing class.
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Cricket.UnitTests.Requirements
{
[TestClass]
public class ApplicationControllerRequirements
{
[TestInitialize]
public void Setup()
{
//This method runs before each test method.
}
#region Test Group
[TestMethod]
public void unit_test_method()
{
//Arrange.
//Act.
//Assert.
}
#endregion
}
}
There are three attributes being used on this class: TestClass, TestInitialize, and TestMethod.
- TestClass – Signals this is a unit testing class.
- TestInitialize – This is an initialization method that is executed before each test method.
- TestMethod – This is a unit test function.
A unit test only tests one condition and there may be many conditions we need to test for, so I like to group my tests together using regions. These can be collapsed out of the way within Visual Studio to make it easier to work on other unit tests without the unwanted ones getting in the way.
Within a test method, there are three things that need to be done:
- Arrange – This consists of any mocking or setup tasks.
- Act – This is the execution of the action you are testing.
- Assert – This is the verification you received the desired result.
Writing The First Unit Test
First we will start with a very simple test against the Index action of the controller. This is the default action that is called if none is specified in the application’s URL.
We’re going to test if the Index controller returns a ViewResult. Notice the compiler now has an error on the “controller” object. This is because we haven’t created it yet. One nice aspect of TDD (Test Driven Development) is you think about how the interface to your code is used, and then develop the code afterwards. Now we know we need to create a “controller” object and it needs to have a method called “Index”.
Since the initialization of the controller will need to be done for nearly all tests in this class, we’ll add that to the Setup() method.
Now the compiler is showing errors on the “ApplicationController” class. We need to create the new controller in the main project.
- Right-click on the Controllers folder in the main project.
- Select Add, then Controller.
- Type in the Controller Name: ApplicationController and click Add. (Leaving the Template set on Empty Controller)
- In your unit test class, add the using statement: using Cricket.Controllers;
- Under the Unit Test method, add a cast to the “Act” line: ViewResult result = (ViewResult)controller.Index();
- Also, don’t forget to change the name of your unit test method to something meaningful. The more description you can put in this method name, the better.
Running Your Test
Ideally, you want to see your test fail first, to make sure you didn’t accidentally write a test that can never fail.
We can quickly test this by adding the following line to our Index method on the ApplicationController:
return RedirectToAction("Index");
A ViewResult is expected in the test, so now it will fail.
After you have verified the test has failed, change the Index method back to the following:
public ActionResult Index()
{
return View();
}
Another Test
Next, we’ll add another very simple test to verify the correct view is being returned from the Index method.
[TestMethod]
public void index_action_should_return_the_index_view()
{
//Arrange.
//Act.
ViewResult result = (ViewResult)controller.Index();
//Assert.
Assert.AreEqual("Index", result.ViewName, "result.ViewName");
}
Running this test will fail because the Index method is not returning a specific view. To change this, modify the Index method to show:
public ActionResult Index()
{
return View("Index");
}
Now the test will pass because we are specifying a view to display.

Final Thoughts
Unit Testing does take some time to get the hang of it. It is well worth it in the long run to know you can modify your program to add new features without breaking the current functionality.
As we develop this application, these tests will become more complex, but by focusing on one result and writing multiple tests for each action, we can work through it.
The empty “Arrange” comment for each of these tests is a place holder for mocking objects we may need to place there in the future. Typically, Unit Testing developers say to place all setup code in the arrange. I like to place common setup tasks that will happen for each test in the “Setup” method where I only have to code them once. If there is a specific setup task needed for a single test, then I will place that under the “Arrange” comment.
Visit the project site at: http://cricket.codeplex.com.
Download the source code from this post at:
http://cricket.codeplex.com/SourceControl/changeset/changes/df77b3e9d546
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#
Unknown Exceptions
Mar 2nd
When I build an ASP.NET MVC application, I like to add my own error handler and serve up some nicer error messages to the users of the systems. I allow for unknown exceptions to be emailed to me along with a stack trace so I can attempt to track them down and resolve unhandled issues.
Today I came across something new. There were two different files that the client browsers from certain users were trying to access on the server.
- /_vti_bin/owssvr.dll
- /MSOffice/cltreq.asp
It appears that these are requests from a browser to look for web discussions on the site being accessed. While this may be fine for a normal user’s browser, it is causing two exceptions to fire each time my application is being accessed.
To resolve this issue using ASP.NET MVC, I added the following code to the Global.asax.vb file at the beginning of the RegisterRoutes method:
routes.IgnoreRoute("_vti_bin/owssvr.dll")
routes.IgnoreRoute("MSOffice/cltreq.asp")
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
Setting up Structure Map
May 14th
StructureMap
If you haven’t heard about dependency injection, it is something you should definitely look into. It can save tons of time when coding.
StructureMap is a dependency injection framework that makes it easy to create new instances of objects and even cache an instance of an object so various references to the object use the same instance. This is very useful with objects such as database connections.
You can download the library from the StructureMap Home Page. The example used in this post is using StructureMap 2.6.1. I’m also using Visual Basic. I had a tough time finding information on how to use StructureMap with Visual Basic, so hopefully, this will help someone else.
Setting Up MVC
When using StructureMap with ASP.NET MVC 1.0, I’ve found it works best if a folder is created in each project; Main, Data, and Service; where the StructureMap files are stored. This keeps them organized and makes them easy to find as you need to update them. A reference to the StructureMap DLL will need to be added to each project as well.
In the main project’s StructureMap folder, the following files are needed:
StructureMapControllerFactory
Imports System.Web.Mvc
Imports StructureMap
Public Class StructureMapControllerFactory
Inherits DefaultControllerFactory
Protected Overrides Function GetControllerInstance(ByVal controllerType As System.Type) As System.Web.Mvc.IController
Return ObjectFactory.GetInstance(controllerType)
End Function
End Class
This class sets up a factory class to get an instance of the StructureMap factory. It will be used to replace MVC’s default controller factory so that StructureMap will be in charge of creating our controllers.
BootStrapper
Imports StructureMap
Imports YourProject.Data
Imports YourProject.Services
Public Class BootStrapper
Public Shared Sub ConfigureStructureMap()
ObjectFactory.Initialize(AddressOf StructureMapRegistry)
End Sub
Private Shared Sub StructureMapRegistry(ByVal x As IInitializationExpression)
x.AddRegistry(New MainRegistry())
x.AddRegistry(New DataRegistry( _ ConfigurationManager.ConnectionStrings("iSeries").ConnectionString, _ ConfigurationManager.ConnectionStrings("Interbase").ConnectionString))
x.AddRegistry(New ServiceRegistry())
x.Scan(AddressOf StructureMapScanner)
End Sub
Private Shared Sub StructureMapScanner(ByVal scanner As StructureMap.Graph.IAssemblyScanner)
scanner.Assembly("YourProjectNamespace")
scanner.Assembly("YourProjectNamespace.Data")
scanner.Assembly("YourProjectNamespace.Services")
scanner.WithDefaultConventions()
End Sub
End Class
This class is where StructureMap is configured. Within the StructureMapRegistry method, each AddRegistry call is made to include each of our project’s registry files, which have yet to be created. We will get to that in a moment, but notice that the DataRegistry is accepting values for connection strings. This is how information can be passed into a class being created by StructureMap when you would like to keep the configuration settings within the Web.config file.
Also, within the StructureMapScanner method, an entry needs to be made to scan each project’s namespace.
MainRegistry
Imports DCS.Data
Imports StructureMap.Configuration.DSL
Public Class MainRegistry
Inherits Registry
Public Sub New()
[For](Of IWebContext)() _
.Use(Of WebContext)()
End Sub
End Class
Each project will have its own registry file where you can specify that Interface-A should create an instance of Class-A. In the example above, I want StructureMap to create an instance of WebContext (from the main project) when it comes across a reference to IWebContext.
In the Data project’s StructureMap folder you will need:
DataRegistry
Imports StructureMap.Configuration.DSL
Imports Spartan.DAO.Database
Public Class DataRegistry
Inherits Registry
Public Sub New(ByVal iSeriesConnectionString As String, ByVal interbaseConnectionString As String)
'Data Connections.
[For](Of YourDataContext)() _
.HybridHttpOrThreadLocalScoped _
.Use(Function() New YourDataContext())
[For](Of DB2Connection)() _
.HybridHttpOrThreadLocalScoped _
.Use(Function() New DB2Connection(iSeriesConnectionString))
[For](Of InterbaseConnection)() _
.HybridHttpOrThreadLocalScoped _
.Use(Function() New InterbaseConnection(interbaseConnectionString))
'Repositories.
[For](Of IShiftRepository)() _
.Use(Of ShiftRepository)()
End Sub
End Class
The DataRegistry is interesting because we are passing in two connection strings from the Web.config file. The first data connection is for Microsoft SQL, the second for DB2 and the third for Interbase. The second and third are using the DB2Connection and InterbaseConnection classes which are home grown database connection class that I wrote. All three of these database connections are being cached by using the .HybridHttpOrThreadLocalScoped property. Using this will make the database cached instance work for both your live program and your unit testing.
The entry under repositories is what all remaining entries would look like within the registry class. Since the data project contains our repositories, they would all be listed here.
And, in the Service project’s StructureMap folder you will need:
ServiceRegistry
Imports StructureMap.Configuration.DSL
Public Class ServiceRegistry
Inherits Registry
Public Sub New()
[For](Of IShiftService)() _
.Use(Of ShiftService)()
End Sub
End Class
The service registry is similar to that of the main project. All service classes found in the service project would be listed here.
Changes to the Global.asax
The last thing to do is setup the Global.asax file to load StructureMap. Make the following changes to the Application_Start method:
Sub Application_Start()
RegisterRoutes(RouteTable.Routes)
'StructureMap
BootStrapper.ConfigureStructureMap()
ControllerBuilder.Current.SetControllerFactory(New StructureMapControllerFactory())
End Sub
Now, the default controller factory used by MVC will be overridden by our StructureMapControllerFactory. When a controller is created, it will now use StructureMap.
So, how do you use this when creating a class? This is the easy part.
StructureMap will use the greediest constructor from your controller, meaning, if you have two constructors, the one with the most parameters will be used. Each parameter references an Interface and sets a class variable for the object. StructureMap uses the registry classes that we setup to map an interface to a real object.
Example Controller
Imports YourProject.Data
Imports YourProject.Services
Imports StructureMap
Public Class ExampleController
Inherits System.Web.Mvc.Controller
Private _shiftService As IShiftService
Private _webContext As IWebContext
Public Sub New( _
ByVal shiftService As IShiftService, _
ByVal webContext As IWebContext)
_shiftService = shiftService
_webContext = webContext
'Initialize service classes.
_shiftSummaryService.Initialize(New ModelStateWrapper(Me.ModelState))
End Sub
...
All that you need to do is create a constructor, pass in all the interface references you need for the controller, then store them in a class variable. If you need to use the ModelState for validation within your service class, the best way I’ve found to do this is use an Initialize function in your service class to pass in the ModelState. This is because the ModelState is not yet created by MVC when the service classes are created by StructureMap.
When StructureMap creates the instance of the ShiftService, it will look at the greediest constructor from that class to create instances for any required parameters. This continues for all classes that are referenced.
Once the solution has been configured to use StructureMap, the only thing you’ll need to maintain will be the registry files as you add new classes and interfaces to your project. Don’t forget to add a registry entry or you will recieve an exception.






