Jay Harris is Cpt. LoadTest

a .net developers blog on improving user experience of humans and coders
Home | About | Speaking | Contact | Archives | RSS
 
Filed under: Learn to Code | Testing | Tools

Aligned with another jam session at Ann Arbor's Come Jam With Us is another installment of Learn to Code, this time providing an introduction to WatiN, or Web Application Testing in .NET. The jam session was held at the offices of SRT Solutions in Ann Arbor, Michigan, at 5:30p, Tuesday April 6th. Though thunderstorms were in the forecast, the predicted high was 72°F (22°C), so we weren't bothered by the same 8" of fluffy white snow that caused cancellations and delays during the my session on ASP.NET MVC 2. But for those that couldn't make the WatiN jam session, might I recommend the exercise below.

About This Exercise

This coding exercise is designed to give you an introduction to browser-based testing using the WatiN framework, or Web Application Testing in .NET. The framework allows developers to create integration tests (using a unit testing framework like MbUnit, NUnit, or MSTest) to test and assert their application within a browser window. The framework interacts with the browser DOM much like and end-user, producing reliable results that mimic the real world. In this sample, we will write a few WatiN tests against the Google search engine.

Prerequisites

To complete this exercise, you will need to meet or complete a few prerequisites. Please complete these prerequisites before moving on. The session is designed to be completed in about an hour, but setup and prerequisites are not included in that time.

  • An active internet connection. (Our tests will be conducted against live third-party sites.)
  • Install Microsoft Visual Studio 2008 or Microsoft Visual Studio 2010.
  • Download and extract the latest version of the WatiN framework.

Exercise 0: Getting Started

Creating a Project

WatiN is generally used within the context of a unit testing framework. For this exercise, we will be using a Visual Studio Test Project and MSTest to wrap our WatiN code.

  1. Create a new "Test Project" in Visual Studio named "WatinSample". The language is up to you, but all of the examples in this post will use C#.
  2. Feel free to delete the Authoring Tests document, the Manual Test file, and UnitTest1.cs. We won't be using these.
  3. Add a reference to WatiN.Core.dll from the bin directory of your extracted WatiN download.
  4. Compile.

Exercise 1: My First Browser Tests

In our first test, we will use the project we just created to test Google's home page. After accessing http://www.google.com, we will check a few properties of the browser and a few loaded elements to ensure that the expected page was returned. The first thing we will need is a new Unit Test class to start our testing.

  1. Create a new class (Right click on the "WatinSample" project and select Add –> Class…), called WhenViewingTheGoogleHomePage.
  2. Mark the class as public.
  3. Add the MSTest [TestClass] attribute to the new class.
  4. Compile.
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace WatinSample
{
  [TestClass]
  public class WhenViewingTheGoogleHomePage
  {
  }
}

Make an instance of the browser

Now that we have a test class, we can start writing WatiN code. Each of our tests will first need a Browser object to test against. Using methods attributed with TestInitialize and TestCleanup, we can create a browser instance before the test starts and shut it down when the test is complete.

Creating an instance of a browser in WatiN is easy: simply create a new instance of the IE class, passing in a URL. We can assign this new class to a field of type Browser, which is a base class of all browser classes in WatiN. Currently, WatiN supports Internet Explorer and Firefox.

  1. Create a private field in the test class named browserInstance of type WatiN.Core.Browser. Add a using statement to WatiN.Core if you wish.
  2. Create a test initialization method named WithAnInstanceOfTheBrowser and give it the [TestInitialize] attribute. Within this method, create a new instance of the IE class, passing in the Google URL, http://www.google.com, and assigning the instance to the browserInstance field.
  3. Finally, create a test cleanup method named ShutdownBrowserWhenDone and give it the [TestCleanup] attribute. Within this method, execute the Close() method on our browser instance and assign the field to null to assist with object disposal.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WatiN.Core;

namespace WatinSample
{
  [TestClass]
  public class WhenViewingTheGoogleHomePage
  {
    Browser browserInstance;

    [TestInitialize]
    public void WithAnInstanceOfTheBrowser()
    {
      browserInstance = new IE("http://www.google.com");
    }

