Presentation Layer – Best Practices – Presentation Entities

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. 

Presentation Layer – Best Practices – 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 Layer – Best Practices – 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. Bow, I 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.

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. 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.

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.

Presentation Layer – Best Practices – 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.

Presentation Layer – Best Practices – Understand the UI Requirements

Presentation Layer Design Principles : 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.

Extension Methods in C#

What are extension methods?

Extension methods in C# are used to extend the functionality of a class which is not provided by the class itself, without altering the definition of the original type. An extension method is a static method of a static class, where the this modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.

Rules to Use Extension Methods

We need to import the namespace in which the static class is defined which contains the extension methods. Suppose I have defined my method in a class which is again defined under namespace. In that case, we need to include the namespace using the keyword using wherever we want to use the method.
C# only supports extension methods, it does not support extension properties, extension events, extension operators.
Extension methods must be declared in non-generic and static classes.
C# compiler looks only for the extension methods defined in static classes that are themselves defined at the file scope. In other words, if we define a static class in some class and then define our extension methods, in that case, we will get a compile time error as shown below.

C# New Features

1- Auto-properties, and their improvements

Auto-properties have been available in C# for a long time by now, the thing is that Microsoft now introduce a new feature. “Initializers” can be used to initialize these properties to their defaults. A few of the ways that they can be used is like this:

private string Name { get; set; } = “C# Learners”;

// Without a setter, a readonly
private string Name { get; } = “C# Learners”;

// Simply read-only
private readonly string Name = “C# Learners”;

2- Null-conditional operator

Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced “Nullable of Int32,” can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

Nullable types have the following characteristics:

Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

The syntax T? is shorthand for Nullable<T>, where T is a value type. The two forms are interchangeable.
Assign a value to a nullable type just as you would for an ordinary value type, for example int? x = 10; or double? d = 4.108. A nullable type can also be assigned the value null: int? x = null.

Use the Nullable<T>.GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.GetValueOrDefault();

Use the HasValue and Value read-only properties to test for null and retrieve the value, as shown in the following example: if(x.HasValue) j = x.Value;

The HasValue property returns true if the variable contains a value, or false if it is null.

The Value property returns a value if one is assigned. Otherwise, a System.InvalidOperationException is thrown.

The default value for HasValue is false. The Value property has no default value.

You can also use the == and != operators with a nullable type, as shown in the following example: if (x != null) y = x;

Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;

Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;


Factory Pattern in C#

What is Factory pattern?

Factory pattern is the most widely used pattern in the software engineering world. This pattern introduces loose coupling between classes which is the most important principle one should consider and apply while designing the application architecture. Loose coupling can be introduced in application architecture by programming against abstract entities rather than concrete implementations. This not only makes our architecture more flexible but also less fragile.

In fact, factory pattern is very common in C# programming. If you check .NET framework or any other frameworks Factory Pattern is widely used which shows its popularity. Factory Pattern belongs to Creational Patterns, and it deals with object creation. When we write codes, there are situations like creating objects based on some if conditions or switch case. If this object creation is not based on a proven design pattern then we are really making the object creation complex and future enhancements very tough. At this time we should consider Factory Pattern to abstract the complexity of the object creation logic, and enabling future additions hassle free. Factory Pattern is nothing but hiding object creation logic from the client so that the end client doesn’t have to worry about object creational logic, rather the client can refer the factory pattern created object using a common interface.


The Dependency Inversion Principle (DIP or D in SOILD principles) in C#

What is the Dependency Inversion Principle?

Robert Martin defines it as “Depend on abstractions, not on concretions or, A. High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details B. Abstraction should not depend upon details. Details should depend upon abstractions.”
If you use both OCP and LSP strictly, you will notice how a new pattern or structure emerges from it that can be generalized into what is known as the Dependency Inversion Principle.
This is one of the most useful principles, as it allow us to design software that is flexible (easy to change or extend), robust (reacts well to changes i.e. doesn’t break everywhere) and reusable (the parts of the system are very decoupled and we can extract them and use them in other projects), and whose main aim is to address bad design. The cause of bad designed software – software that is rigid, fragile and inmobile (opposite to flexible, robust and reusable in this case) – is the heavy hard-coded dependencies between its modules. These dependencies can in turn force the need of a cascade of changes when we want to introduce a tiny little change in the system (rigidity), or can result in a chain of unexpected errors (fragility), and of course, make impossible to reuse code in other applications because everything is so entwined that we might as well bring together the whole system.

The DIP addresses this problem saying no to hard-coded and top-down dependencies. The high- level modules should not depend upon the low-level modules, everything has to depend upon abstractions (thereby we get and “inverted” dependency). This way, the high level modules don’t know exactly what they depend upon, they just know they are using something that must adhere to a given interface, and thus, everything that follows that interface contract can be plugged in (or plugged out). If you extend the principle to the whole system you end up with a set of highly decoupled modules, that are completely isolated from changes in other modules and that can be easily reused. You end up with a well defined set of interfaces or abstractions that define the policy of your system, and a set of concrete implementations that are connected via these abstractions.

Interface Segregation Principle (ISP or I in SOLID principles) in C#

What is Interface Segregation Principle (ISP)?

The interface segregation principle is one of the SOLID principles that states that the clients should not be compelled to implement an interface that contains declarations of members or operations that they would not need or never use. Such interfaces are known as “fat” or polluted interfaces (also called interface bloat) as they contain too many operations.
Rather than having a fat interface and have the clients consume them, it is a recommended practice to break the fat interface to one or more specific and cohesive interfaces. If your code violates the interface segregation principle, you can fix it by taking advantage of the Adapter design pattern.
Imagine a situation in which the type that implements the interface needs to use only a few methods of the interface but not all. So, implementing such an interface where not all of the methods are relevant to the type implementing the interface is not a good practice.
So, then what’s the solution or alternative? Well, you can break this fat interface into one or more interfaces if you have access to the interface source code. If it is that you have no access to the interface, all you can do is use the relevant methods and just ignore the other ones. You can just throw and instance of the NotImplementedException class from those methods of the interface you don’t need at all. Note that when you are implementing an interface in a class, you must implement all of its members – otherwise the compiler would flag an error.
Generally speaking, if an interface has methods that can be broken into groups, each serving a different set of clients, we say the interface is “fat” and violates ISP. According to SRP, it means the same interface is assuming multiple responsibilities. To solve this problem, the “fat” interface should be replaced with multiple client-specific interfaces.

Copyright © All Rights Reserved - C# Learners