Computed properties in Xomega Framework

In this article you will get familiar with Xomega Framework, and will learn how to write testable and reusable multi-platform presentation logic for your applications. Specifically, you will learn how to implement computed properties using both the traditional MVVM approach and a new, simple but powerful expressions-based approach.

What is Xomega Framework

For those of you who are not familiar with the Xomega Framework, it's a powerful framework for building web and desktop applications in .NET using MVVM pattern with clean layer separation. It allows you to easily write most of your presentation logic in a platform-independent way, which not only makes it extremely testable, but also allows you to use (and reuse) it with completely different UI layers, such as WPF and Blazor, or even with the older WebForms framework.

This way you can share your presentation logic between different UI technologies for web, desktop or even mobile applications, and then easily upgrade the UI layer if a new UI framework becomes available, thus future-proofing your application.

Let's take a look at some of the major parts of the Xomega Framework.

Data Objects

Data objects represent a part of the View Model in the MVVM pattern that contains observable data, which the View can be bound to. Data objects consist of special data properties, as well as other child data objects.

A special type of data object is a list object, where the data is stored in data rows, and the data properties represent columns in a table.

Data Properties

Unlike regular object properties, Xomega Framework data properties encapsulate not only the data value or multiple values, but also dynamic property metadata, such as editability, visibility, security access, whether or not the property is required, a list of possible values, modification state, as well as formatting, validation and conversion rules for the values.

The framework has an extensible hierarchy of data properties, which represents various data types with their specific conversion and formatting rules.

Here is what a data object and some of its properties will look like for the SalesOrderDetail table from the AdventureWorks database.

public class SalesOrderDetailObject : DataObject
    public EnumIntProperty ProductIdProperty { get; private set; }
    public SmallIntegerProperty OrderQtyProperty { get; private set; }
    public EnumIntProperty SpecialOfferIdProperty { get; private set; }
    public MoneyProperty UnitPriceProperty { get; private set; }
    public PercentFractionProperty UnitPriceDiscountProperty { get; private set; }
    public MoneyProperty LineTotalProperty { get; private set; }

Property Change Events

Similar to the other classic MVVM frameworks, Xomega data properties allow you to subscribe to property change events. However, unlike notifying about only the value changes, like the INotifyPropertyChange interface, data properties can also notify you about changes in their metadata as well, such as when the property becomes editable or required, or when the list of possible values for the property has changed.

A single property change event can be fired for any change in the data property’s value or any of its metadata, and also for any combination of such changes. So a single event can notify you about changes in all property attributes at once, which would allow listeners, such as property-bound controls, to update all of its state at the same time.

It also means that when listening for just property value changes, for example, you need to check if the property change includes the value change to avoid unnecessary execution of your callback.

Binding to UI controls

One of the primary usage of the property change events is support for binding properties to UI controls. This would automatically include binding control’s state to the property metadata, which makes this binding extremely simple and easy to use.

Once a UI control is bound to the property, you can set the property to be editable, required or invisible, and the changes will be reflected in the UI control automatically,  without you having to bind those things separately.

Depending on the UI framework that you use, there could be two different ways to bind UI controls to data properties, as described below.

Control property bindings

With UI frameworks that allow you to associate additional attributes with the controls, such as attached properties in WPF, or custom attributes in WebForms controls, you can set the data property name on such controls, and have those controls bound to the data property using separate bindings.

This method allows you to bind any custom or third-party control that is derived from common UI controls to your data properties. Xomega Framework provides an extensible hierarchy of property bindings for both WPF and WebForms controls.

Here is an example of a WPF ComboBox control that is bound to the ProductId property using a static constant for the property name to provide compiler safety.

<ComboBox xmlns:xom="clr-namespace:Xomega.Framework;assembly=Xomega.Framework.Wpf"
          xom:Property.Label="{Binding ElementName=lblProductId}"
          xom:Property.Name="{x:Static o:SalesOrderDetailObject.ProductId}" />

The same control in WebForms would look as follows.

<asp:DropDownList LabelID="lblProductId" Property="<%# SalesOrderDetailObject.ProductId %>"
                  AutoPostBack="true" runat="server" />

Property bound controls

In other UI frameworks where using separate property bindings is not supported or problematic, you can develop and use custom UI controls that can be bound to Xomega data properties.