    [TestCleanup]
    public void ShutdownBrowserWhenDone()
    {
      browserInstance.Close();
      browserInstance = null;
    }
  }
}

Our First Tests: Checking for existence of an element

There are three prominent items on the Google home page: the Google logo, the search criteria text box, and the search button. Using WatiN, we can check for them all. The WatiN Browser object contains an Elements collection, which is a flattened collection of every element in the entire DOM. Like any collection, you can use Linq and lambda expressions to search for items within this collection. Alternately, you may also use the Element method, which accepts the same lambda expression that would be used within the Where extension method on the collection, and returns the first or default element. For more specific searches, WatiN's Browser object includes similar collections and methods for searching explicitly for Images (<IMG>), Paras (<P>), Text Fields (<INPUT type="text" />), and so on.

On each returned Element (or derived Para, Image, or Text Field, etc., all of which inherit from Element), WatiN supplies properties for accessing the CSS Class, Id, InnerHtml, Name, Tag, Text, Value, or many other attributes. The method GetAttributeValue(string attributeName) is provided for accessing other attributes that are not explicitly defined on the object (uncommon attributes and custom attributes). Finally, elements also contain a Style property, which not only gives access to the inline style attribute, but also any CSS properties associated with the element from Internal Style (in the Page Head) or External Style (in an external style sheet).

On to checking for the three elements within the Google home page: the logo, the criteria input, and the search button. First, check for the existence of the Google logo graphic. The image can be found by searching the DOM for an image with an Id of "logo". WatiN works very closely with lambda expressions, so we can use these to help us find out graphic.

  1. Create a new public method named PageShouldContainGoogleLogo.
  2. Add the MSTest [TestMethod] attribute to the method.
  3. Search for and assert on the existence of an image with the Id of "logo".
  4. Optionally, we can also check that the image has the expected Alt attribute; in this case, the value should be "Google".
  5. Compile and run the test. The test should pass.
[TestMethod]
public void PageShouldContainGoogleLogo()
{
  Image googleLogo;
  googleLogo = browserInstance.Image(img => img.Id == "logo");
  Assert.IsTrue(googleLogo.Exists);
  Assert.AreEqual("Google", googleLogo.Alt);
}

Next, check for the existence of the search criteria input box. WatiN refers to these elements as Text Fields, using the TextField type. Additionally, this form field is identified by its Name rather than its Id. In Google, the name given to the criteria input is "q".

  1. Create a new public method named PageShouldContainSearchCriteriaInput and give it the [TestMethod] attribute.
  2. Search for and assert on the existence of a Text Field with the name "q".
  3. Compile and run the test. The test should pass.
[TestMethod]
public void PageShouldContainSearchCriteriaInput()
{
  TextField criteriaInput;
  criteriaInput = browserInstance.TextField(tf => tf.Name == "q");
  Assert.IsTrue(criteriaInput.Exists);
}

Finally, check for the existence of the search button using the Button method. In our lambda expression, it is not important to know if the field is identified by a Name property or an Id attribute, as WatiN supplies a IdOrName property to help us find the element. The value to identify the button is "btnG".

  1. Create a new public method named PageShouldContainSearchButton and give it the [TestMethod] attribute.
  2. Search for and assert on the existence of a Button with the Id or Name of 'btnG".
  3. Optionally, we can also check the value of the button, which is the text displayed on the button on-screen. This text should be "Google Search".
  4. Compile and run the test. The test should pass.
[TestMethod]
public void PageShouldContainSearchButton()
{
  Button searchButton;
  searchButton = browserInstance.Button(btn => btn.IdOrName == "btnG");
  Assert.IsTrue(searchButton.Exists);
  Assert.AreEqual("Google Search", searchButton.Value);
}

Working with Style

WatiN can access properties on the DOM beyond just Text values and Alt attributes. WatiN also has full access to the style that CSS has applied to an element. Let's check out a few CSS properties, both those explicitly defined by WatiN and those implicitly accessible through the WatiN framework.

