Write End-to-End Tests for Your Angular 2 Applications With Protractor

Add E2E testing and make sure your users don’t fail!

Testing your applications is a critical step in ensuring software quality. While many agree, it can be hard to justice the budget for it. This issue can occur when development and testing are imagined as two separable activities. In fact, there are common practices in place designed around their coupling (see TDD). End-to-End (E2E) testing is another common practice designed in this way.

E2E testing can be thought of as an additional direction or angle in which to test an Angular 2 application’s logic. It tests, from a user’s perspective, if the application does what is expected. If these tests fail, your users will fail and the failure will be right in their face. This user-centric approach is critical to ensuring an intended user experience. Writing these tests will produce a detailed user experience specification enforced by simply making sure the tests pass.

End to End testing does not replace QA resources. All software is written by people and people are not perfect – no matter what they say.

Interacting with Your Application

To begin creating the tests we need a way to interact with the application. This is made easier with Protractor. With Protractor, Selenium can be leveraged within JavaScript including integration with Angular applications. A few critical components are exposed to you through Protractor.

browser – browser-scoped operations such as navigating to a particular URL.
element – provides a way to retrieve the UI components of your application from within your tests.
by – What UI component do you want and how should it be found?
promise – support asynchronous operations.
ElementFinder – perform operations on retrieved UI components.
ElementArrayFinder – perform operations on an array of retrieved UI components.

Importing from Protractor

Importing what you need from Protractor is as easy as importing anything else:

import {
   browser, element, by, promise, ElementFinder } from 'protractor';

Navigating to a URL

Get to the correct page using browser.get():

navigateTo() {
  return browser.get('/list');
}

Retrieving and Manipulating UI Components:

Use the Protractor API to retrieve elements and perform operations in your application:

clickEditButton(): promise.Promise {
  return element(by.css('.edit-button')).click();
}

Creating Page Objects

Now that a few fundamentals are out of the way, let’s take a look at organizing our tests. First, we need to create Page Objects. These objects encapsulate interactions with UI components. Implementing Page Objects could be thought of as user experience mapping including structure and operations.

With single-page applications, a “Page Object” could get quite unwieldy! This is why we need to consider the structure of the application. Considering the Angular Components within the application is a great way to begin dividing your Page Objects. Take a simple Todo application shown in Figure 1:

todoscreenshot
Figure 1: Sample todo application

Even with this simple application, there is a lot to include in just a single Page Object. This screen can be divided up into four distinct areas: header, menu, list, and details. Let’s look at how these can be created using separate Page Objects:

Header

todoheader
// header.po.ts
import { promise, ElementFinder } from 'protractor';

export class Header {
  getContainer(): ElementFinder {
    return element(by.css('.header'));
  }
  getHeader(): ElementFinder {
    return this.getContainer().element(by.css('.header-text'));
  }
  getHeaderText(): promise.Promise {
    return this.getHeader().getText();
  }
}

Menu

todomenu
// menu.po.ts
import { element, by, promise,
  ElementFinder, ElementArrayFinder } from 'protractor';

export class Menu {
  getContainer(): ElementFinder {
    return element(by.css('.menu'));
  }
  getMenuItems(): ElementArrayFinder {
    return element.all(by.css('.menu-item'));
  }
  getActiveMenuItem(): ElementFinder {
    return this.getContainer()
       .element(by.css('.menu-item.active-menu-item'));
  }
  getActiveMenuItemText(): promise.Promise {
    return this.getActiveMenuItem().getText();
  }
  getCompletedMenuItem(): ElementFinder {
    return this.getContainer()
       .element(by.css('.menu-item.completed-menu-item'));
  }
  getCompletedMenuItemText(): promise.Promise {
    return this.getCompletedMenuItem().getText();
  }
  getAddMenuItem(): ElementFinder {
    return this.getContainer()
       .element(by.css('.menu-item.add-menu-item'));
  }
  getAddMenuItemText(): promise.Promise {
    return this.getAddMenuItem().getText();
  }
  clickActiveMenuItem(): promise.Promise {
    return this.getActiveMenuItem().click();
  }
  clickCompletedMenuItem(): promise.Promise {
    return this.getCompletedMenuItem().click();
  }
  clickAddMenuItem(): promise.Promise {
    return this.getAddMenuItem().click();
  }
}

