I haven't talked about CODE Framework (CODE Magazine's free development framework) in quite some time, although, as you know because you probably follow this open-source project, lots has changed and lots has been added. For this reason, it's time to take stock and take a look at some of the most important new features and enhancements. There's no way to take a look at all the new features and details that have been added. Even so, there are many big features that I'd like to highlight in this article. (Editor's note: Since this article was published, CodePlex where CODE Framework was hosted, is gone; readers can now download the CODE Framework here: https://codeframework.io/)

A New WPF Theme: Universe

The WPF components of CODE Framework have always been known for their rich UI experience and out-of-the-box themes that allow you to create applications that simply look good without having to spend a lot of time designing the UI graphically. (Although for those interested in such things, there's a great degree of freedom to do that. See my previous article about theme creation: http://www.codemag.com/Article/1211091). There are themes that look like Microsoft Office. There's a theme that looks like a traditional Windows application, one that uses a black style, and another that looks and behaves much like Windows 8 “Metro” that allows people to create Metro-style apps without being “trapped” on Windows 8, because it runs on any computer that can run WPF. Of course, most of the industry has either moved on from Windows 8 (or never left Windows 7). Even Microsoft has moved on and replaced Metro apps with the new Universal Windows App system in Windows 10.

The Universe Theme looks and feels like a Universal Windows App, even though it's a standard Windows Desktop Application that runs on all versions of Windows, not just Windows 10.

As you can imagine, we've also upgraded CODE Framework to support a new theme called “Universe,” which looks like a Windows Universal App, but, just like our Metro theme, it doesn't require a certain version of Windows and runs everywhere WPF apps run. It doesn't require any of the infrastructure associated with UWP (the Universal Windows Platform, which is the basis of Universal Windows Apps). Instead, this new theme is simply a WPF theme that looks like Universal Windows Apps, but remains a conventional Windows Desktop Application at heart. This also means that it's easy to use this theme to retrofit older applications and give them a facelift.

Figure 1 shows an example of an application using the Universe theme. As you can see, the result looks almost indistinguishable from the Universal Windows Apps you'd see on Windows 10, even though this is actually a WPF Desktop Application that runs on all flavors of Windows supporting WPF.

Figure 1: The magazine example application using the Universe theme
Figure 1: The magazine example application using the Universe theme

Figure 2 shows another example of a screen from the example application with the Universe theme applied. This example shows a view using one of the standard layout themes that make it possible to create complex screens quickly and in a very maintainable fashion. The Universe theme is a complete theme that supports all the concepts provided by the most complex CODE Framework themes, including all of the layout styles, all the standard templates, a whole new set of icons, and so on.

Figure 2: This is another example of a Universe-themed UI. This example uses a standard layout theme to arrange the UI elements on the screen.
Figure 2: This is another example of a Universe-themed UI. This example uses a standard layout theme to arrange the UI elements on the screen.

What isn't immediately obvious is that the Universe theme supports many things that Windows Universal Apps don't support. This is in part due to the application still being a WPF application, and in part due to advanced features supported by this theme. For instance, the theme supports standard top-level windows that can independently float around the desktop and across multiple monitors. The theme also supports opening multiple views (windows) at once, rather than always having a single view open. This is a feature that's extremely useful in business applications that often require knowledge workers to juggle multiple things at the same time and have multiple windows open.

What isn't immediately obvious is that the Universe theme supports many things that Windows Universal Apps don't support.

Another example is the use of the “Hamburger Menu.” Universe supports an expandable/collapsible Hamburger Menu, but the supported feature set goes far beyond a simple Hamburger Menu. Instead, the menu can be hierarchical and feature sub-menus and so on. Of course, the menu can be automatically populated from defined actions just like other menus, ribbons, or other navigation elements in CODE Framework. On a side note, the Hamburger Menu can also be used as a stand-alone object that can be useful in other apps, or themes that you may want to create on your own.

General Overhaul of Existing Themes

The new Universe Theme has been very popular (some say Universe is the new standard theme in CODE Framework). However, all of the existing themes have received significant upgrades as well. For instance, one of the builds from a while back had a specific focus on touch-support. The original Metro theme received an overhaul to support touch a lot better and in a more automatic fashion, so developers can assume that touch “just works” in a smooth and professional manner. We then also made the decision that touch should be a first-class citizen in all themes and extended our enhancements to include all themes. For this reason, touch now works a lot better in all themes, meaning that controls, such as lists, simply work as intended in touch scenarios, without you having to do anything specific. You are, of course, free to tweak things to their heart's content and there even are special objects, such as the new TouchEx object, which you can use to manually implement specific touch features. Another example is the UIs that automatically adjust when the user uses touch rather than the mouse. The most prominent example is scrollbars that adjust in width in some themes, to allow grabbing them with the mouse, while they are just a narrow visual indicator in touch scenarios. Needless to say, all of these features also fit in very well with the new Universe theme.

Another area where we focused a lot of our effort was to create additional standard layout styles (also often referred to as templates). Having such styles is one of the truly unique features in CODE Framework. These layout styles allow you to create an entire view, or a part of a view, and apply a layout style to arrange controls as suitable for specific UIs, such as edit forms, or search-and-list UIs, and so forth. This is a very productive way to create UIs, and more importantly, it's extremely maintainable and flexible. This is one of the ways to truly unleash the power of WPF and XAML. For this reason, it simply made sense to add new standard styles for people to use.

Among the new layout styles is the MultiPanel, which splits a user interface into multiple areas, either in a horizontal or vertical fashion. (Imagine Microsoft Outlook, which can be seen as a multi-panel containing a tree, the list of emails, the email preview, and a task pane). A similar example is the BladePanel. Microsoft Azure users know what that looks like, because it's the layout approach used by the portal. It arranges a user interface into vertical panels. When there isn't enough space to fit all panels, a horizontal scroll bar can be used to scroll left and right. Figure 3 shows an example of such an interface.

Figure 3: This UI uses a BladePanel arrangement to show different panels in a left-to-right arrangement - with a scroll bar, in case not all panels fit.
Figure 3: This UI uses a BladePanel arrangement to show different panels in a left-to-right arrangement - with a scroll bar, in case not all panels fit.

Other examples of layout styles include an improved EditForm layout as well as a new FlowForm layout, which behaves similar to layout in HTML with a lot of extra logic to more easily create business app UIs. There's now a Panorama panel, which allows for the creation of Panorama UIs, as they are often used in Phone apps and in UWP apps in general. (The Panorama panel is usable in all themes). There are several versions of primary/secondary panels, which are useful for scenarios where the main area of a view is used up by a large element, with some kind of secondary element on one of the edges. A typical example for such a UI is a search-and-list UI. The search UI in Figure 1 has been implemented using such a style. For a complete list (which seems to be ever-growing), take a look at the CODE Framework online docs.

Of course, all of these layout styles are supported in all themes. The exact look of the layout is theme-specific and thus changes as appropriate. Therefore, each layout style automatically translates into something that makes sense for the chosen theme. An edit form in an Office-style application (using the Workplace theme) will look slightly different from the same edit form in a touch-centric app. Also, developers often choose to tweak the details of the styles to fit their needs, which results in changes across the entire application (or at least the scope that the developer chooses to apply the style to) without having to change the implementation of the UIs.

This is just a small sampling of the new and enhanced WPF UI features. I encourage you to take a look at the specific change log.

Input Validation, Security, and Binding

There's one more area in the WPF components that warrants more detailed discussion: A recent build of the WPF framework introduced new input validation and security components. CODE Framework has always supported security by leveraging standard .NET security features. For instance, it's always been possible to secure menu items by assigning security roles. The framework then simply allowed access to those elements based on the user context (principal). In our overhaul of our security system, we built on top of that and added new security features.

For UI elements, there's now a new Security object providing attached properties that can simply be assigned to UI elements. For instance, to secure a TextBox, you can use the following XAML:

<TextBox Text="Secret!"
    sec:Security.FullAccessRoles="Super Admin, Super Hero"
    sec:Security.ReadOnlyRoles="Normal Admin" />

This TextBox will only be fully accessible to users who are either in the “Super Admin” or “Super Hero” roles (or both). Users who are assigned the role “Normal Admin” (and not the other two) have read-only access. Everyone else has no access to the control at all. It's also possible to only specify full-access roles, in which case, everyone else is assumed to have read-only access.

The “sec” namespace in this example maps to the following namespace:

xmlns:sec="clr-namespace:CODE.Framework.Wpf.Security;
assembly=CODE.Framework.Wpf"

Note: The role assignments are done using standard .NET security and principals. CODE Framework uses the principal's IsInRole() method to determine whether or not the currently logged in user is a member of the required role. Developers can create their own principals or use existing principals to implement this functionality. CODE Framework's default templates create a fundamental principal implementation for this purpose.

This is very nice functionality that makes it simple to implement UI security. Developers can either directly specify roles as in this example, or the properties can be data bound to implement more complex scenarios:

<TextBox Text="Secret!"
    sec:Security.FullAccessRoles="{Binding SecretFA}"
    sec:Security.ReadOnlyRoles="{Binding SecretRO}" />

Another very desirable way of defining such security is to add security attributes to view-model properties. This is now also supported in the following fashion through the new CODE Framework Security attribute:

[Security(
    FullAccessRoles = "Super Admins, Super Heroes",
    ReadOnlyRoles = "Normal Admins")]
public string Description
{
    get { return _description; }
    set
    {
        _description = value;
        NotifyChanged(nameof(Description));
    }
}

This is great, because you can now define this type of logic on the view-model and then include it in testing and quality control. It also makes the construct more interesting to maintain and reuse. For instance, the view-model containing this property could be used in multiple views, without having to account for the security in each XAML file.

However, there's one issue: How does a bound UI element (such as the textbox) know to use the security attribute? There are two answers to this question. The first lies in a new CODE Framework markup extension that allows binding to all kinds of attributes. You can use this functionality for your security definition (although this feature is also useful for all kinds of other scenarios). Here's the appropriate syntax:

<TextBox Text="Secret!"
    sec:Security.FullAccessRoles="{ex:AttributePropertyBinding
            Description[Security.FullAccessRoles]}"
    sec:Security.ReadOnlyRoles="{ex:AttributePropertyBinding
            Description[Security.ReadOnlyRoles]}" />