Xomega Framework provides a set of common Blazor components that you can bind directly to your data properties.

For example, a view with Blazor components that is bound directly to the properties of our SalesOrderDetailObject would look as follows.

    <XLabel Property="@VM?.MainObj?.ProductIdProperty" Text="Product:" />
    <XSelect Property="@VM?.MainObj?.ProductIdProperty" />
    <XLabel Property="@VM?.MainObj?.OrderQtyProperty" Text="Order Qty:" />
    <XInputText Property="@VM?.MainObj?.OrderQtyProperty" />
    <XLabel Property="@VM?.MainObj?.SpecialOfferIdProperty" Text="Special Offer:" />
    <XSelect Property="@VM?.MainObj?.SpecialOfferIdProperty" />
    <XLabel Property="@VM?.MainObj?.UnitPriceProperty" Text="Unit Price:" />
    <XDataLabel Property="@VM?.MainObj?.UnitPriceProperty" />
    <XLabel Property="@VM?.MainObj?.UnitPriceDiscountProperty" Text="Unit Price Discount:" />
    <XDataLabel Property="@VM?.MainObj?.UnitPriceDiscountProperty" />
    <XLabel Property="@VM?.MainObj?.LineTotalProperty" Text="Line Total:" />
    <XDataLabel Property="@VM?.MainObj?.LineTotalProperty" />
When you run the application and open that view, it will look as shown below.

We used appropriate edit controls, such as dropdown lists and a textbox, for the first three fields that the user can enter. The last three fields are calculated based on the selected values of the first three fields, and cannot be entered directly by the user. So we used a display-only XDataLabel component for them, which is also bound to our properties.

Note also that the properties are automatically displayed using proper formatting, such as currency or percent.

Computed Properties

As you saw earlier, calculated display-only fields on a view are bound to data properties, where the value is not entered by the user, but is rather computed from the values of other data properties.

Specifically, the Unit Price is calculated based on the selected Product, and the Discount is calculated based on the selected Special Offer. Those selected values are represented by a Xomega Framework class Header, which stores an internal Id, the display text, and an arbitrary number of named attributes. The values of the unit price and discount are stored as special attributes of those selections, as you will see below.

The Line Total property is computed based on the specified quantity and the calculated unit price and discount. Let’s take a look at how to implement such computed properties using Xomega Framework.

Computed properties via events

The most straightforward way to implement a computed property is to add property change listeners to any other data properties that it depends upon, and then recalculate the computed value whenever the value of any of those data properties changes.

To implement the Unit Price we can override the OnInitialized method on our data object, and add a listener to the ProductIdProperty, which will update the UnitPriceProperty as follows.

protected override void OnInitialized()
    ProductIdProperty.Change += (sender, e) =>
        if (e.Change.IncludesValue())
            UnitPriceProperty.SetValue(ProductIdProperty.IsNull() ? null : 
                                       ProductIdProperty.Value["list price"]);

Note how we check if the change includes value, since data property changes may be fired for other metadata changes.

To implement the computed property for the Unit Price Discount, we will add a similar listener to the SpecialOfferIdProperty, and will set the value of the discount from an attribute of the selected special offer as follows.

SpecialOfferIdProperty.Change += (sender, e) =>
	if (e.Change.IncludesValue())
		UnitPriceDiscountProperty.SetValue(SpecialOfferIdProperty.IsNull() ? null : 

		UnitPriceDiscountProperty.Visible = !UnitPriceDiscountProperty.IsNull() &&
                                                     UnitPriceDiscountProperty.Value > 0;

In the same listener we update the visibility of the discount property in order to hide the field if there is no discount.

Finally, to implement the computed Line Total property, we will first add two helper functions: GetLineTotal that calculates the line total for supplied nullable values, and the UpdateLineTotal property change listener, which uses that function to set the value of the LineTotalPoperty from the values of the other properties, as follows.

private decimal GetLineTotal(decimal? price, decimal? discount, int? qty) =>
    (price ?? 0) * (1 - (discount ?? 0)) * (qty ?? 0);
private void UpdateLineTotal(object sender, PropertyChangeEventArgs e)
    if (e.Change.IncludesValue())
            UnitPriceDiscountProperty.Value, OrderQtyProperty.Value));