List

todolist
// list.po.ts
import { element, by, promise,
  ElementFinder, ElementArrayFinder } from 'protractor';

export class List {
  getContainer(): ElementFinder {
    return element(by.css('.list'));
  }
  getItems(): ElementArrayFinder {
    return element.all(by.css('app-todo'));
  }
  getItem(index: Number): ElementFinder {
    return this.getItems().get(index);
  }
  getEditButton(index: Number): ElementFinder {
    return this.getItem(index).element(by.css('.edit'));
  }
  getDeleteButton(index: Number): ElementFinder {
    return this.getItem(index).element(by.css('.delete'));
  }
  clickEditButton(index: Number): promise.Promise {
    return this.getEditButton(index).click();
  }
  clickDeleteButton(index: Number): promise.Promise {
    return this.getDeleteButton(index).click();
  }
}

Details

tododetails
// details.po.ts
import { element, by, promise, ElementFinder } from 'protractor';

export class Details {
  getContainer(): ElementFinder {
    return element(by.css('.details'));
  }
  getDetailHeader(): ElementFinder {
    return this.getContainer().element(by.css('.detail-header'));
  }
  getDetailHeaderText(): promise.Promise {
    return this.getDetailHeader().getText();
  }
  getDescription(): ElementFinder {
    return this.getContainer().element(by.css('.detail-description'));
  }
  getDescriptionText(): promise.Promise {
    return this.getDescription().getText();
  }
}

Alright, that was a lot of code. Let’s take a step back for a moment. We are creating Page Objects representing the distinct areas of the UI that we have determined. Each Page Object has offered the ability to retrieve (e.g. getContainer) and operate (e.g. clickDeleteButton) on UI elements from their respective areas. The last item we need now is a root Page Object to complete our Page Object hierarchy.

The Page Object Hierarchy

todopageobjecthierarchy

Yes, I can’t seem to help it – there is one additional Page Object that has been included along with the root Page Object. The Item Page Object will encapsulate the structure and logic of each todo item within the List.

An instance of each leaf Page Object (which includes header, menu, list, and details) is stored on the root Page Object (TodoApp). This provides the ability to write complex operations while exposing a simple API to your tests:

// snippet todo-app.po.ts
export class TodoApp {
  constructor() {
    this.list = new List();
  }

  private list: List;

  removeAllItems(): promise.Promise<void[]> {
   let promises: Array<promise.Promise> = new Array<promise.Promise>();

   this.list.getItems().each(item => {
    promises.push(item.clickDeleteButton());
   });

   return promise.all(promises);
  }
}

In removeAllItems() each todo item is found and its Delete button is clicked. We should no longer have any todo items. This is a testable scenario. Testing this would mean answering the question – what happens when there are no items? We can use our Page Objects to create tests around this scenario!

Testing with Page Objects

Creating tests using Page Objects can clean up your tests and allows more explicit definition of your test scenarios. This way also helps keep the user interface definition out of the tests making it easier to maintain – keep in sync with your application!

Jasmine Syntax

If you have written tests using Jasmine before, you know how to create tests for Protractor. It is a great tool for writing unit tests! It is just as good for writing tests with Protractor. Simply follow their tutorials to learn more about Jasmine.

Writing Tests

Now let’s see some tests. We will test the ability to remove all items by clicking their Delete button:

// todo-app.e2e-spec.ts
import { TodoApp } from './todo-app.po.ts'

describe('Todo Item', () => {
 let page: TodoApp;
 
 beforeEach(() => {
   page = new TodoApp();
 });
 
 it('delete button should remove todo item', (done) => {
   page.navigateTo();
   const text: String = 'test text';
   
   page.addItem(text, text).then(() => {
     page.removeAllItems().then(() => {
       expect(page.getItems().count()).toBe(0);
       done();
     });
   });
 });
});