The AttributePropertyBinding extension works similar to other WPF bindings, except rather than binding to a single member, this special binding can bind to attributes associated with that member. There are several variations of this binding (the online docs list them all). This particular version finds the Description property, then digs into the Security attribute, and grabs the value of the FullAccessRoles and ReadOnlyRoles settings respectively.

Note: The ex namespace in this example is defined like this:

xmlns:ex="clr-namespace:
CODE.Framework.Wpf.MarkupExtensions;
assembly=CODE.Framework.Wpf"

This is a nice approach that's useful in a lot of scenarios. It also provides a great degree of control. However, as indicated above, there's a second way to do this. CODE Framework provides a new data binding XAML extension. The use of this new data binding mechanism is optional. It builds on standard WPF bindings, so it supports everything that standard binding supports. However, it also adds new features. The syntax is simple:

<TextBox Text="{ex:Bind Description}" />

As you can see, this is very similar to WPF's standard {Binding…} syntax, except that the CODE Framework version is simply called Bind. It does everything that the Binding syntax does, but it can also do a few additional things. One of those extra features - you guessed it - is to automatically respect the Security attribute. So this simple example automatically handles attribute-driven security, whenever the security definition is present. Nifty, isn't it?

But wait, there's more! In addition to overhauling security, we also overhauled the WPF data validation system. The fundamental goal for validation was to create attribute-based validation in a way that's familiar (and largely compatible) with the validation found in ASP.NET MVC. Therefore, it is now possible to do this on view-model members:

[Required(ErrorMessage = "Can't be blank.")]
[MinLength(10, ErrorMessage = "10 char minimum!")]
[MaxLength(50, ErrorMessage = "50 char maximum!")]
public string Description { get; set; }

These attributes are not CODE Framework attributes. Instead, they're standard .NET data validation attributes and are also used in ASP.NET MVC. It's also possible to extend the attributes and add your own attributes and rules, just like in ASP.NET MVC. This is nice because it enables code-sharing with MVC apps (or at least re-use of skills MVC developers already have).

Again, the question that arises is “how does the XAML-layer know about these attributes?” You may have already guessed the answer: We can attribute-bind these attributes to special attached properties, but I'll spare you those details (if you're interested, check out the CODE Framework docs), because if you use the new Bind syntax, the binding automatically respects all these properties.

New security features, enhanced data validation, and an enhanced way of data-binding may not be the flashiest of features, but they drastically simplify day-to-day life.

The second question that arises from this is “how does the XAML know how to visually represent validation errors?” For one, all of the styles in the default themes are aware of validation and show validation errors in a way that's appropriate for each theme. Of course, all of these templates and styles can be modified to suit your specific needs. (A detailed explanation of the creation of these styles is beyond the scope of this article, but feel free to contact us at info@codemag.com.)