Now we just need to update the OnInitialzied method, and add the UpdateLineTotal as a listener to all the properties, whose values it depends on, as shown below.

    ProductIdProperty.Change += UpdateLineTotal;
    SpecialOfferIdProperty.Change += UpdateLineTotal;
    OrderQtyProperty.Change += UpdateLineTotal;

Remember that all this presentation logic is contained entirely in the data object, and does not depend on the actual UI layer, which means that you can reuse it with any UI framework.

Computed properties via expressions

While implementing computed properties via events, as described earlier, could be the most straightforward way, it’s not the simplest or the most natural one. Adding all these property listeners that recalculate values of other properties can get very tedious. And even after you add them all, you will have a hard time understanding how each computed property is calculated. You also need to be very careful when changing any of the calculations to make sure you add new listeners for any additional properties that computed value uses, and remove the listeners for the properties that it no longer depends on.

A more natural way to define computed properties is to just express the formula for calculating the value, and let the system update the computed value whenever the other properties change. This would be similar to defining such formulas for calculated cells in an Excel spreadsheet.

In order to support this, Xomega Framework added a new feature, where you can define an expression that takes any number of data objects or data properties and returns the computed value as an object. Then you call the SetComputedValue method on the target computed property, and pass that expression to it along with references to the actual objects for the expression’s arguments.

With this approach, setting up the computed UnitPriceProperty with an expression that takes the current data object will be very easy and succinct, as shown below.

protected override void OnInitialized()
    // computed property using the entire object
    Expression<Func<SalesOrderDetailObject, object>> xPrice = sod =>
        sod.ProductIdProperty.IsNull(null) ? null : sod.ProductIdProperty.Value["list price"];
    UnitPriceProperty.SetComputedValue(xPrice, this);

You can make it even more succinct and easier to read, if you make the expression based on specific data properties rather than a data object, as shown in the following snippet, which sets up the price discount based on the special offer.

    // computed property using individual property
    Expression<Func<EnumProperty, object>> xDiscount = spOf =>
        spOf.IsNull(null) ? null : spOf.Value["discount"];
    UnitPriceDiscountProperty.SetComputedValue(xDiscount, SpecialOfferIdProperty);

If you want to set up computed metadata, such as visibility or editability, based on the values or metadata of other properties, then you can use a similar expression that returns a bool. For example, the following code shows how to make the price discount visible only if its own value (the discount) is greater than zero.

    // computed visible attribute based on discount value
    Expression7lt;Func<PercentFractionProperty, bool>> xVisible = dp =>
        !dp.IsNull(null) && dp.Value > 0;
    UnitPriceDiscountProperty.SetComputedVisible(xVisible, UnitPriceDiscountProperty);

Finally, to configure more complex computed properties, such as our LineTotalProperty, we can make the expression use our helper function GetLineTotal, and just pass it the values of individual data properties, as follows.

    // computed total using a helper function
    Expression<Func<SalesOrderDetailObject, decimal>> xLineTotal = sod =>
    LineTotalProperty.SetComputedValue(xLineTotal, this);

Using helper functions like this will allow you to keep the expressions easy to read and implement, since you will no longer be limited by the expression syntax in the helper functions, and can use the full gamut of C# features there.


In this article you have learned the basic principles of Xomega Framework that uses observable data properties and data objects to implement reusable presentation logic of your application independent of the UI framework being used.

You saw how the property change events can be used both for binding data properties to UI controls, and to implement computed properties.

And lastly, you learned how the new Xomega Framework features allow you to easily set up computed properties using clear and concise expressions for the calculated value, without the hassle of managing any property listeners.

Please feel free to try out these new cool features of the Xomega Framework, and let us know how you like them.

New Xomega.Net 8.10.3 for VS2019 with advanced solution configuration

We are happy to announce a new release 8.10.3 of Xomega.Net for VS2019, which makes creating and configuring Xomega solutions and picking the right technologies for your application a total breeze.

Instead of dozens of preconfigured New Project VS templates for various combinations of technologies to select from, the new Xomega release provides a single, easy to find New Project template for creating or updating Xomega solutions, which allows you to select the technologies you want to use in your application, and then configure each included project as needed.