For our first style check, we'll take a look at the default font family used on the Google Home Page. Font Family is one of the explicitly available style properties on a WatiN element. Some others, like Color, Display, and Height are also explicitly defined.

  1. Create a new public test method named BodyShouldUseArialFontFamily.
  2. Assert that the font family assigned to the body matches "arial, sans-serif".
  3. Compile and run the test. The test should pass.
[TestMethod]
public void BodyShouldUseArialFontFamily()
{
  Assert.AreEqual("arial, sans-serif", browserInstance.Body.Style.FontFamily);
}

For our second style check, we will look for an implicit style definition. At the top of the Google Home Page is a series of links to other areas of Google, such as Images, Videos, Maps, and News. At the end of this list is a More link, that when clicked, displays a hidden DIV tag containing even more links, such as Books, Finance, and Google Translate. Since we do not have any code in our test initialization that interacts with the browser, and thus nothing that is clicking the More link, that DIV should still have a hidden visibility. However, since Visibility isn't an explicitly defined style property within WatiN, we need to use the GetAttributeValue method to retrieve the current visibility setting.

  1. Create a new public test method named MoreItemsShouldNotBeVisibleOnPageLoad.
  2. Search for the More Items DIV. It's Id is "gbi".
  3. Using the property lookup method, GetAttributeValue(string attributeName), check that the Visibility is set to "hidden".
  4. Compile and run the test. The test should pass.
[TestMethod]
public void MoreItemsShouldNotBeVisibleOnPageLoad()
{
  var googleBarMoreItems = browserInstance.Div(gbi => gbi.Id == "gbi");
  Assert.AreEqual("hidden", googleBarMoreItems.Style.GetAttributeValue("visibility"));
}

Exercise 2: Interacting with the Browser

Browser Integration tests are more than just loading a page and checking a few element attributes. Our tests may also need to enter values into form fields, click links and buttons, or interact with browser navigation like the back button. WatiN fully supports all of these features in a very intuitive fashion.

A new test class, this time with Search Capability

Create a new test class, similar to what we did in Exercise 1, calling the new test class WhenViewingGoogleSearchResultsForComeJamWithUs. Also add in the TestInitialize and TestCleanup methods that open and close the browser. However, this time, after we load http://www.google.com, enter a value into the search criteria input and then click the Google Search button.

  1. Create a new class named WhenViewingGoogleSearchResultsForComeJamWithUs, similar to what was done in Exercise 1.
  2. Add in the TestInitialize and TestCleanup methods from Exercise 1. Name the Initialize method WithAnInstanceOfTheBrowserSearchingGoogle.
  3. After the code that initializes the IE class, find the search criteria Text Field and set its value to "Come Jam With Us".
  4. After setting the Text Field value, click the Google Search button by calling the Click() method on the Button class.
  5. Compile.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WatiN.Core;

namespace WatinSample
{
  [TestClass]
  public class WhenViewingGoogleSearchResultsForComeJamWithUs
  {
    Browser browserInstance;

    [TestInitialize]
    public void WithAnInstanceOfTheBrowserSearchingGoogle()
    {
      browserInstance = new IE(@"http://www.google.com");
      TextField criteria =
        browserInstance.TextField(tf => tf.Name == "q");
      criteria.Value = "Come Jam With Us";
      Button search =
        browserInstance.Button(btn => btn.IdOrName == "btnG");
      search.Click();
    }

    [TestCleanup]
    public void ShutdownBrowserWhenDone()
    {
      browserInstance.Close();
      browserInstance = null;
    }
  }
}

With this code, or initialized test will load the Google Home Page and will conduct a search for "Come Jam With Us".

Validating the Search Results Page

For our first verification, let's check the URL for the browser window. The search result URL should contain the search criteria in the URL's query string; we can validate this using the URL property on our instance of the Browser object.

  1. Create a new public test method named BrowserUrlShouldContainSearchCriteria.
  2. Validate that the current browser URL contains the search criteria information, "q=Come+Jam+With+Us".
  3. Compile and run the test. The test should pass.
[TestMethod]
public void BrowserUrlShouldContainSearchCriteria()
{
  Assert.IsTrue(browserInstance.Url.Contains(@"q=Come+Jam+With+Us"));
}

Finding Child Elements