This test sample is following a few common practices. First, the root Page Object is imported:

import { TodoApp } from './todo-app.po.ts';

Next, the top-level test suite is defined. Within this test suite a variable is defined to hold our root Page Object. Then comes the initialization of each test in the suite:

beforeEach(() => {
  page = new TodoApp();
});

This is a fairly rudimentary example but, the initialization code will run once before each test in the suite. Make sure to place any necessary test initialization code within this block such as initializing Page Objects and setting up the UI.

Next comes the fun. The test is defined using typical Jasmine syntax with support for asynchronous test code:

it('delete button should remove todo item', (done) => {
  page.navigateTo();
  const text: String = 'test text';
 
  page.addItem(text, text).then(() => {
    page.removeAllItems().then(() => {
      expect(page.getItems().count()).toBe(0);
      done();
    });
  });
});

The first step in our test is to navigate to the TodoApp and create a variable to hold our new item text and description.

Considering that the test is for ensuring items get deleted when their Delete button is clicked, we need to be sure there is an item to remove! Using a Page Object method for adding an item, a new todo item is added to the screen using the new item text and description defined earlier. Since the method returns a promise, we use then() to continue execution.

We have added an item. Now its time to remove it. We know that the Page Object contains a method that clicks a todo item’s Delete button. We also know that the Page Object provides the ability to remove all of the todo items in the list using this method. This means we can simply call removeAllItems() and check the list to make sure it is empty.

If the test passes we can say the Delete button works for each todo item.

Mean TODO

There is a sample application demonstrating Angular 2 in the MEAN Stack that includes a set of E2E tests. Simply follow the guide on GitHub to get started!

Thank you for reading this far! If you have any comments, questions or concerns please send a message.

 

Angular 2 in the MEAN Stack – A Project Template

Should I leverage my love for JavaScript to develop an application from the ground up? Yes Please!

I recently became aware of the beauty of developing with the MEAN stack. It started with my desire to brush up on Angular 2 and using the Angular CLI. I ended up with a TODO application that runs on Node using MongoDB, Express.js, and Angular 2 (from a foundation found here: https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli).

I am also a fan of LESS. It makes writing modular CSS a breeze. I am also not yet sold on the Styled Component approach Angular is now pushing. I do believe Component-based UI architectures make writing modular CSS quite simple. I just don’t think styles should be located across the application when, with an optimally modular UI, the CSS used can be quite minimal. Beyond that, an application should have a look and feel that gives the user at least the illusion of cohesiveness. Easily done when styles are in one place.

Using Feature Modules with Angular 2 makes a lot of sense. Each feature can be created in isolation while still being integrated with the rest of the application. The module structure of the TODO application is shown in Figure 1. This structure allows the application to be extended and makes features easy to find for updates and bug fixes. The approach also provides a more SOLID application.

todofeaturemodule
Figure 1: Module structure

With the focus on Angular 2, the server-side code is quite minimal and I don’t have much to say about it. Figure 2 depicts the main ideas.

todoapi
Figure 2: Server-side

I almost forgot to mention that this app is on GitHub: https://github.com/calebmagenic/ng2-mean. Let me know your thoughts!

I look forward to continuing my work with the MEAN stack and sharing what I find that works – and what doesn’t work so well. Look for more in the future.

UPDATE: After working with later versions of Angular, I found it to be an effective front-end framework that can solve enterprise-level concerns. I enjoy working with TypeScript and creating stunning multi-faceted projects with the help of Nx Workspaces. To make it easier to get up to speed with the MEAN stack, Manning Publications released a new book called Getting Mean with Mongo, Express, Angular, and Node (2nd Ed.) written by two smashing authors and developers in the field Simon Holmes and Clive Harper. After leveraging this book, I am able to create substantial solutions using the MEAN stack. I highly recommend it even if you are just trying it out. It has a ton of immediately actionable information packed into it.

Custom Data-Bound Control for ASP.Net