When selecting any technology or configuration, the Xomega solution configuration wizard will automatically select any other projects that are needed to support that technology. For example, if you select a Blazor WebAssembly client for your application, the wizard will also include projects for shared Blazor components, UI objects and view models shared with all clients, as well as projects for shared service contracts and service implementations. In addition, it will include a project for REST services, since that's the only supported communication protocol for Blazor WebAssembly clients.

On the other hand, if you select a WPF client, then you can configure your architecture on how it will communicate with the backend services - via REST or WCF as the middle tier, or directly call them and access the database from the client in the two-tier client-server architecture. Based on your selection the wizard will include a project for exposing services via REST or via WCF, or none of those for the two-tier case.

For other projects you can choose their relevant configurations, such as which ORM to use - EF Core or the classic Entity Framework 6.x, whether or not to host the WebAssembly in ASP.NET Core, and so on. You can also customize the project names to use for each project, if you don't like the default names.

Once you configure and create a Xomega solution, you'll be able to use the same New Project template to add and configure additional projects to it later on. Take a look at what the new process of creating Xomega solutions looks like in our updated walkthrough tutorial.

As a side note, we have also updated our installer to no longer offer installation of individual features, since all technologies use the same template now.

So go ahead and download the new release, and give it a test drive. We would love to hear your feedback on it, so please don't hesitate to contact us with any questions or issues.

Xomega 8.10 for VS 2019 with Blazor and .NET Core 3.1 support.

We are excited to announce our new major Xomega release 8.10 for Visual Studio 2019.

The main focus of this release is upgrading to the latest .NET Core 3.1 technologies for building web and desktop applications. This includes adding support for the new Blazor Server web apps, upgrading WPF and EF6 to their latest .NET Core versions, using ASP.NET Core REST services for multi-tier apps, and switching to use asynchronous operations both on the client and server sides.

The legacy .NET Framework technologies, such as WebForms and WCF, have been also upgraded to support async operations. We recommend to use them only if you want to add Xomega to your existing systems that use these technologies, or if you are more familiar with them, and would like to try out Xomega before moving up to the latest .NET Core technologies. Since most of the code is shared, you can easily switch from one technology to another.

Below please find a summary of the updates in the new release.

Blazor Server support
  • New template to create Xomega Blazor solutions and projects.
  • New package Xomega.Framework.Blazor that provides base views and components for Blazor server projects based on Xomega Framework.
  • Generation of Blazor views from the Xomega model.
  • Authentication and authorization support.

Common enhancements
  • Support for async operations with cancellation tokens on both the client and server sides.
  • Upgrade to Entity Framework 6.4 to allow using it in .NET Core apps in addition to the Entity Framework Core.
  • Generation of REST service clients in C# that allows multi-tier client apps to use ASP.NET Core REST services.
  • Minimized custom code required to implement contextual lookup tables.
  • Support for dynamic view titles with modification indicators in view models.
  • Localization support for common messages.
  • Using Xomega Framework 3.0.0 with support of the above features and other improvements and bug fixes.
  • Using the latest versions of the NuGet packages.

WPF enhancements
  • Upgrade to use the latest cross-platform WPF on .NET Core 3.1
  • Upgrade to support async operations to minimize UI freezing.
  • Using REST services for multi-tier WPF apps now, with an option to still use legacy WCF services.
  • Allowing to create a custom window for generated views.
  • Project file for WPF projects upgraded to .NET Core format, allowing to not have to add generated files to them, and to customize file nesting rules.

SPA enhancements
  • Consuming REST services that use System.Text.Json for serialization.
  • Upgrades to the TypeScript XomegaJS 3.0.0 framework to support new features in the Xomega Framework 3.0.0.

WebForms enhancements
  • Upgrade to support async pages and operations to improve scalability.

Since Visual Studio 2017 does not support .NET Core 3.1, all this functionality will be available only from VS 2019 and up, so we recommend that you upgrade to the latest version of Visual Studio.

As you may know, VS 2019 changed the way New Project dialog works, and shows a single searchable list of project and solution templates rather than an organized tree view. With the number of technologies Xomega supports and their combinations, there are currently 33 different Xomega project templates, which may be confusing to navigate. In a future release, we are planning to add a wizard that would help you pick the desired combination of technologies and features to build your solution.

We are also going to update the documentation, but most of the steps are either similar or the same as before. You can follow us on twitter to stay tuned with these updates. Also check out our updated sample solution on github that demonstrates all the technologies and various Xomega features.