With WatiN, we are not just limited to searching for items directly from the Browser object. We can also search for child elements directly from their parent element or any ancestor element. Our search results should contain a search result item linking to the Come Jam With Us web site. The Google Results page contains a DIV identified as "res" that serves as a container for all search result information. Rather than checking that our Come Jam With Us link exists somewhere on the page, we should search for it directly within the results DIV.

  1. Create a new public test method named ResultsShouldContainLinkToComeJamWithUs.
  2. From the browser instance, find a DIV identified as "res".
  3. Assert that a link to http://www.comejamwithus.org exists within the "res" DIV.
  4. Compile and run the test. The test should pass.
[TestMethod]
public void ResultsShouldContainLinkToComeJamWithUs()
{
  Link comeJamWithUs;
  Div searchResults = browserInstance.Div(div => div.IdOrName == "res");
  comeJamWithUs =
    searchResults.Link(link => link.Url == @"http://www.comejamwithus.org/");
  Assert.IsTrue(comeJamWithUs.Exists);
}

Inner Text verses InnerHtml

An element may contain many child elements. An anchor tag—<A href="#">—can contain text, and child elements may make portions of that text bold, italic, underlined, or even bright red. Through WatiN, we can access that inner content as straight text without the formatting, or as the InnerHtml including all of the child elements.

  1. Create two public test methods, one named ResultsLinkContainsComeJamWithUsText and the other named ResultsLinkContainsComeJamWithUsHtml.
  2. In both methods, search for the results DIV, as we did in the previous test.
  3. In both methods, search through the results DIV for a link with a URL matching http://www.comejamwithus.org
  4. In the Text method, assert that the text of the link matches "Come Jam with us (Software Development Study Group)". Note that the value contains no child HTML elements.
  5. In the HTML method, assert that the InnerHtml of the link matches "<EM>Come Jam with us</EM> (Software Development Study Group)". Note that for the same link, we now have the emphasis tags surrounding Come Jam With Us.
  6. Compile and run both tests. The tests should pass.
[TestMethod]
public void ResultsLinkContainsComeJamWithUsText()
{
  Link comeJamWithUs;
  Div searchResults = browserInstance.Div(div => div.IdOrName == "res");
  comeJamWithUs =
    searchResults.Link(link => link.Url == @"http://www.comejamwithus.org/");
  Assert.AreEqual(@"Come Jam with us (Software Development Study Group)",
    comeJamWithUs.Text);
}

[TestMethod]
public void ResultsLinkContainsComeJamWithUsHtml()
{
  Link comeJamWithUs;
  Div searchResults = browserInstance.Div(div => div.IdOrName == "res");
  comeJamWithUs =
    searchResults.Link(link => link.Url == @"http://www.comejamwithus.org/");
  Assert.AreEqual(
    @"<EM>Come Jam with us</EM> (Software Development Study Group)",
    comeJamWithUs.InnerHtml);
}

Back to the Start

As previously mentioned, we can also fully interact with the browser, itself. Our test initialization started from the Google Home Page and performed a search. Using functionality built in to WatiN, we can execute the browser's back navigation to return to the previous page.

For our next test, execute a back navigation and verify that the browser's URL matches http://www.google.com/.

  1. Create a public test method named PageShouldHaveComeFromGoogleDotCom.
  2. Execute back navigation in the browser by calling the Back() method on browserInstance.
  3. Validate that the browser URL matches http://www.google.com/.
  4. Compile and run the test. The test should pass.
[TestMethod]
public void PageShouldHaveComeFromGoogleDotCom()
{
  string previousUrl;
  browserInstance.Back();
  previousUrl = browserInstance.Url;
  Assert.AreEqual(@"http://www.google.com/", previousUrl);
}

Putting it all together