This post was a result from a question on Code Project asking what the GetData method is. This post will be a basic tutorial on how to create custom data-bound controls for ASP.Net. General knowledge of ASP.Net development with C# will be assumed.

What is GetData()?

The question implies the necessity of a custom data-bound control. When creating a custom data-bound control, the data-binding abilities must be implemented. DataBoundControl, GetData(), DataSourceView, and GetDataSource() are a few methods and classes involved in these custom controls.

DataBoundControl is the base class used to implement custom data-bound controls. It contains methods such as GetData() and GetDataSource() to help with the data-binding implementation of the custom control.

A data-bound control by definition will need to bind to data. There is one important question to answer regarding data: What is the data? Is it a file? Is it a table in a database? If it is a file, what format is it in: CSV, XML, text, pdf? Is it a collection of related data or a single piece? Knowing what the raw data is; its structure; its format; is essential to be able to use it as the underlying data for the data source of the custom control.

A data-bound control will need a data source. The data source is generally set by the user of the control. The data source can be such things as files and database entities as previously implied. When working with binding in the custom control the data is accessed by calling GetData(). The GetData method calls GetDataSource() internally. Calling these methods retrieves an IDataSource instance that is cached by the DataBoundControl object. This instance will remain until the OnDataPropertyChanged method signals that the data source has changed.

Specifically, GetData() returns a DataSourceView. The DataSourceView is a base class and is used by the control for data operations. Creating a custom data-bound control may involve creating a custom DataSourceView. A DataSourceView provides create, read, update, and delete (CRUD) operations for working with the underlying raw data. The corresponding methods are: Insert, Select, Update, and Delete.

In a way, the DataSourceView provides the structure of the data for the data-bound control. Therefore, there are three representations of the raw-data: the raw-data structure itself (XML, database table), the DataSourceView (the structure to provide to the control), and the data-bound control (the way the control presents the data to the user).

That’s the theory. Here’s an example.

The following will be a walkthrough in creating a custom list control. The CustomList control will be created that renders CustomListRecord children controls which will also be demonstrated. First, the CustomListRecord will be shown, then the CustonList control. The process will include setting up necessary Bindable properties, data-binding methods, and rendering.

CustomListRecord : WebControl

The CustomListRecord will contain the text to display to the user. It will be wrapped in a <div> tag with a “customlistrecord-data” class attribute. The only Bindable property is Text which will be the text displayed to the user. Here is the implementation:

