Chapter 11: Designing Presentation Components
For more details of the topics covered in this guide, see Contents of the Guide.
- Step 1 – Understand the UI Requirements
- Step 2 – Determine the UI Type Required
- Step 3 – Choose the UI Technology
- Step 4 – Design the Presentation Components
- Step 5 – Determine the Binding Requirements
- Step 6 – Determine the Error Handling Strategy
- Step 7 – Determine the Input Validation Strategy
- patterns & practices Offerings
- Additional Resources
This chapter describes the steps you should follow when designing the user interface components and presentation logic components that are part of your presentation layer. Some of the stages are related to the design of the presentation layer itself, while others focus more closely on the individual types of components you may choose to build.
You should first understand the requirements for the UI, and be able to select the appropriate technology. Then you can decide how to bind your presentation logic and data to the UI controls. You must also ensure that you understand the requirements for error handling and validation within the UI. The following sections of this chapter describe in more detail the steps for designing presentation components.
Step 1 – Understand the UI Requirements
Understanding UI requirements is the key for making decisions on the UI type, and the technology and type of controls used to implement it. Your UI requirements are driven by the functionality to be supported by the application and by user expectations.
Start by identifying the users of application, and understanding the goals and tasks these users wish to accomplish when using the application. Pay particular attention to the sequencing of tasks or operations; and determine whether the user expects a structured step-by-step user experience, or an ad-hoc unstructured experience where they can initiate multiple tasks simultaneously. As part of this process, also determine the information required by the user and the format in which it is expected. You may decide to conduct a field study to help you understand the environment in which the user will interact with the application. In addition, consider the current levels of user experience, and compare this to the user experience required for your UI to ensure that it is logical and intuitive. These factors will help you to create a user centered design.
One factor that has a large impact on your choice of technology is the functionality required in the UI. Identify if the UI must expose rich functionality or user interaction, must be highly responsive, or requires graphical or animation support. Also consider the data types, formats and presentation formatting requirements for data such as dates, times, and currency from a localization perspective. In addition, identify the personalization requirements of the application, such as allowing the user to change the layout or styles at run time.
To make the UI intuitive and easy to use, consider how you will lay out or compose the interface; and how the user will navigate through the application’s UI. This will help you to choose the appropriate controls and UI technologies. Understand the physical display requirements (such as screen size and resolution) that you must support, and determine accessibility requirements (such as large text or buttons, ink input, or other specialized features). Decide how you will group related information within sections of the UI, avoid interface conflicts or ambiguity, and emphasize the important elements. Identify ways to allow users to find information quickly and easily in the application through the use of navigational controls, search functions, clearly labeled sections, site maps, and other features as appropriate.
Step 2 – Determine the UI Type Required
Based on your UI requirements, you can make a decision on the type of UI for your application. There are a number of different UI types, each with their own strengths and weaknesses. Often, you will find that your UI requirements can be fulfilled with more than one UI type. It is also possible that no single UI type completely covers all of your UI requirements. In this case, consider creating different UI types on top of a shared set of business logic. An example is creating a call center application where you want to expose some of the capabilities for customer self help on the Web and on mobile devices.
Mobile applications can be developed as thin client or rich client applications. Rich client mobile applications can support disconnected or occasionally connected scenarios. Web or thin client mobile applications support connected scenarios only. Device resources may also prove to be a constraint when designing mobile applications.
Rich client applications are usually stand-alone or networked applications with a graphical user interface that display data using a range of controls, and are deployed to a desktop or laptop computer for use by a local user. They are suitable for disconnected and occasionally connected scenarios because the application runs on the client machine. A rich client UI is a good choice when the UI must support rich functionality and rich user interaction or provide a highly dynamic and responsive user experience; or when the application must work in both connected and disconnected scenarios, take advantage of local system resources on the client machine, or integrate with other applications on that machine.
Rich Internet applications (RIAs) are usually Web applications with a rich graphical user interface that run inside a browser. RIAs are typically used for connected scenarios. A RIA is a good choice when your UI must support a dynamic and responsive user experience or use streaming media, and be widely accessible on a range of devices and platforms. They can take advantage of the processing power of the client computer, but cannot easily interact with other local system resources such as webcams, or with other client applications such as Microsoft Office.
Web applications support connected scenarios and can support many different browsers running on a range of operating systems and platforms. A Web UI is a good choice when your UI must be standards-based, accessible on the widest range of devices and platforms, and work only in a connected scenario. Web applications are also well suited to applications whose content is to searchable by Web search engines.
Console-based applications offer an alternative text only user experience, and typically run within command shells such as a Command window or Power Shell. They are most suitable for administrative or development tasks, and are unlikely to be part of a layered application design.
Step 3 – Choose the UI Technology
After you have identified the UI type for your UI components, you must choose an appropriate technology. In general, your choices depend on the UI type you have chosen. The following sections describe some appropriate technologies for each UI type:
Mobile client user interfaces can be implemented using the following presentation technologies:
- Microsoft .NET Compact Framework. This is a subset of the Microsoft .NET Framework designed specifically for mobile devices. Use this technology for mobile applications that must run on the device without guaranteed network connectivity.
- ASP.NET for Mobile. This is a subset of ASP.NET, designed specifically for mobile devices. ASP.NET for Mobile applications can be hosted on an Internet Information Services (IIS) server. Use this technology for mobile Web applications when you must support a wide range of mobile devices and browsers, and can rely on a permanent network connection.
- Silverlight for Mobile. This subset of the Silverlight client requires the Silverlight plug-in to be installed on the mobile device. Use this technology to port existing Silverlight applications to mobile devices, or if you want to create a richer UI than is possible using other technologies. (At the time of writing, this technology is announced but has not yet been released).
Rich client user interfaces can be implemented using the following presentation technologies:
- Windows Presentation Foundation (WPF). WPF applications support more advanced graphics capabilities, such as 2-D and 3-D graphics, display resolution independence, advanced document and typography support, animation with timelines, streaming audio and video, and vector-based graphics. WPF uses Extensible Application Markup Language (XAML) to define the UI, data binding, and events. WPF also includes advanced data binding and templating capabilities. WPF applications support developer/designer interaction—allowing developers to focus on the business logic, while designers focus on the look and feel –by separating the visual aspects of the UI from the underlying control logic. Use this technology when you want to create rich media-based and interactive user interfaces.
- Windows Forms. Windows Forms has been part of the .NET Framework since its release, and is ideally suited to line-of-business style applications. Even with the availability of Windows Presentation Foundation (WPF), Windows Forms is still a good choice for UI design if your team already has technical expertise with Windows Forms, or if the application does not have any specific rich media or interaction requirements.
- Windows Forms with WPF User Controls. This approach allows you to take advantage of the more powerful UI capabilities provided by WPF controls. You can add WPF to an existing Windows Forms application, perhaps as a path for gradual adaption to a fully WPF implementation. Use this approach to add rich media and interactive capabilities to existing applications, but keep in mind that WPF controls tend to work best on higher powered client machines.
- WPF with Windows Forms User Controls. This approach allows you to supplement WPF with Windows Forms controls that provide functionality not provided by WPF. You can use the WindowsFormsHost control provided in the WindowsFormsIntegration assembly to add Windows Forms controls to the UI. Use this approach if you must use Windows Forms controls in a WPF UI, but keep in mind that there are some restrictions and issues relating to overlapping controls, interface focus, and the rendering techniques used by the different technologies.
- XAML Browser Application (XBAP) using WPF. This technology hosts a sandboxed WPF application in Microsoft Internet Explorer or Mozilla Firefox on Windows. Unlike Silverlight, you can leverage the full WPF framework, but there are some limitations related to accessing system resources from the partial trust sandbox. XBAP requires Windows Vista, or both the .NET Framework 3.5 and the XBAP browser plug-in on the client desktop. XBAP is a good choice if you have an existing WPF application that you want to deploy to the Web, or you want to leverage the rich visualization and UI capabilities of WPF that are not available in Silverlight.
Rich Internet application user interfaces can be implemented using the following presentation technologies:
- Silverlight. This is a browser-optimized subset of WPF that works cross platform and cross browser. Compared to XBAP, Silverlight is a smaller, faster install. Due to its small footprint and cross-platform support, Silverlight is a good choice for graphical applications that do not require premium WPF graphics support, or that do not require installation of the application on the client.
Web application user interfaces can be implemented using the following presentation technologies:
- ASP.NET Web Forms. This is the fundamental UI design and implementation technology for .NET Web applications. An ASP.NET Web Forms application needs only to be installed on the Web server, with no components required on the client desktop. Use this technology for Web applications that do not require the additional features provided by AJAX, Silverlight, MVC, or Dynamic Data described in this section.
- ASP.NET Web Forms with AJAX. Use AJAX with ASP.NET Web Forms to process requests between the server and client asynchronously to improve responsiveness, provide a richer user experience, and reduce the number of post backs to the server. AJAX is an integral part of ASP.NET in the .NET Framework version 3.5 and later.
- ASP.NET MVC. This technology allows you to use ASP.NET to build applications based on the Model-View-Controller (MVC) pattern. Use this technology if you need to support test-driven development, and achieve a clear separation of concerns between UI processing and UI rendering. This approach also helps you to create clean HTML and avoids mixing presentation information with logic code.
- ASP.NET Dynamic Data. This technology allows you to create data-driven ASP.NET applications that leverage a Language-Integrated Query (LINQ) to Entities data model. It is a good choice if you require a rapid development model for line-of-business (LOB) style data-driven applications based on simple scaffolding, while still supporting full customization.
Console-based user interfaces can be implemented using the following presentation technologies:
- Console Applications are text only applications that can be run from Command shells and produce output to the standard output console and error console. These applications often are built to take all input at time of invocation and run unattended.
- Power Shell Commandlets. Power Shell is a command-line shell and scripting environment to provide comprehensive control and automation of system and application administrative tasks. Commandlets are application-specific extensions to the Power Shell environment that provide a more deeply integrated experience into the Power Shell language.
For more information about the technologies listed in the previous sections, see Appendix B "Presentation Technology Matrix."
Step 4 – Design the Presentation Components
After you choose the implementation technology for your UI, the next step is to design your UI components and your presentation logic components. The types of presentation components you may decide to use are the following:
- User Interface Components
- Presentation Logic Components
- Presentation Model Components
These components support a separation of concerns in the presentation layer, and are often used to implement a separated presentation pattern such as MVP (Model-View-Presenter) or MVC (Model-View-Controller) by dividing UI processing into three distinct roles: Model, View, and Controller/Presenter. Separating the concerns in the presentation layer in this way increases maintainability, testability, and opportunities for reuse. The use of abstraction patterns such as dependency injection also makes it easier to test your presentation logic.
For general component design considerations, and more information on the components commonly found in all the layers of an application, see Chapter 10 "Component Guidelines."
User Interface Components
UI components are the visual elements that display information to the user and accept user input. Within a separated presentation pattern, they are typically referred to as Views. Consider the following guidelines when designing your UI components:
- Consider dividing your pages or windows into discrete user controls in order to minimize complexity and to allow reuse of these user controls. Choose appropriate UI components, and take advantage of the data-binding features of the controls you use in the UI.
- Try to avoid inheritance hierarchies of user controls and pages to enable code reuse. Favor composition over inheritance and consider creating reusable presentation logic components instead.
- Try to avoid creating custom controls unless it is necessary for specialized display or data collection. If you find that your UI requirements cannot be achieved with the standard controls, consider buying a control toolkit before deciding to write your own custom controls. If you must create custom controls, extend existing controls if possible instead of creating a new control. Consider extending existing controls by attaching behaviors to them, rather than inheriting from them, and consider implementing designer support for custom controls to make it easier for developers to use them
Presentation Logic Components
Presentation logic components handle the nonvisualization aspects of the user interface. This will often include validation, responding to user actions, communicating between UI components, and orchestrating user interactions. Presentation logic components are not always necessary; create them only if you will perform significant processing in the presentation layer that must be separated from the UI components, or to improve opportunities for unit testing your presentation logic. Consider the following guidelines when designing presentation logic components:
- If the UI requires complex processing or must communicate with other layers, consider using presentation logic components to decouple this processing from the UI components.
- Use presentation logic components to store state related to (but not specific to) the UI. Avoid implementing business logic and business rules, other than input and data validation, within the presentation logic components. Also, avoid implementing rendering or UI specific logic in the presentation logic components.
- Use presentation logic components to help your application recover from a failure or error by using them to make sure after recovery that the user interface is in a consistent state.
- Where the UI requires complex workflow support, consider creating separate workflow components that use a workflow system such as Windows Workflow Foundation or a custom mechanism within the application’s business layer. For more information, see Chapter 14 "Designing Workflow Components."
Presentation Model Components
Presentation model components represent data from your business layer in a consumable format for your UI and presentation logic components in the presentation layer. Models typically represent data, and so they use the data access and possibly the business layer components to collect that data. If the model also encapsulates business logic, it is usually called a presentation entity. Presentation model components may, for example, aggregate data from multiple sources, transform data for the UI to display more easily, implement validation logic, and may help to represent business logic and state within the presentation layer. They are typically used to implement separated presentation patterns, such as MVP or MVC. Consider the following guidelines when designing presentation model components:
- Determine if you require presentation model components. Typically, you might use presentation layer models if the data or the format to be displayed is specific to the presentation layer, or if you are using a separated presentation pattern such as MVP or MVC.
- If you are working with data-bound controls, design or choose appropriate presentation model components that you can easily bind to UI controls. If using custom objects, collections, or data sets as your presentation model component format, ensure that they implement the correct interfaces and events to support data binding.
- If you perform data validation in the presentation layer, consider adding the code for this to your presentation model components. However, also consider how you can take advantage of centralized validation code or code libraries.
- Consider the serialization requirements for the data you will pass to your presentation model components if this data will be passed over the network or stored on disk on the client.
You must also choose a suitable data type for your presentation model components and presentation entities. This choice is driven by the application requirements, and constrained by your infrastructure and development capabilities. You must first choose a data format for your presentation layer data and decide if your components will also encapsulate business logic and state. Next, you must decide how you will present the data within the user interface. The common data formats for presentation data are the following:
- Custom class. Use a custom class if you want to represent your data as a complex object that maps directly to your business entities. For example, you might create a custom Order object to represent order data. You can also use a custom class to encapsulate business logic and state and to perform presentation layer validation or to implement custom properties.
- Array and Collection. Use an array or a collection when you must bind data to controls such as list boxes and drop-down lists that use single column values.
- DataSet and DataTable. Use a DataSet or a DataTable when you are working with simple table-based data with data-bound controls such as grids, list boxes, and drop-down lists.
- Typed Dataset. Use a Typed DataSet when you want tight coupling with your business entities to avoid discrepancies due to database changes.
- XML. This format is useful when working with a Web client, where the data can be embedded in a Web page or retrieved via a Web service or HTTP request. XML is a good choice when you are using controls such as a tree view or grid. XML is also easy to store, serialize, and pass over communication channels.
- DataReader. Use a DataReader to retrieve data when fully connected and the data is to be accessed in a read-only, forward-only manner. The DataReader provides an efficient way to process data from your database sequentially, or to retrieve large volumes of data. However, it ties your logic very closely to the schema of your database and is not generally recommended.
Presentation model components should, where possible, encapsulate both the data from your business layer, and business logic and behavior. This helps to ensure data consistency and validity in the presentation layer, and helps to improve the user’s experience.
In some cases, your presentation model components may be the business entities from your business layer, directly consumed by the presentation layer. In other cases, your presentation model components may represent a subset of your business entity components, specifically designed to support the presentation layer of your application. For example, they may store the data in a format that is more easily consumable by your UI and presentation logic components. Such components are sometimes referred to as presentation entities.
When the business layer and presentation layer are both located on the client, a typical scenario for rich client applications, you will usually consume the business entities directly from the business layer. However, you may consider using presentation entities if you must store or manipulate the business data in a way that is distinct from the format or behavior of the business entities exposed by the business layer.
When the business layer is located on a separate tier from the presentation layer, you may be able to consume the business entities in the presentation tier by serializing them across the network using data transfer objects, and then resurrecting them as business entity instances on the presentation tier. Alternatively, you can resurrect the data as presentation entities if the required format and behavior differs from that of the business entities. Figure 1 shows this scenario.
Presentation model components and presentation entities may be useful when the presentation layer and business layer are on separate physical tiers
Step 5 – Determine the Binding Requirements
Data binding provides a way to create a link between the controls in the user interface and the data or logic components in your application. Data binding allows you to display and interact with data from databases as well as data in other structures, such as arrays and collections. Data binding is the bridge between a binding target (typically a user interface control) and a binding source (typically a data structure, model, or presentation logic component).
Objects used in data binding
As shown in Figure 2, data binding normally involves four elements that interact to update the properties of the bound control with values exposed by the binding source. Data-bound controls are controls that are bound to data sources; for example, a DataGrid control bound to a collection of objects. Data binding is often used with separated presentation patterns to bind the UI components (the Views) to the presenters or controllers (the presentation logic components) or to the presentation layer model or entity components.
Support for data binding, and its implementation, varies for each UI technology. In general, most UI technologies allow you to bind controls to objects and lists of objects. However, specific data binding technologies may require certain interfaces or events to be implemented on the data sources in order to fully support data binding, such as INotifyPropertyChanged in WPF or IBindingList in Windows Forms. If you are using a separated presentation pattern, you must ensure that your presentation logic and data components support the required interfaces or events to allow UI controls to be easily data bound to them.
There are typically two common types of binding you can use, described in the following list:
- One-way binding. Changes to the source property automatically update the target property, but changes to the target property are not propagated back to the source property. This type of binding is appropriate if the control being bound is implicitly read-only. An example of a one-way binding is a stock ticker. If there is no need to monitor changes to the target property, using one-way binding avoids unnecessary overhead.
- Two-way binding. Changes to either the source property or the target property automatically update the other. This type of binding is appropriate for editable forms or other fully interactive UI scenarios. Many editable controls in Windows Forms, ASP.NET, and WPF support two-way binding so that changes in the data source are reflected in the UI control and changes in the UI control are reflected in the data source.
Step 6 – Determine the Error Handling Strategy
UI components are the external boundary of your application, and so you should design an appropriate error handling strategy to maximize application stability and provide a positive user experience. Consider the following options when designing an error handling strategy:
- Design a centralized exception handling strategy. Exception and error handling is a crosscutting concern, and should be implemented using separate components that centralize the functionality and make it accessible across the layers of the application. This also eases maintenance and promotes reusability.
- Log exceptions. It is vital to log errors at system boundaries so that your support organization can detect and diagnose errors. This is important for presentation components, but can be challenging for code that is running on client machines. Be careful how you log Personally Identifiable Information (PII) or security sensitive information, and be aware of log size and location.
- Display user friendly messages. In this strategy, you display a user friendly message that shows the reason for the error and explains how the user can rectify it. For example, data validation errors should be displayed in a way that makes it clear which data is in error and why it is invalid. The message may also indicate how the user can fix the data or enter valid data.
- Allow retry. In this strategy, you display a user-friendly message that explains the reason for the error and asks the user to retry the operation. This strategy is useful when errors are due to a temporary exception situation such as resource unavailability or a network timeout.
- Display generic messages. If your application encounters an unexpected error, you should log details of the error but display only a generic message to the user. Consider providing the user with a unique error code that they can present when contacting your support organization. This strategy is useful when dealing with unexpected exceptions. It is generally recommended that you close the application if an unhandled exception occurs in order to prevent data corruption or security risks.
For more information about exception handling techniques, see Chapter 17 "Crosscutting Concerns." For information about Enterprise Library, which provides useful features for implementing exception handling strategies, see Appendix F "patterns & practices Enterprise Library."
Step 7 – Determine the Validation Strategy
An effective input validation strategy will help to filter unwanted and malicious data and protect your application from vulnerabilities. Typically, input validation is performed by the presentation layer, whereas business rule validation is carries out by components in the business layer. When designing a validation strategy, first identify all data inputs that must be validated. For example, inputs from a Web client in Form fields, parameters (such as GET and POST data and query strings), hidden fields, and view state should all be validated. In general, you should validate all data received from untrusted sources.
For applications that have both a client-side and a server-side component, such as RIAs or rich client applications that call services on an application server, you must perform validation on the server in addition to any validation you carry out on the client. However, you can duplicate some of the validation on the client for usability and performance reasons. Performing validation on the client is useful to give users feedback quickly if they have entered invalid data. It can save time and bandwidth, but be aware that a malicious attacker can bypass any validation you have implemented on a client.
After you have identified the data to validate, decide on your validation techniques for each item. The most common validation techniques are:
- Accept known good (Allow list, or positive validation). Accept only data that satisfies the matching criteria, and reject all other.
- Reject known bad (Block list, or negative validation). Accept data that does not contain a known set of characters or values.
- Sanitize. Eliminate or translate known bad characters or values in an effort to make the input safe.
In general, you should accept known good values (Allow list) rather than try to determine all the possible invalid or malicious values that must be rejected. If you are not able to define fully the list of known good values, then you can supplement the validation with a partial list of known bad values and/or sanitization as a second line of defense.
Different presentation technologies use different approaches to validating and reporting validation problems to the user. WPF, for example, uses converters and validation rule objects that are often connected using XAML, while Windows Forms provides validating and binding events.
For more information about validation techniques, see Chapter 17 "Crosscutting Concerns." For information about Enterprise Library, which provides useful features for validating objects and data both server-side and client-side, see Appendix F "patterns & practices Enterprise Library."
patterns & practices Offerings
For more information on related offerings available from the Microsoft patterns & practices group, see the following resources:
- Composite Client Application Guidance for WPF for both desktop and Silverlight make it easier to create modular applications. For more information, see "Composite Client Application Guidance" at https://msdn.microsoft.com/en-us/library/cc707819.aspx.
- Enterprise Library contains a series of application blocks that address crosscutting concerns. For more information, see "Enterprise Library" at https://msdn.microsoft.com/en-us/library/cc467894.aspx.
- Software Factories speed development of specific types of application such as Smart Clients, WPF applications, and Web Services. For more information, see "patterns & practices: by Application Type" at https://msdn.microsoft.com/en-gb/practices/bb969054.aspx.
- Unity Application Block for both enterprise and Silverlight scenarios provides features for implementing dependency injection, service location, and inversion of control. For more information, see "Unity Application Block" at https://msdn.microsoft.com/en-us/library/dd203101.aspx.
For more information, see the following resources:
- "Design Guidelines for Web Applications" at https://msdn.microsoft.com/en-us/library/ms978618.aspx.
- "Data Binding Overview" at https://msdn.microsoft.com/en-us/library/ms752347.aspx.
- "Design Guidelines for Exceptions" at https://msdn.microsoft.com/en-us/library/ms229014%28VS.80%29.aspx.