So go ahead and install the new release to start with these new technologies now. Feel free to contact us if you have any questions or issues with Xomega.

Support for .Net Core added to Xomega for VS 2017

We are excited to announce a new Xomega release 7.9 for Visual Studio 2017.

The main target of this release is the support of .Net Core, which allows you to use the latest, yet already quite mature Microsoft technologies, in order to quickly build high-performance cloud-enabled web applications in addition to the regular desktop apps.

Here is a summary of the new features in this release.

Support for Entity Framework Core.

You can now generate the entities and DB context classes either for the original EF 6.x or for the new EF Core, based on a flag set in the global entities configuration in the model. You can also generate extended partial classes for selected entities to add your custom code to.

ASP.NET Core REST Services.

The project for REST services has been updated to use ASP.NET Core 2.2 and EF Core instead of the older OWIN-based Web API package. This allows you to easily host your REST services on any machine as well as on the cloud.

To improve performance of the REST services, they now use asynchronous services by default, which helps them handle higher volumes of requests. You can still use traditional synchronous services though by setting the corresponding async parameter on the global services configuration in the model.

Updated Project Templates.

Project templates for creating new Xomega solutions or individual projects have been updated to use EF Core, but the legacy templates for EF 6.x are also available as an alternative.

All shared projects use the slim .Net Core format now, which makes them automatically pick up new changes after code generation without having to reload them.

Right after you add a new solution, you will be able to build it now without having to build the model project first.

And finally, all third party NuGet packages for the solution will be installed from the standard sources configured in your Visual Studio, such as, instead of the local file system. This helped to cut the size of the installation download almost in half by not including any external packages.

For Visual Studio 2015 users

Unfortunately, Visual Studio 2015 does not support the latest .Net Core projects, nor is it likely to support them in the future, given the upcoming release of the VS 2019. Therefore, these new features will be only available for VS 2017 and up.

We did release a patch 6.8.1 for VS 2015 though, which contains some fixes for the previous release. Note that after we release a Xomega version for VS 2019, support for the VS 2015 version will be discontinued, so we recommend that you upgrade to the latest version of Visual Studio.

We hope that you’ll enjoy the new features once you go ahead and install the new release, but please feel free to contact us if you have any questions or issues.

Introducing support for Flexible Operators

In release 7.8 Xomega has tremendously improved support for operators that are used to build search forms and LINQ queries.

Thanks to the framework support, using operators to build LINQ queries takes just a single line of code now. The framework comes loaded with standard operators for common data types, as well as dynamic operators for ranges of (relative) dates and numbers. Plus, it allows you to implement and plug in your own operators or override the behavior of any of the built-in operators.

Read on to learn more about these powerful features.

Framework to support operators for building queries.

While Xomega supported operators for query operations before, it was using a predefined list of operators, and each operator was handled explicitly for each criteria in the generated service, which resulted in a rather bloated and inflexible generated class.

With addition of the operators support to the Xomega Framework, including in the BaseService class, handling any criteria with operators takes just one line in the service now. Not only does it make the generated code much more cleaner, but it also helps writing custom code for non-standard criteria so much easier.

Standard operators for common data types.

Xomega Framework provides implementation for most of the standard operators on the common data types, such as Is Null, Equals To, Less Than and Greater Than, Between etc., including the corresponding inverse operators.

You can also develop and register your own implementation of any custom operator, or even override implementation of any of the standards operators.

Dynamic operators for date ranges using relative dates.

In addition to the standard predefined operators, Xomega Framework supports dynamic operators for date ranges. For each upper/lower bound of the range you can use either an absolute date or a relative date, such as ‘ct’ for the current time, ‘bo(s/m/h/d/w/M/y)’ for the beginning of second, minute, hour, day, week, month or year respectively, or the ‘eo(s/m/h/d/w/M/y)’ for the end of the same period.

You can further adjust it by adding or subtracting a certain number of periods, e.g. -60d to subtract 60 days, and also indicate whether you want to include or exclude the bound by using either square brackets or parentheses respectively.