New security features, enhanced data validation, and an enhanced way of data binding may not be the flashiest of features, but they drastically simplify your day-to-day life and make the creation of business apps much less error-prone and easier to maintain at the same time.

WebApi Service Hosting

CODE Framework isn't just a WPF UI Framework. It also provides a significant set of server-side features, especially for the creation of Services and microservices. Long-time CODE Framework users know that the framework makes it easy to develop services and then host those services in a variety of ways, typically in WCF hosts and supporting protocols such as SOAP, TCP/IP, or REST. Those features are still present and have been enhanced in many details. In particular, the service test-bench environment has been greatly enhanced, making it very efficient to create services and test them without the need of real client-applications. (If you're interested in these features, see this article: http://www.codemag.com/Article/1203061).

You can now host one-and-the-same service in WebApi as well as WCF and even new technologies such as .NET Core!

A feature we haven't discussed in this magazine even though it's been around for a while, is hosting the same services in WebApi. This allows for the creation of services that can be hosted in a range of environments, including WebApi, without having to change anything in the service that would make it incompatible with other standards and hosting environments.

So let's say that you have a service called CustomerService. Using the new WebApi hosting features, you can simply add a new controller to WebApi system:

public class CustomerController : ServiceHostController<CustomerService>
{
}

That's it! No further code is needed in this controller. This controller, which is based on the CODE Framework ServiceHostController class, exposes everything in the CustomerService service class to the outside world using REST and JSON. Note that this has nothing to do with WCF! Developers sometimes think that just because they can also host the same service in WCF means that there is some kind of WCF dependency. This is not the case! This is simply using WebApi all the way.

Admittedly, it might be desirable to tweak things a bit more. After all, there is no way for this controller to understand HTTP verbs that you'd like to use, or how to map URL parameters and such. CODE Framework provides special attributes for this purpose. This example shows how the CustomerService contract can be decorated with specific REST features:

[ServiceContract]
public interface ICustomerService
{
    [OperationContract]
    [Rest(Method = RestMethods.Post, Name = "List")]
    GetCustomerListResponse
        GetCustomerList(GetCustomerListRequest request);

    [OperationContract]
    [Rest(Method = RestMethods.Get, Name = "")]
    GetCustomerResponse       
        GetCustomer(GetCustomerRequest request);

    [OperationContract]
    [Rest(Method = RestMethods.Put, Name = "")]
    SaveCustomerResponse       
        SaveCustomer(SaveCustomerRequest request);

    [OperationContract]
    [Rest(Method = RestMethods.Put)]
    AssignShipmentResponse
        AssignShipment(AssignShipmentRequest request);
}