Some interactions on a page cause element properties to change. An example of this is the More link from Exercise 1; when the end-user clicks the More link, the More Items DIV appears because the link's click event changes the Visibility style property of the DIV to visible. For our final test, we will use what we have learned to test this functionality.

  1. Create a new public test method named MoreItemsShouldBeVisibleOnMoreLinkClick.
  2. Search for the header bar of Google links, a DIV with an Id of "gbar".
  3. Within "gbar", search for the More Items DIV by an Id or Name of "gbi".
  4. Assert that the visibility style property has a value of "hidden".
  5. Within "gbar", search for the More link by its class name, "gb3". Note that since a class attribute may contain multiple class definitions, this is accomplished by validating that the class attribute contains the class you are searching for.
  6. Execute a Click event on the link.
  7. Assert that the visibility style property of the More Items DIV has changed to "visible".
[TestMethod]
public void MoreItemsShouldBeVisibleOnMoreLinkClick()
{
  var googleBar = browserInstance.Div(gbar => gbar.Id == "gbar");
  var googleBarMoreItems = googleBar.Div(gbi => gbi.Id == "gbi");
  Assert.AreEqual("hidden",
    googleBarMoreItems.Style.GetAttributeValue("visibility"));
  var googleBarMoreLink =
    googleBar.Link(link => link.ClassName.Contains("gb3"));
  googleBarMoreLink.Click();
  Assert.AreEqual("visible",
    googleBarMoreItems.Style.GetAttributeValue("visibility"));
}

That's It

Now that we have spent some time on basic properties, interactions, and style sheets within the WatiN framework, hopefully you can apply this to your own application and get started with your own browser-based integration tests. If you would like more information, I encourage you to check out the WatiN site at http://watin.sourceforge.net. And as always, if you have any questions, drop me a line.