For example, Xomega supplies the following standard dynamic range operators for relative  dates, but you are free to define your own operators like that in your Xomega model.
      <item name="Today" value="[bod,eod)"/>
      <item name="This Week" value="[bow,eow)"/>
      <item name="This Month" value="[boM,eoM)"/>
      <item name="This Year" value="[boy,eoy)"/>
      <item name="Last 30 Days" value="[bod-30d,ct]"/>

Dynamic operators for number ranges.

Similar to the date ranges, Xomega Framework also supports dynamic operators for numeric ranges. So, for certain numeric fields you may want to let the user select criteria for some  predefined ranges instead of, or in addition to, manually supplying the From and To values.

For example, to filter something by price you can define low, medium, and high price ranges,  which you can call  Budget, Average and Luxury respectively, as follows.
      <item name="Budget" value="[0,100)"/>
      <item name="Average" value="[100,1000)"/>
      <item name="Luxury" value="[1000,)"/>

These operators do not require additional values, and are more convenient for the user. If none of your operators for a certain field require additional values, then you can also make the operator parameter multi-value in the Xomega model, which will allow the user to filter by multiple ranges at the same time.

New Service Validations in Xomega 7.8

Xomega now supports more easy and powerful validation on the server side, which ties into the Xomega error reporting framework.

This includes service request validations using Data Annotations, as well as user-friendly errors for common constraint violations as follows.

Improved validation of entity existence.

The services project template includes a convenient extension method to find entities by the key(s) and report an immediate 404 error if the entity is not found. This method is used by the generated services, and can be used by the custom code, which makes the code much cleaner.

Improved validation of foreign keys.

Similar to the entity existence validation, there is now a simple method to validate if the supplied foreign key(s) are valid. Unlike the previous validation though, it reports a regular error, which allows to gather all applicable errors before running the business logic and report them in a user-friendly fashion, as opposed to the DB constraint violation errors.

Validation of duplicate primary keys.

Another added validation that is also used by the generated services allows you to validate if the entity with the given key(s) already exists when creating a new domain object, which also reports a user-friendly error instead of a DB primary key violation.

Request validation of required fields, maximum length and enumerations.

The UI forms generated by Xomega already take care of validating user input in terms of required fields, maximum length etc. and make sure the values for enumerated fields are selected from the associated list.

However, the best practices for multi-tier architectures call for the business services that are exposed via REST or WCF to also perform such validations, without relying solely on the client for those. While some of these checks would be done by the database as well, Xomega now validates request values upfront, and reports user-friendly errors before running the business logic.

Improved Error Reporting in Xomega 7.8

Xomega has made some significant changes in the way errors and other messages are reported from the business services and displayed to the user.

This includes ability to return not only errors, but also warnings and info messages from any service operation in a standardized way, and handle them consistently by displaying them in a configurable closable panel as described below.

Ability to return (warning/info) messages from services along with the results.

Validation errors, as well as other types of errors from business services are returned to the client using standard Xomega Framework structures for error messages, which allows handling them consistently on the client side. However, if a service operation succeeds and has no errors, but still needs to report some warning or info messages to the client, potentially also with the actual results of the operation, there was no standardized way to report those, and you’d have to custom design each such operation to return the necessary messages.

With the new release, each Xomega service operation now returns a standardized list of errors, warnings and/or info messages in addition to the actual results of the operation, where applicable. This way any service operation can easily report additional warning or info messages, which would be displayed to the user, without having to customize its output structure.

For example, an update service operation may report some warnings to the user based on business validations. Or a service may report cross-cutting messages informing the users about a scheduled downtime or about a newer version of the service available.

Reported messages and errors displayed consistently in a closable panel.

Previously the validation and service errors were displayed inconsistently across the UI clients as a simple list either on the screen or in a popup dialog for WPF clients. The errors could be closed also inconsistently - by closing the dialog in WPF, after any postback in WebForms, and after re-running the validations and the service operation in the SPA client.

In the current release, all Xomega messages from client-side validation or service operations are consistently displayed in a closable panel on the same view that triggered the operation as shown below.

This way the users can have the messages up while they are addressing the errors on the screen, or they can just close it if they don’t need it anymore.

Configuration of the messages panel layout.

In addition to the messages being in a closable panel now, you can now configure whether you want to display it at the top or the bottom of the form for both the search and details screen. This is done as part of the view layout configuration in the model, which you can configure in one place, or override for each individual view as needed.