[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomListRecord runat=server></{0}:CustomListRecord>")]
public class CustomListRecord : WebControl
{
  [Bindable(true)]
  [Category("Appearance")]
  [DefaultValue("")]
  [Localizable(true)]
  public string Text
  {
   get
   {
     string s = (ViewState["Text"] as string);
     return ((s == null) ? String.Empty : s);
   }
   set
   {
     ViewState["Text"] = value;
   }
  }
  protected override void RenderContents(HtmlTextWriter output)
  {
    output.WriteBeginTag("div");
    output.WriteAttribute("class", "customlistrecord-data");
    output.Write(">");
    output.WriteEncodedText(this.Text);
    output.WriteEndTag("div");
  }
}

Here we have a class derived from WebControl that has the DefaultPropertyAttribute and ToolboxData attribute. This class has a single property called Text. It is the property used to display text to the user. It has the BindableAttribute, CategoryAttribute, DefaultValueAttribute, and LocalizableAttribute. Click the links for each of the attributes to learn more about them. The property’s backing store is the control’s ViewState. When this control is rendered, it will use the given HtmlTextWriter to emit a <div> tag using the various Write methods. The html will generally look like:

<div class='customlistrecord-data'>Text to display to the user.</div>

It is very important to emit the “>” character after calls to WriteBeginTag. Otherwise, the opening tag will not be closed properly. The end tags do not need this character.

CustomList : DataBoundControl

Now that the record for the list is created, the creation of the CustomList can begin. Below is the implementation:

[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomList runat=server></{0}:CustomList>")]
public class CustomList : DataBoundControl
{
 public</span> CustomList() : base()
 {
   this._records = new Collection<CustomListRecord>();
 }
 protected override void PerformSelect()
 {
   if (!this.IsBoundUsingDataSourceID)
   {
   this.OnDataBinding(EventArgs.Empty);
   }
   var view = this.GetData();
   view.Select(CreateDataSourceSelectArguments(),
      new DataSourceViewSelectCallback((IEnumerable retrievedData) =>
      {
        if (this.IsBoundUsingDataSourceID)
        {
          this.OnDataBinding(EventArgs.Empty);
        }
        this.PerformDataBinding(retrievedData);
      })
   );
 }
 protected override void PerformDataBinding(IEnumerable data)
 {
   base.PerformDataBinding(data);
   if (data != null)
   {
    foreach (object dataItem in data)
    {
      var record = new CustomListRecord();
      if (this.DataMember.Length > 0)
      {
        record.Text = DataBinder
          .GetPropertyValue(dataItem, this.DataMember, null);
      }
      else
      {
        var props = TypeDescriptor.GetProperties(dataItem);
        if (props.Count > 0)
        {
          for (var i = 0; i < props.Count; i++)
          {
            var value = props[0].GetValue(dataItem);
            if (value != null)
            {
              record.Text += value.ToString();
            }
          }
        }
        else
        {
          record.Text = String.Empty;
        }
      }
      this._records.Add(record);
    }
  }
  this.RequiresDataBinding = false;
  this.MarkAsDataBound();
  this.OnDataBound(EventArgs.Empty);
 }
 private IList _records;
 public IList Records
 {
  get
  {
   if (null == this._records)
   {
     this._records = new Collection<CustomListRecord>();
   }
   return this._records;
  }
 }
 [Bindable(true)]
 [Category("Appearance")]
 [DefaultValue("")]
 [Localizable(true)]
 public string Title
 {
  get
  {
    string s = ViewState["Title"] as string;
    return ((s == null) ? String.Empty : s);
  }
  set
  {
    ViewState["Title"] = value;
    if (this.Initialized)
    {
      this.OnDataPropertyChanged();
    }
  }
 }
 protected override void Render(HtmlTextWriter output)
 {
  if (output == null)
  {
    return;
  }
  if (this._records.Count <= 0)
  {
    return;
  }
  if (this.Page != null)
  {
    this.Page.VerifyRenderingInServerForm(this);
  }
  /*
  * <div class="customlist-container">
  *  </div class="customlist-header">
  *     Heading Text
  *    </div>
  *    <div class="customlist-data">
  *       <div class="customlist-record">
  *          <customlistrecord />
  *       </div>
  *     <div class="customlist-record">
  *        <customlistrecord />
  *       </div>
  *    </div>
  * </div>
  */
  output.WriteBeginTag("div");
  output.WriteAttribute("class", "customlist-container");
  output.Write(">");
  output.WriteBeginTag("div");
  output.WriteAttribute("class", "customlist-header");
  output.Write(">");
  output.WriteEncodedText(this.Title);
  output.WriteEndTag("div");
  output.WriteBeginTag("div");
  output.WriteAttribute("class", "customlist-data");
  output.Write(">");
  foreach (CustomListRecord item in this._records)
  {
    output.WriteBeginTag("div");
    output.WriteAttribute("class", "customlist-record");
    output.Write(">");
    item.RenderControl(output);
    output.WriteEndTag("div");
  }
  output.WriteEndTag("div");
  output.WriteEndTag("div");
 }
}

CustomList’s Implementation Explained

Here we have a class derived from DataBoundControl that has the DefaultPropertyAttribute and ToolboxData attribute. Each section will be explained.

The Constructor

The constructor simply initializes the _records field with a Collection of CustomListRecords:

public CustomList() : base()
{
 this._records = new Collection<CustomListRecord>();
}

The Properties

This class has two properties: Records and Title.

 private IList _records;
 public IList Records
 {
  get
  {
   if (null == this._records)
   {
     this._records = new Collection<CustomListRecord>();
   }
   return this._records;
  }
 }
 [Bindable(true)]
 [Category("Appearance")]
 [DefaultValue("")]
 [Localizable(true)]
 public string Title
 {
  get
  {
    string s = ViewState["Title"] as string;
    return ((s == null) ? String.Empty : s);
  }
  set
  {
    ViewState["Title"] = value;
    if (this.Initialized)
    {
      this.OnDataPropertyChanged();
    }
  }
 } 

The Title property is used to display the title of the list to the user. It has the BindableAttribute, CategoryAttribute, DefaultValueAttribute, and LocalizableAttribute. The property’s backing store is the control’s ViewState. When this is rendered a <div> tag will be emitted:

<div class='customlist-header'>Title of the CustomList control</div>

The Records property contains the children CustomListRecord controls. The backing store is the private IList _records field. CustomListRecord controls will be added to this list upon data-binding.

The Data

The PerformSelect method is where the control obtains its data:

 protected override void PerformSelect()
 {
   if (!this.IsBoundUsingDataSourceID)
   {
   this.OnDataBinding(EventArgs.Empty);
   }
   var view = this.GetData();
   view.Select(CreateDataSourceSelectArguments(),
      new DataSourceViewSelectCallback((IEnumerable retrievedData) =>
      {
        if (this.IsBoundUsingDataSourceID)
        {
          this.OnDataBinding(EventArgs.Empty);
        }
        this.PerformDataBinding(retrievedData);
      })
   );
 } 

The internals of the PerformSelect method depends on the DataSourceView that is obtained by the call to GetData(). The Select method of the DataSourceView instance is called with DataSourceSelectArguments and a new instance of the DataSourceViewSelectCallback. The Select method, as described by Microsoft’s documentation, asynchronously retrieves a list of data from the underlying data store.

The Binding

Within the DataSourceViewSelectCallback handler is where the binding part of data-binding resides. The binding code is executed in the PerformDataBinding method:

 protected override void PerformDataBinding(IEnumerable data)
 {
   base.PerformDataBinding(data);
   if (data != null)
   {
    foreach (object dataItem in data)
    {
      var record = new CustomListRecord();
      if (this.DataMember.Length > 0)
      {
        record.Text = DataBinder
          .GetPropertyValue(dataItem, this.DataMember, null);
      }
      else
      {
        var props = TypeDescriptor.GetProperties(dataItem);
        if (props.Count > 0)
        {
          for (var i = 0; i < props.Count; i++)
          {
            var value = props[0].GetValue(dataItem);
            if (value != null)
            {
              record.Text += value.ToString();
            }
          }
        }
        else
        {
          record.Text = String.Empty;
        }
      }
      this._records.Add(record);
    }
  }
  this.RequiresDataBinding = false;
  this.MarkAsDataBound();
  this.OnDataBound(EventArgs.Empty);
 } 

The list below outlines the major aspects of this method:

  • Cycles through the list of data retrieved from the Select method described previously.
  • Upon each item:
    • A new CustomListRecord instance is created
    • An adequate property is found on the data item
    • The property is then assigned to the Text property of the CustomListRecord instance
    • The new CustomListRecord instance is added to the collection of CustomListRecords
  • Notifies listeners that the control has been data-bound.

The Rendering

After data-binding, the control has it’s internals ready for rendering:

protected override void Render(HtmlTextWriter output)
{
  if (output == null)
  {
    return;
  }
  if (this._records.Count <= 0)
  {
    return;
  }
  if (this.Page != null)
  {
    this.Page.VerifyRenderingInServerForm(this);
  }
  /*
  * <div class="customlist-container">
  *  </div class="customlist-header">
  *     Heading Text
  *    </div>
  *    <div class="customlist-data">
  *       <div class="customlist-record">
  *          <customlistrecord />
  *       </div>
  *     <div class="customlist-record">
  *        <customlistrecord />
  *       </div>
  *    </div>
  * </div>
  */
  output.WriteBeginTag("div");
  output.WriteAttribute("class", "customlist-container");
  output.Write(">");
  output.WriteBeginTag("div");
  output.WriteAttribute("class", "customlist-header");
  output.Write(">");
  output.WriteEncodedText(this.Title);
  output.WriteEndTag("div");
  output.WriteBeginTag("div");
  output.WriteAttribute("class", "customlist-data");
  output.Write(">");
  foreach (CustomListRecord item in this._records)
  {
    output.WriteBeginTag("div");
    output.WriteAttribute("class", "customlist-record");
    output.Write(">");
    item.RenderControl(output);
    output.WriteEndTag("div");
  }
  output.WriteEndTag("div");
  output.WriteEndTag("div");
}

The DataBoundControl’s Render method is overridden in order to render the data for the user. The first two if-statements help deal with potential invalidity of the control. In this example, nothing is displayed. In a real scenario, it would be wise to add an ability to specify what is done. The comment block in this method merely depicts the html that the code below it will emit. Finally the html is emitted with the control’s Title and Records property. To render each CustomListRecord appropriately, the RenderControl method of the WebControl created earlier is called.

Using the CustomList Control

Now that the CustomList and CustomListRecord control is created, it can be used in an ASP.Net page. The steps provided in the subsequent sections are:

  1. Registering access to the CustomList control at the top of the page.
  2. Adding the CustomList control to the page.
  3. Creating a data source for the CustomList control.
  4. Setting up the data-binding to the data source previously created.
  5. Viewing the results.

Registering Access to the CustomList Control

To use the custom data-bound control, there must be a reference to the Assembly containing it as described in (@ Register):

<%@ Register assembly="DataBoundControls"
 namespace="DataBoundControls.Custom" tagprefix="asp" %>

Note: along with the assembly reference on the page, the project the page resides in must also reference the assembly containing the custom data-bound control. If the page and control reside in the same project, the project assembly reference is not necessary.

Adding the CustomList Control

Once the assembly is referenced, the CustomList control can be added to the page:

<body>
  <form id="Form1" runat="server">
  <cc1:customList
        ID="customList"
        Title="This is the title."
        runat="server"/>
  </form>
</body>

Here the CustomList control is added to the body of the page within a element. The title is set to “CustomList Heading” and runat=”server” is specified.

The page should now generally look like this:

<%@ Page Language="C#" AutoEventWireup="true"
 CodeBehind="Default.aspx.cs" Inherits="AspPageLifeCycle._Default" %>
<%@ Register assembly="ASPNetServerControls"
 namespace="ASPNetServerControls.DataBound" tagprefix="cc1" %>
<html>
 <head><title>Custom Data-Bound Controls</title></head>
 <body>
  <form id="Form1" runat="server">
  <cc1:CustomList
        ID="customList"
        Title="This is the title."
        runat="server" />
  </form>
 </body>
</html>

Creating a Data Source

The CustomList control needs data to bind to. Here, the CustomList’s data source will be created. The data source will consist of a simple <a title=”List” href=”http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx” target=”_blank” rel=”noopener noreferrer”>List of CustomListDataRecord objects. Here is the implementation of CustomListDataRecord:

public class CustomListDataRecord
{
 public CustomListDataRecord(string text)
 {
   this.Text = text;
 }
 public string Text { get; set; }
}

This object will be used to provide the item data for each CustomListRecord in the CustomList control. The data source will be of type List. Here is the code:

var data = new List<CustomListDataRecord>();
data.Add(new CustomListDataRecord("Hello,"));
data.Add(new CustomListDataRecord("world!"));
data.Add(new CustomListDataRecord("This"));
data.Add(new CustomListDataRecord("is goodbye…"));

The above code creates a new List instance and adds four items. This list will be used as the data source for the CustomList control on the page. Placement of this code will be described below.

Data-Binding Setup

Next comes the data-binding setup. The steps here include assigning the List instance to customList’s DataSource property, using CustomListDataRecord’s Text property for the DataMember, and calling DataBind(). Here is the code that does this:

customList.DataSource = data;
customList.DataMember = "Text";
customList.DataBind();

The above code sets up the data-binding for the CustomList instance and then calls DataBind. The DataBind method will in turn call the methods we created in the CustomList control. The following section will describe the placement of this code.

Viewing the Results

At this point, the CustomList is created, added to the page, and is set up for data-binding. The code in the previous two sections will be placed in the PreRender page event handler:

protected void Page_PreRender(object sender, EventArgs e)
{
 var data = new List<CustomListDataRecord>();
 data.Add(new CustomListDataRecord("Hello,"));
 data.Add(new CustomListDataRecord("world!"));
 data.Add(new CustomListDataRecord("This"));
 data.Add(new CustomListDataRecord("is goodbye…"));
 customList.DataSource = data;
 customList.DataMember = "Text";
 customList.DataBind();
}

Further information on the PreRender event and the ASP.Net Life Cycle can be found here (ASP.Net Page Life Cycle Overview). With this code in place, the project should be ready to run! Run the project to view the created page in the browser. The page shouldn’t look too much different than below:

The view inside the browser

The page doesn’t look like much but, the html provides great potential with CSS.

Conclusion

Custom data-bound controls depend on data, data structures, and rendering. This article described the creation of each of these. There can certainly be improvements to the control ranging from default CSS to more robust data-binding and the inclusion of item templating. The code provided lays a foundation to improve upon.

The Importance of SharePointWebPartCodeGenerator

Honestly, I have yet to actually enjoy SharePoint development specifically but, I still let myself learn. I want to briefly describe an issue I had when creating visual web parts in a sandbox solution. As the name of this entry implies, the SharePointWebPartCodeGenerator plays an important role in the web part creation. I will briefly describe what it is, where it is used, and why it is important. A basic knowledge of ASP.Net and developing in Visual Studio is necessary.

Huge Name, Small Functional Scope

The SharePointWebPartCodeGenerator is quite a self-descriptive name. It is a tool used to generate code for a web part. It is the “designer file” creator for the visual aspect of the SharePoint web part. Let me explain by describing what this is in average ASP.Net. In ASP.Net, pages and controls (ASPX and ASCX respectively) have a corresponding designer file. This is where the generated UI code is placed when a developer adds such things as “<asp:Textbox..” or “<asp:Literal..” etc etc. This is automated so it doesn’t usually affect the developer. The wonder that is the Visual Studio 2010 SharePoint Power Tools requires the use of the tool SharePointWebPartCodeGenerator. I’ll explain how and where to use this tool in the following sections.

Case in Point

I recently created a web part to display items from a list in a certain way and to wrap some specific functionality around those items. I went with a Visual Web Part. I find it a lot easier to develop a web user interface when it can actually be seen in HTML while I’m developing it. As usual, I found a better way to implement the web part only After I finished creating it. The change involved updating the controls used in the markup for the web part. After making the changes, I attempted to build the solution and got a nice error similar to:

‘..WebPart’ does not contain a definition for ‘userControlID’ and no extension method ‘userControlID’ accepting a first argument of type ‘..WebPart’ could be found (are you missing a using directive or an assembly reference?)

Looking at the project structure I noticed there was no designer file. Obviously, that is a problem! No designer file means that there is no code-behind support for the management of controls in my web part. I finally found that I needed to use a tool to create this designer file. I had to add ‘SharePointWebPartCodeGenerator’ to the ‘Custom Tool’ field of the markup file’s properties.

How-To

Let me describe this process. It is quite straightforward.

Make sure the markup file (e.g. .ascx) is selected in the Visual Studio project as shown below:

Select the ASCX In VS Solution Explorer

View the Properties of the markup file and make sure the ‘Custom Tool’ field contains ‘SharePointWebPartCodeGenerator’ as shown below:

Add SharePointWebPartCodeGenerator as CustomTool in ASCX's File Properties

This was all I needed to fix my issue. Making markup edits were no problem after I made that entry into the properties of the markup file. It now automatically runs the custom tool when I save my changes to the markup.