Wednesday, 07 April 2010 11:27:53 (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Learn to Code | MVC

On Tuesday, February 9th, I was scheduled lead a jam session for Come Jam With Us, the software developer study group in Ann Arbor. The session was to be on ASP.NET MVC 2, aimed to give attendees enough of an introduction to the product to empower developers to be able to start coding their own ASP.NET MVC 2 projects. Unfortunately, Mother Nature did not cooperate that day, half of the state of Michigan seemingly shut down under 8" of snow, and the session was cancelled and rescheduled for February 23rd. The goal of these Learn to Code exercises is to give you an introduction to building applications with ASP.NET MVC 2. In the near future, I also hope to provide a screen cast of these same exercises.

About this Exercise

This coding exercise is designed to give you an introduction to ASP.NET MVC 2. In this exercise, developers will create their first database-driven ASP.NET MVC 2 application within Visual Studio, primarily using code generation built in to Visual Studio. Developers performing this exercise should be familiar with ASP.NET development and Visual Studio, but no previous experience with ASP.NET MVC is required.

Prerequisites

You will need few things for ASP.NET MVC 2 application development and to complete these exercises. Please complete the following prerequisites prior to moving on. The session is designed to be completed in about an hour, but prerequisite setup is not included in that time.

Exercise 0: Getting Started

Creating a Project

Before any coding can occur, the first thing that we have to do is create a new ASP.NET MVC 2 project from within Visual Studio.

  1. In Visual Studio, create a new "ASP.NET MVC 2 Web Application" named MvcJamSession. You can create your project in either Visual Basic or Visual C#, though all of the examples in this post will be in C#.
  2. After selecting the project type and solution/project name, you will be prompted for creating a unit test project. Select "Yes." Though we will not be using these tests in this exercise, we will be in future installments.
  3. Be sure that your MvcJamSession.Test project includes a project reference back to your MvcJamSession project.
  4. Compile and run. Your browser should display a blue web site showing "Welcome to ASP.NET MVC!" Congratulations. You now have your first ASP.NET MVC application.

Convention-Based Development

Project Folder Structure of MVC Jam Session Project Development within ASP.NET MVC is based on convention over configuration. Certain naming conventions are built in the system to eliminate the amount of boiler-plate code that you need to recreate. That is not to say that you must follow these naming conventions—you may use whatever convention you like—but by straying from the standardized conventions, you will be creating a lot of extra work for yourself. With our new ASP.NET MVC 2 Project, a few of these conventions are immediately visible.

  • Controllers folder. This is where all Controller classes must go. Individual classes must be named <Name>Controller. The default project includes HomeController, which governs the Home and About actions, and AccountController, which governs the log in, log out, change password, and registration actions. If we were to make an application that manages Widgets, we would likely have a class named WidgetController.
  • Views folder. This is where all of the Views must go. By default, views are paired one-to-one with controller actions, such as one view for new user registration and another view for changing your password. Views are also separated into folders matching the associated controller name—/Views/<ControllerName>/<ActionName>. Thus, HomeController's About action is associated with the /Views/Home/About view.
    The Views folder also contains a Shared folder. This folder is where any common views, such as a Master Page, would reside. The Shared folder is also where the ViewEngine cascades to when it can't find an appropriate view in the /Views/<ControllerName> folder; if /Views/Home/About didn't exist, the ViewEngine would look for /Views/Shared/About. This can come in handy for common pages shared by all controllers, such as an error page.

Session Exercise 1: Building an Application

Using the project we just created, we're going to create an application that manage a list of employees, including their name, job title, date of hire, and date of termination. Though the default project is a great help on some applications, it can get in the way on others; we're not going to need any account services in our application, so we need to first trim the project down a little.

  1. Delete the entire Account folder under /Views/.
  2. Delete AccountController.cs from the Controllers folder.
  3. Delete shared partial view /Views/Shared/LogOnUserControl.ascx.
  4. Delete reference to this partial view by removing the "LoginDisplay" DIV from /Views/Shared/Site.Master, lines 18-20.
  5. Removing LoginDisplay will cause a slight layout problem from the CSS. To fix it, modify the #menucontainer definition in /Content/Site.css on line 263.
    #menucontainer
    {
        padding-top:40px;
    }
  6. Save all, compile, and Run. The site should be functioning normally, but without the Log In link in the top right of the home page.

Creating a Database

Like any dynamic web site, we need a storage mechanism. Create a database in SQL Server or SQL Server Express with an Employee table containing columns for name, job title, hired date, and termination date, as well as an identity column for finding records.MvcJamSession-EmployeeTable

  • For those with SQL Server Express, create a new database through right-clicking the App_Data folder, and adding a new item. The new item should be a SQL Server Database.
  • For those with SQL Server, create a new database through SQL Server Management Studio (SSMS).
  1. Create a new table called Employee.
  2. Create the following columns within the new table:
    • Id (primary key, identity, int, not null)
    • Name (varchar(50), not null)
    • JobTitle (varchar(50), not null)
    • HiredOn (date, not null)
    • TerminatedOn (date, null)
  3. Add a record or two to the table for good measure.

Creating a Model

The next thing we need to create is our Model. Not only is it the code representation for our business entity (An Employee class contains Name, JobTitle, HiredOn, and TerminatedOn properties), it is also responsible for how to get, save, or delete data from the database. We will be using Microsoft Entity Framework through Visual Studio to generate our model for us.

  1. To create our new Model, right-click the Model folder and select Add New Item. The new item should be an ADO.NET Entity Data Model, found within the Data category of the Add New Item dialog. Name it MvcJamSessionEntities.
  2. Generate the Model from a database, connecting to your MVC Jam Session database created in the previous section. On the step where you select your database connection, be sure to allow Visual Studio to add the connection string to your web.config by checking the appropriate checkbox.
  3. The Employee table is the only Data Object that needs to be generated.
  4. When the dialog completes, your Entity Data Model (a .edmx file) should be displayed in design view.
  5. Save all and compile.

Creating a Controller

Now that our model is in place, we need to create a controller. The controller is responsible for managing all interaction between the end-user and the application, including identifying what data to get, save, or delete. (Remember, though the Controller is responsible for what, the Model is responsible for how.)

  1. To create our new Controller, right-click the Controller folder and select Add Controller. Since the name matters in ASP.NET MVC's convention-over-configuration style, name it EmployeeController.cs (or .vb, if you happen to be working in Visual Basic .NET). Be sure to check the "Add action methods for Create, Update, Detail, and Delete scenarios" as we will be using them later.
  2. We now have a basic controller, but it doesn't do anything yet. First, we want to modify our Index action, as it is the default action in the controller. We will use this action to list all of the Employees that currently exist in our database. Your Index() action method should contain the following code:
    var _entities = new MvcJamSession.Models.MvcJamSessionEntities();
    return View(_entities.Employee.ToList());
  3. Save all and compile.

Creating a View

We have our Model and we have our Controller, so it is time for our View. The View is responsible for display only—it should contain virtually no logic. Our controller doesn't do anything yet, but we can at least get the base file structure and navigation in place. Since our Model governs how and our Controller governs what, think of the View as governing where, as it is responsible for deciding where each data element gets displayed on your page.

  1. Once you have saved and compiled your Controller, right-click on the Index action name and select Add View.
  2. The View should be named Index, just like your Controller action. Also, make your View strongly typed to the Employee model. Since a list of Employees is being passed to the View from the Controller, making the View strongly-typed prevents us from having to cast our View Model from object to Employee. Finally, since we are providing a list of Employees, the View Content should be a List.
  3. The Employee folder should be automatically created under the /Views/ folder, and the Index.aspx View inside of this new Employee folder.
  4. The last thing we need to do is provide some navigation to this view. Open up /Views/Shared/Site.Master and add an ActionLink within the Menu Container section to the Index action of the Employee controller. When you are done, the Menu Container should look like this:
    <ul id="menu">              
      <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
      <li><%= Html.ActionLink("About", "About", "Home")%></li>
      <li><%= Html.ActionLink("Employees", "Index", "Employee")%></li>
    </ul>
  5. Save all and run. When you navigate to your Employees link, you should get a list of all employees currently in the database with an Edit, Details, and Delete links.
New in ASP.NET MVC 2: Strongly Typed HTML Helpers

In the previous version of ASP.NET MVC, HTML helpers were simple generic classes. Generated views were full of Magic Strings for each property in your model, such as <%= Html.TextBox("Name") %>, opening the door for a fat-fingered property name. MVC 2 includes strongly-typed HTML helpers on strongly-typed views. For form-based views, use the new strongly-typed "For" methods, such as <%= Html.TextBoxFor(model => model.Name) %> or <%= Html.EditorFor(model => model.Name) %> to eliminate the risk of incorrectly entering a property name. For display fields, use Html.DisplayFor() to provide similar benefits for your read-only data, including the elimination of HTML encoding for each field.

Adding New Data

A list of employees is great, but we also need the ability to manipulate that data. First, let's start with the ability to create new data.

  1. Within Visual Studio, open /Controllers/EmployeeController and navigate to the POST Create action. POST is an HTTP verb associated with pushing data to the server in the HTTP header, commonly associated with form submits. GET is the HTTP verb for pure retrieval, commonly associated with a direct URL request, such as clicking a link. In this case, the POST action can be identified by the [HttpPost] decoration.
  2. The method arguments currently include only a FormCollection object that will contain all of the header values associated with the POST. However, MVC is smart; it can automatically transform this collection into a type-safe Model, based on the names of the header variables (the identities of the HTML form inputs match the names of the Model's properties). The one exception is the Id attribute, which is available in the Model but not populated until after the object is saved to the database. To get strong typing, and avoid having to manually cast or map form collection data to a new instance of our Model, change the method signature to the following:
    public ActionResult Create([Bind(Exclude="Id")] Employee newEmployee)
  3. Now that we have a populated Model, we just need to save the Model to the database and redirect back to the List when we are done. Do this by replacing the contents of the action method with the following code:
    try
    {
      if (!ModelState.IsValid) return View();
    
      var _entities = new MvcJamSession.Models.MvcJamSessionEntities();
      _entities.AddToEmployee(employee);
      _entities.SaveChanges();
      return RedirectToAction("Index");
    }
    catch
    {
      return View();
    }
  4. Save and compile.
  5. Now we must create the View for adding data. As we did with Index, we can create the view by right-clicking the Action method and selecting Add View. The view content should be Create.
  6. The only modification for the Create view is the Id property. The generated code creates an input for this property, but it is not needed since the column value is auto-populated by the database when saving the entity. Remove this input and label from the form.
  7. Save and run. You should now be able to add new records to the database.
New in ASP.NET MVC2: Better Verb Attributes

In the first version of ASP.NET MVC, HTTP Verb conditions were placed on an Action via the AcceptVerbsAttribute, such as the Create action's [AcceptVerbs(HttpVerbs.Post)]. In ASP.NET MVC 2, these attributes have been simplified with the introduction of the HttpGetAttribute, HttpDeleteAttribute, HttpPostAttribute, and HttpPutAttribute.

Routing and Updates

The end user can view a list of Employees, and can create new employees, but when the end user clicks the Edit or Detail links, they get an error since these Views haven't been created yet and the Actions are not implemented. One by one, we will get the new views in place.

  1. Within Visual Studio, open /Controllers/EmployeeController and navigate to the Details action. You may notice that the method already accepts an integer as input, and shows example usage of the action in a commented URL above the method: /Employee/Details/5. This integer is the identity value of the Employee record, and is already populated in the links of our List view created in the previous section.
  2. Within Visual Studio, open Global.asax and navigate to the RegisterRoutes method. The default route for ASP.NET MVC is /{controller}/{action}/{id}/. By parsing out any URL into the application, MVC can determine which Controller to use, which Action to execute, and which arguments to pass to the Action. Later portions of the URL path are often optional, and when not specified, are replaced with the default values: Home, Index, and String.Empty. The URLs of "/", "/Home", "/Home/", "/Home/Index", and "/Home/Index/" are all equivalent URLs in the eyes of ASP.NET MVC.

Go back to the Employee controller. Now that we know what the integer argument is for, we need to retrieve the Employee matching the associated identity and pass it to a view for editing or display.

  1. Replace the contents of the GET version of the Edit action method with the following code to retrieve the Employee from the database that matches the identity specified in the route:
    var _entities = new MvcJamSession.Models.MvcJamSessionEntities();
    return View(_entities.Employee.Where(emp => emp.Id == id).First());
  2. Save and compile.
  3. Right-click the Action and add the View. The View should still be strongly typed, but this time the view content should be Edit.
  4. The Details and GET Delete actions are largely similar as the GET Edit action, except that the view is labels instead of text boxes. Repeat the above three steps for the Details action method with a Details view content and for the GET Delete action method with a Delete view content.
  5. As with the Create view, the Id property should be removed from the Edit view, as it is not an item that should be edited by the end user.
  6. Save and run. You should see the details of an Employee when clicking on the Edit and Details links.
  7. We can view Employee details within the Edit form, but when we make changes and submit, nothing happens. We need to modify the POST Edit action to save our changes back to the database. The default POST Edit action accepts an id and a FormCollection as input arguments, but similarly to the POST Create action, we can change this to use our strongly typed model to avoid having to cast or map data. However, unlike our Create action, we need to bind the id property so that the system knows which record to update. To make these modifications, replace the POST Edit signature with the following:
    public ActionResult Edit(MvcJamSession.Models.Employee employee)
  8. Replace the contents of the POST Edit action method with the following code to save the changes to the database:
    try
    {
      if (!ModelState.IsValid) return View();
    
      var _entities = new MvcJamSession.Models.MvcJamSessionEntities();
      var _originalEmployee =
        _entities.Employee.Where(emp => emp.Id == employee.Id).First();
      _entities.ApplyPropertyChanges(_originalEmployee.EntityKey.EntitySetName,
                                     employee);
      _entities.SaveChanges();
      return RedirectToAction("Index");
    }
    catch
    {
      return View();
    }
  9. Replace the signature of the POST Delete action method with the following code to provide strong typing on our model:
    public ActionResult Delete(MvcJamSession.Models.Employee employee)
  10. Finally, replace the contents of the POST Delete action method with the following code to delete a record:
    var _entites = new MvcJamSession.Models.MvcJamSessionEntities();
    var originalEmployee =
      _entites.Employee.Where(emp => emp.Id == deletedEmployee.Id).First();
    _entites.DeleteObject(originalEmployee);
    _entites.SaveChanges();
    return RedirectToAction("Index");
  11. Save, compile, and run. You should now be able to modify existing Employee records.

We now have a fully-functional ASP.NET MVC application to manage our Employee records. Congratulations!

Tuesday, 23 February 2010 17:38:00 (Eastern Standard Time, UTC-05:00)  #    Comments [3] - Trackback