This example is designed to be hosted both in WCF and WebApi (if you are only interested in WebApi, you can omit the ServiceContract and OperationContract attributes). The interesting parts are the Rest attributes, which CODE Framework provides for this purpose. (Note: If this service were WCF hosted, those attributes would be largely ignored, unless you used CODE Framework's features to host REST within WCF, but that's a scenario I'll ignore for the sake of brevity in this article).

The Rest attribute can be used to define how the outside world perceives the service methods when seen through “REST glasses.” For instance, the GetCustomerList() method will be exposed as a List endpoint accessible using HTTP-Post. Depending on the configuration of your WebApi application, the service may thus be accessible on the following URL:

http://www.mydomain.com/api/Customer/List

Other methods use similar configurations, but use different names (including no names) and different verbs. For instance, accessing a customer through the GetCustomer() method is mapped to the following URL (no method name, but an additional parameter to identify the customer):

http://www.mydomain.com/api/Customer/12345

Similarly, saving a customer through the SaveCustomer() method is mapped to the same URL, except it's using the Put HTTP verb.

You may have noticed that the GetCustomer() and SaveCustomer() methods have an additional parameter to identify the customer in question. The method takes a complex parameter, which is itself an object with (potentially multiple) properties. How does the system know how to route the parameters? The answer lies in the definition of the input message. Here is the parameter object used by the GetCustomer() method:

[DataContract]
public class GetCustomerRequest
{
    [DataMember(IsRequired = true)]
    [RestUrlParameter(Mode = UrlParameterMode.Inline, Sequence = 1)]
    public Guid CustomerId { get; set; }
}

This class has a property called CustomerId. This property is decorated with a RestUrlParameter property that specifies that this property is mapped from an “inline” URL parameter. It also specifies that it's the first in the sequence of parameters. This isn't required in this example, as there's only one property, but in more complex examples, multiple URL parameters may be mapped to the input object using this approach. (For more details on more complex scenarios, see the online documentation.)

Note: The exact URL changes with your WCF Routing setup. To make this example work, I'm using the following standard set up to route to all REST controllers:

config.Routes.MapHttpRoute("DefaultApi",
    "api/{controller}/{id}/{id2}/{id3}/{id4}/{id5}",
    new
    {
        id = RouteParameter.Optional,
        id2 = RouteParameter.Optional,
        id3 = RouteParameter.Optional,
        id4 = RouteParameter.Optional,
        id5 = RouteParameter.Optional
    }
);

Of course, you can completely change the routing and URL naming using standard WebApi routing mechanisms and configuration.

Does this mean that you should create all of your WebApi services that way? No. If you have WebApi services that will always only be WebApi services, then why not continue only using WebApi? If you want to create services that can be hosted in WebApi as well as WCF (supporting protocols such as SOAP or binary TCP/IP), then this is a great approach. This is also a great approach to support future technologies. For instance, it's entirely conceivable to host the same service in .NET Core on Linux. (Note that the implementation details may foil that plan, as not all the things your service may want to do are currently supported in .NET Core. For instance, it wouldn't make sense to expect to open a SqlConnection if you are running your .NET Core app on a Mac. So your individual mileage may vary depending on what you do in your services and how mature .NET Core has become by the time you are reading this).

Calling REST Services

Hosting REST in various ways isn't the only REST feature that CODE Framework concerns itself with. Another area of particular interest is calling REST Services from the client, when the client is .NET. There are two main scenarios that CODE Framework supports:

  • Calling any REST service no matter who created it
  • Calling CODE Framework hosted REST services with a known “service contract” (known structure)

The first scenario is supported through the ServiceClient.CallREST() method. This method allows calling an arbitrary REST URL. As an optional feature, you can create client-side contracts, so the result is a strongly typed object. (For the obvious reason, this should only be done for REST services that return an unchangeable structure; otherwise the result should be seen as a dynamic object). Here's an example:

var request = new MyRequest();
var response = ServiceClient.CallREST<MyRequest,
    MyResponse>("http://url.com/...", request);

This feature is not earth shattering, but it certainly is nice and easy to use from .NET. More interesting is the ability to call REST services using standard CODE Framework service calling. For instance, you may already have a call to a service that uses WCF and binary TCP/IP hosted on a Windows Server somewhere. Using CODE Framework, you can call this service in the following fashion:

ServiceClient.Call<ICustomerService>(s => {
    var request = new GetCustomerRequest{Id=x};
    var response = s.GetCustomer(request);
});

This is one of the many variations of calling a service using CODE Framework. The system uses configuration to know where this service lives and what protocol is used to invoke it. From a developer's point-of-view, none of that matters in the potentially hundreds of places from which this service is called. It's simply a standardized approach that isn't fundamentally harder than using a local object.

No client-side coding changes are needed in C# when switching from WCF to WebApi hosted services.

Now let's say that you have just discovered the new CODE Framework feature that allows you to host the same exact service in WebApi rather than WCF, which may make your life easier on the server side. But what about the hundreds of service calls on the client that connect to the old service? Well, using CODE Framework, it's a piece of cake, because the ServiceClient.Call() code will continue to work as always. All you have to do is change the ServiceProtocol setting in your configuration to REST and you're all set! The framework figures out everything else, and no code changes are needed whatsoever. How's that for a long-term maintainable coding strategy?

By the way, all REST services (WebApi and WCF) in CODE Framework now use a new JSON serialization strategy based on JSON.NET. This results in more powerful and standards-compliant JSON serialization. You may not notice any difference if you work mostly in .NET, but JavaScript-based clients will certainly notice and appreciate the difference.

Community and GitHub

I could go on and on about specific technical details and new features that we've added to the framework. Instead, I'd like to draw your attention to another newish development. For well over a year, CODE Framework has been mirrored to GitHub (https://github.com/markuseggerinc/codeframework). Others can find information on the CODE website here: https://codeframework.io/. I encourage you to take a look, and perhaps even contribute.