The Compleat History of Data Access Patterns


One of the great things about Xamarin development is that we get to use many of the concepts we learned in pre-mobile development. Software architecture is a good example. Most of the software patterns that we used in web development are still applicable.

Let’s look at the data access patterns outlined by the master of enterprise software architecture, Martin Fowler. We can still use the pre-OO procedural approaches to coding like his Transaction Script, Table Module, and Table Data Gateway. Then we can code using strictly object-oriented patterns such as Domain Models, Data Mappers, and the ever-popular Repository. Many of these are the equivalent of or have evolved into the patterns we use today such as POCO, Controller, ViewController, and ViewModel.

If you want to explore the Xamarin Data Access Layer(DAL) in the context of traditional enterprise design patterns then read on. If you just want to know how to create a DAL using the Repository pattern in Xamarin, then stay tuned for my forthcoming blog entry on the Repository.

Let’s begin at the beginning with the old-skool patterns.

Procedural Patterns

The point of object-oriented design was to wean us off of the procedural approach. Before we created domain models, data objects, object-oriented business logic and the like, we created a list of procedures to call, which is now called the Transaction Script pattern.

Transaction Script

We make calls to these procedures that return the data we need. Using the Transaction Script pattern (though most of us don’t call it that when we’re using it) and some pseudocode, our app looks something like this:

class void MyEntireApp 
    public GetSomethingAndDoSomethingWithIt() 
    public GetSomethingElseAndDoSomethingElseWithIt() 

Data access and business logic were wrapped up together in this construct. Until…someone became annoyed with how long this list of procedures was (and sadly we used let it hit the floor sometimes). They would call this a long method code smell and say that the Transaction Script had become an anti-pattern. Another approach was employed to break up these procedures according to the tables in the database.

Table Modules

Blocks of table-specific business and data access logic are now called Table Modules. This one is for the Item table.

class void ItemTableModule() 
    public GetPersonAndDoSomethingWithIt(int ID)
    public GetPersonAndDoSomethingElseWithIt(int ID)

Mind you, we haven’t yet introduced a domain model, so the business logic is probably operating on database-specific entities, such as Record Sets or variables from rows specified using numeric IDs. What we have here is a coupled business and data access layer grouped by table, violating Separation of Concerns (SOC).

The next step is to break out the data access logic into separate table-specific data access components which Fowler calls Table Data Gateways.

Table Data Gateways

A Table Data Gateway handles all of the data access for a particular table: usually CRUD-style (create, read, update, delete), using row ids.

class void ItemTableGateway 
    public Get(int Id)
    public Put(string Name)
    public Update(int Id, string Name)
    public Delete(int Id)

The Table Data Gateway houses basic data transactions as well as more advanced queries and inserts, but the results are generally record sets.  The record sets are generally passed back to the Table Module which can then handle the business logic. Using a Table Module with a Table Data Gateway gives us separation of business and data access logic, all without much object-oriented programming.

If all of the tables in the database are handled using Table Modules and Table Data Gateways, a facade class can be laid on top of all of them to provide easy-access to all data calls in one place. This pattern is a monolithic Table Data Gateway which I’m going to call a Database Gateway (my term, not Folwer’s). A Database Gateway has all table CRUD calls for all tables in the same class( and hints at important things to come when we get to the Repository pattern in OOP).

Database Gateway

Here’s a Database Gateway for both Item and Person tables.

class void DatabaseGateway
    public GetItem(int Id)
    public PutItem(string Name)
    public UpdateItem(int Id, string Name)
    public DeleteItem(int Id)
    public GetPerson(int Id)
    public PutPerson(string Name)
    public UpdateItem(int Id, string Name)
    public DeletePerson(int Id)

Not very pretty but, for a small number of tables, quite concise and organized. You’ll see soon why a Database Gateway is important in Xamarin development.

Those are some oldie-but-goodie non-OO patterns  useful in simple apps or in simple components of OO apps.  Now, fast-forward to the present.

Domain Model Patterns

Enter domain models! Create classes that represent specific entities within the workflow and have a one-to-one relationship between a business entity and an object instance (like a physical car and a Car object). Here is where we stopped sticking all of our logic in procedures (pre-OOP-speak for method), and started constructing classes to represent our domain logic. In simple apps that means an Item class or a Group class, which pretty much correspond to our table names.  In more complex apps this means lots of classes which correspond to different entities and processes that arise as a result of defining user stories or system architecture.

Let us begin with the simplest of the object-oriented patterns.

Domain Model

Now called a ‘model containing business logic’, Folwer’s Domain Model is an OOPified Table Module pattern. This class reflects our domain logic with names like Item, Person, Building, Conversion, Forecast, Event, and Reimbursement. Each object instance generally corresponds to a single physical thing. For example, each instance of an Item class represents a single physical item. A Domain Model class for an item entity might look like this.

class void Item() 
    public int Id {get;set;}
    public string Name { get; set;}
    public BuyItem(Item item)
    public ReturnItem(Item item)

Today, most apps separate the Domain Model into its constituent data fields and data access calls. POCOs (Plain Old CLR (or C#) Object) contain primarily strongly-typed data fields and sometimes property attributes and a method or two. Typically, ViewControllers or Controllers house the business logic and handle data using data models.  This is an important point, but meanders away from our data access pattern topic. This article doesn’t cover the much-discussed MVC and MVVC patterns.

Back to the Domain Model and data access. All of our logic surrounding the processing of an Item is now  tucked into the Item class.  Unfortunately, that also includes the data access logic. So, once again, now we have business logic and data access logic that is tightly coupled. We require the same type of decoupling solution that Table Data Gateway offered us, but in the world of OOP. Enter the Data Mapper.

Data Mapper

A domain object-oriented data access class is called a Data Mapper, which is an implementation of CRUD for a specific table or entity.

class void ItemMapper() 
    public Item Get(Id id)
    public void Put(Item item)
    public void Update(Item item)
    public void Delete(Item item)

This Data Mapper, called ItemMapper, is the data access component for the Item Domain Model. Now the Item class discussed earlier can contain only business logic and make data calls to ItemMapper. We have appeased the great god SOC (Separation of Concerns).

Data Mappers typically handle only single objects, not collections. If you want to return and handle collections you’ll need a to use a Repository pattern.


The most common choice for a data access pattern by Xamarin developers in their apps, a Repository for a Domain Model is basically a Data Mapper for a collection, such as ItemRepository for Items.

class void ItemRepository
    public List[Item] GetAllItems();
    public void PutAllItems(List[Item] items);

Using Domain Models, Data Mappers, and Repositories in this way will result in a pile of class pairs like Item and ItemMapper (or ItemRepository), Person and PersonMapper, Building and BuildingMapper, and Conversion and ConversionMapper.

So many Mappers (or so many Repositories)!

Some developers might be pleased with the elegance and OOPness of this architecture.  Others might think that it spreads the code out too much. Multiple Data Mappers and Repositories can smell of code duplication, so sometimes we want all of our Mappers available in one place. Creating a facade or an additional layer of abstraction over the mappers offers a single location where all data access can take place, which is divided behind the scenes to the appropriate data mapper. Filtering and code reuse all take place in methods to optimize the data access layer.

A simple Database Repository for the Item and Person classes might look like this.

Add this:

    public List[Item] GetAllItems()
    public void PutAllItems(List[Item] items)

to this:
class void Repository
    public Item GetItem(Id id)
    public void PutItem(Item item)
    public void UpdateItem(Item item)
    public void DeleteItem(Item item)
    public Person GetPerson(Id id)
    public void PutPerson(Personitem)
    public void UpdatePerson(Personitem)
    public void DeletePerson(Personitem)

The Repository is the OO version of the Database Mapper that we discussed earlier. It provides an app-wide location for all data access calls, but this time the calls employ the object-oriented Domain Model instead of procedures that execute some SQL and return record sets.  Repository methods call the appropriate Data Mappers, then filter and process the data that is returned.

class void Repository
    public Item GetItem(Id id)
    public void PutItem(Item item)
    public void UpdateItem(Item item)
    public void DeleteItem(Item item)
    public Person GetPerson(Id id)
    public void PutPerson(Personitem)
    public void UpdatePerson(Personitem)
    public void DeletePerson(Personitem)
    public List[Item] GetAllItems()
    public void PutAllItems(List[Item] items)

So that’s a Repository. Awesome. Study it closely. You’ll need this one.

Note: The definition of the repository pattern has evolved since its inception.  It was originally intended as an abstraction to decouple the data layer  implementation (for example, SQLite) from the rest of the app with the added benefit of providing in-memory data-object collections. Over the years, many C# apps needed the decoupling but not the in-memory data objects, so those collections have evolved to become data objects returned by methods in many cases, not persisted in repository properties. This is true in most mobile apps as well.

That’s the compleat data access story. Here’s the recap.


Pre-OOP we built coded everything in Transaction Scripts, code that made calls to procedures for everything. Then we divided code into Table Modules, organized by the data in our tables which contained both business logic and data access. Record ids were passed into these procedures and they returned record sets. Awareness of the importance of decoupling led to data layer code called Table Data Gateways which handled CRUD transactions for each table. Table Data Gateways were sometimes aggregated into facades, which I call Database Gateways, which handled all data access in the application.

OOP gave us the ability to do all of this using data models instead of record sets, which means a more powerful and more app-specific toolset for data access. Domain Models, like Table Modules, let us build entity-specific objects except that the actual data fields used.  Domain Models are data models combined with business logic. Loosely couple the data access from that business logic by making a Data Mapper, implementing of CRUD for a specific table for a single table or entity: Get, Put, Update, and Delete.  Even a few Data Mappers can create a confusing data access interface. Simplify with a Repository, which is a facade over top of all your Data Mappers, providing a single entry point for all data access without compromising SOC.

Most mobile app development uses a Repository of some kind.

Data Access Using Xamarin

What does any of this have to do with Xamarin development?

Here’s what: The SQLite.NET ORM has already created Data Mappers for us. Let me say that again. SQLite.NET is a big library of table-specific Data Mappers. SQLite.NET will return Item objects from the your Item table, Person objects from your Person table, etc., etc., assuming that you’ve mapped the fields correctly in your data models.

Creating a data access class (or classes) which uses a bunch of calls to SQLite.NET is often an implementation of the Repository pattern. Now we can code our mobile DAL in the context of design patterns that are familiar.

In a later post I’ll talk about how to use the Repository pattern to implement SQLite.NET in a Xamarin app.

How to Mobilize Web and Desktop Business Apps


If you’re a business with a suite of mobile apps, you have an advantage in the mobile game. You already have a product direction. You also have a technology foundation. The trick is determining appropriate directions for mobile apps which leverage these assets. What to mobilize?

1. Identify Candidates
Look first at your existing app suite, whether it’s desktop or web. Pinpoint areas that provide simple, easy-to-display feedback to the user. Look for important or frequently used:

  • Dashboards
  • Reports
  • Functionality

If you’re not certain about functionality, then focus on important junctures in your users’ workflow.  Seek ways to facilitate key decisions. Identify candidates for migration from your existing application suite.

2. Sell and Market
Some of the best apps are artful blends of key functionality, useful marketing collateral, and the sale of relevant products. Marketing collateral can include videos, images, and articles. Sales can include e-commerce, so the user can shop for themselves, or tactful, appropriate offers. Sales and marketing in an app can be useful and valuable to a user if it is carefully considered. Don’t just put in pitches and collateral that you think are slick.  Ask yourself: I’m a user and I’ve taken my valuable time to download this app. Does it give me what I need? Will I be amazed and delighted by it? Useful tools such as customized needs assessments, calculators, or interactive graphs can engage a user while stoking the sales process.

2. Consumption Not Production
Mobile device screens are smaller than their PC counterparts and the mobile experience is generally about speed, not depth. Many PC apps are 50% about viewing information and 50% about entering and interacting with it. PCs are production tools, built for helping their users produce information. Mobile devices are tiny media centers, built for easy consumption of information. Take what your apps are already doing and simplify it so that the user experience is closer to 80% viewing info and only 20% interaction, and make that 20% extremely easy on your user.  (and most mobile production seems to be of a social nature) Give them quick access to tons of your apps’ great content with as little effort on their part as possible.  Mobile users with their apps are mostly consuming (and communicating) not producing.

3. Leverage Existing Tech
Reuse of your databases and other back-end tech like stored procedures and APIs may help save your company a lot of time and money. Don’t assume that everything will have to be written from scratch. If you’re working from an existing system, it’s more likely that you’ll simply need an “adapter” from the old back-end to your new mobile one.

4. Innovate
Opportunities abound for innovation in mobile so don’t be afraid to go off script. Mobile apps are not always just tinier versions of web apps.  Innovation in mobile often has to do with taking advantage of unique phone capabilities, like GPS, camera, voice, integration with other systems and objects, real-time notifications and updates, or simply the fact that the user takes the device wherever they go.

You and your team will probably come up with dozens of ideas for great mobile apps.  Run them by your staff, and even by a few trusted users. Then pick the top three. Ask yourself which one of those would make your users ecstatic and commit to it.  Flesh it out. Build a prototype. Show it to your users and see what they say.

That’s how to mobilize.

Xamarin Dev Days 2016 Recap


Xamarin Dev Days happened in Boston!  Here are some pics from the event on Twitter.

I spoke about Xamarin.Forms 2.0 Effects, which are a lightweight approach to custom controls. Also, if you just need a real native control, you can now embed native controls right into your Xamarin.Forms pages by adding them as children of a layout just like regular Forms controls.  Recycling cells in your ListViews for performance and memory usage improvements using ListViewCachingStrategy.RecycleElement. XAML is now compilable using the XAML compiler (XAMLC) for faster loading, smaller app size, and errors shown at build time rather than at run time (too late).  Themes extend styles with new ways to apply design to your entire app.

Jesse Liberty kicked the event off with an intro to Xamarin, covering the API for iOS and Android.  Gavin Bauman spoke about connecting your Xamarin app to the Azure cloud. Pierce Boggan led a hands-on lab. The event was organized by Pierce Boggan and Jayme Singleton (a killer last name in the software development industry).

Look for Xamarin Dev Days in your area.

Xamarin Navigation Design Patterns

Navigation gives a user what they need to get around an app quickly, moving from screen-to-screen with confidence and ease. This may include menus, tappable icons, buttons, tabs, and list items, as well as many types of gesture-sensitive screens to display data, information, and options to the user.

Navigation patterns are industry-standard templates for tying an app’s screens together in an elegant and usable way. The two most common visual design patterns in mobile navigation are hierarchical and modal. Out of these base navigation patterns come an entire family of derivative patterns which combine, enhance, and decorate these patterns to create the full range of mobile UI patterns available. Here is an exhaustive list of the most common mobile UI navigation patterns used in Xamarin development:

  • Hierarchical – a stack-based navigation pattern where users can move deeper into a screen hierarchy, then back out again one screen at a time using the up or back buttons
  • Modal – a screen which interrupts hierarchical navigation, often a pop-up screen with an alert or menu which the user can complete or cancel
  • Drilldown List – a list of tappable items selected to display item detail
  • Navigation Drawer – a navigation menu which slides over from the left side at the tap of an icon, typically three horizontal lines in the upper-left part of the screen known as the “hamburger”
  • Tabs – a bar containing several folder-like tabs at the top or bottom of the screen each with tappable icons or text invoking new pages
  • Springboard – also referred to as a dashboard, this is a grid of tappable icons invoking new pages
  • Carousel – horizontally-slidable screen-sized panels, sometimes containing large images

Let’s explore two of the most common navigation patterns, hierarchical and modal.


Hierarchical is a stack-based pattern where users can move deeper into a screen hierarchy, then back out again one screen at-a-time using the Back or Up button. This typically involves a toolbar at the top of the screen which displays an up button in the upper-left corner of the screen when a page is selected or “drilled down into” by any means. As the user drills deeper into the menu structure, a stack is maintained with each page pushed onto it. Two buttons are used in tandem to navigate backwards, popping pages off of the stack: the up and the back button.  The back button is the curved arrow icon on the bottom of the screen, although iOS doesn’t have one. The up button is the “less than” icon in the upper-left corner. Deep navigational stacks can be traversed in this manner with page selection requiring the use of additional UI navigation patterns such as the navigation drawer, drilldown list, or popup menu.


A Modal is a single, interruptive popup or screen which comes in two flavors. The most common type floats overtop the main page and is usually an alert, dialog, or menu which the user can respond to or cancel.  Navigation reverts back to the originating page when the modal is dismissed. A modal informs the user of some important event, such as a saved record, or gives them the opportunity to provide input or direction, such as a menu or whether to commit or cancel a transaction. The second, less common, type of modal replaces the main page entirely, interrupting the hierarchical navigation stack.

The two most common modal menus in the mobile UI are the Navigation Drawer and the Action Menu. The Navigation Drawer typically slides in from the left and is triggered by the tapping of an icon in the upper-left corner of the screen (usually “the hamburger”) and displays a list of pages to navigate to.  The Action Menu typically slides in or pops up on the right side of the screen, and is invoked by tapping an icon in the upper-right corner of the screen (usually three vertical dots) and contains mostly operations (ex. Favorite This), though less frequently some navigation pages as well.  To follow this established UI pattern, remember the rule: Nav on the left, action on the right.

Hierarchical and modal UI navigation patterns are typically used as complementary techniques with hierarchical providing the skeleton of the navigational structure and modals giving the user choices for what they want to do and where they wish to go within the app as well as informational updates along the way.

Xamarin.Forms provides most of the primary navigation patterns out of the box:

  • Hierarchical navigation using NavigationPage
  • Modal using NavigationPage, alerts, and ActionSheets
  • Drill-down lists using NavigationPage, ListView, and TableView
  • Navigation drawer using MasterDetailPage
  • Tabs using TabbedPage
  • Springboard using images with gesture recognizers
  • Carousel using CarouselPage

I hope that’s enough to get you thinking about navigation in your own apps. In my book, I explore hierarchical, modal, and the rest of the navigation patterns on each platform. The navigation chapter in the book is really one its crown jewels, providing you with patterns to build just about any app you can imagine! If you want to check out the navigation patterns in code, head over to GitHub and look at chapter 6. You can use that code to lay the groundwork for just about any business app!

In last week’s post I covered the Drilldown List pattern. In upcoming posts, I’ll talk about more of the the key navigation patterns in detail.


Navigation Patterns: Drill-down Lists

A drill-down list is a list of tappable items selected to navigate to a new page.


There are many ways to build them using Xamarin.Forms, and the following recipe covers the most common type: by item. Other common types include lists by page and grouped lists.

A drill-down list by item has rows that can be selected to display more information about each item: the traditional master-detail pattern. This recipe uses a ListView to bind to a data model to provide a dynamic list of tappable items. A grouped drill-down list built using TableView is useful for creating categorized static menu items but ListView is one of the most versatile tools for creating drill-down lists. Short lists can, of course, be constructed by hand by using any of the layouts filled with buttons or labels paired with gesture recognizers to handle taps. Longer lists lend themselves to data binding using ListView.

Many lists contain a bunch of items that a user wants to drill down into to reach details about each item. Use ListView to display a list of items data-bound to a data model, and then show a detail page by using
PushAsync , all wrapped in NavigationPage so the user can get back to the list. You can create your ListView using the standard Xamarin.Forms approaches, such as in my post Making a Scrollable List Using ListView. This implementation uses a list item class called DrilldownListViewByItem.

Instantiate the DrilldownListViewByItem page in the Application class’s constructor wrapped in NavigationPage.

public class App : Application
    public App()
        MainPage = new NavigationPage(new DrilldownListViewByItem ());

This creates the a list with a navigation bar on iOS and Android. Windows Phone doesn’t display the navigation bar.

Create a detail page called detailPage whose constructor takes ListItem as a parameter. ListItem must contain either a list item ID for a detailed lookup query or all the fields needed to display on the detail page. This detail page displays a title and description.

class DetailPage: ContentPage
    public detailPage(ListItem listID) { // display detail }

Back on the list page (DrilldownListViewByItem) when an item row is tapped, pass ListItem into the detail page, which displays the detail of that particular item.

listView.ItemTapped += (sender, args) => {
    var item = args.Item as ListItem;
    if (item == null) return;
    Navigation.PushAsync (new detailPage(item) );
    listView.SelectedItem = null;

Tapping a list item row triggers the ItemTapped event, and the PushAsync call instantiates a detailPage and passes in ListItem to display.


You can see the complete book example on GitHub here.

The Drill-down List by Page pattern lets you select a ContentPage then instantiate it when it is tapped. Add a page type property to the list model and navigate to the page using the Activator.CreateInstance method.

Page page = (Page)Activator.CreateInstance(item.PageType);

Check out the book code here for the Drill-down List by Page recipe.

Our Award-Winning Mobile App


I’m proud to announce that PCR Essentials, a mobile app we developed for Android using Xamarin, was awarded a Davey Gold Award and a W3 Award by the International Academy of the Visual Arts (IAVA). Commissioned by Thermo Fisher Scientific and Grand Interactive, this app pushes the boundaries of the Internet of Things (IoT) by bringing real-time data directly from DNA-processing laboratory equipment into the hands of scientists on their mobile devices. The Davey awards are run by the Academy of Interactive and Visual Arts(AIVA). With nearly 4,000 entries from across the US and around the world, the Davey Awards honor the finest creative work from the best small firms, agencies and companies worldwide.  Here it is on Google Play.

The app was also a finalist for a Xammy.  The Xammys are awarded by Xamarin, the company who built the cross-platform technology we used to create the app.  Our award finalist video opened the entire Xamarin Evolve 2014 Conference. What an honor to see our work up on the big screens to kick off this week-long epic mobile conference!

Continue reading

For Science! A Xamarin Internet of Things(IoT) Mobile App


Our latest mobile creation just hit the app store! Commissioned by a Thermo Fisher Scientific brand, Life Technologies, this app pushes the boundaries of the Internet of Things (IoT) by bringing real-time data directly from DNA-processing laboratory equipment into the hands of scientists on their mobile devices. The app provides a suite of functionality ranging from training videos, a full e-commerce experience with lab product details, specs, images, and downloadable PDFs, and a specialized calculator for creating properly balanced solutions for use in the featured lab equipment. The pièce de résistance is the live lab interface empowering the user to log directly into thermal cycling devices, ProFlex™ and SimpliAmp™, to check on their status and temperature. These devices, solutions, and mobile interface are used to conduct lab experiments, replicating a single piece of DNA into thousands to millions of copies of that DNA sequence. The app is used in cancer diagnosis and research as well as studies in genetics. Continue reading

Cross-platform UI Coup: Xamarin.Forms


One of the biggest problems with C# mobile development, platform-specific UI, is solved with Xamarin 3.

The greatest foe we face in our quest for cross-platform implementation is platform-specific code.  Code that is platform-specific must be implemented differently depending on the platform, whether iOS , Android, or Windows Phone.  Cross-platform patterns are the same regardless of operating system.  Cross-platform code is sometimes referred to as shared code, or core code, as it is shared between projects for different mobile operating systems. Certain types of code lend themselves well to cross-platform sharing and other code less so.  The rule of thumb is that the closer the code is to the user, the harder it is to share.  The most reusable code is the server-side web service.  The client-side data layer is often reusable.  The business logic tends to be partially entwined with the UI so there is overlap here between platform-specific and cross-platform code. UI code is nearly impossible to share between platforms. Nearly impossible until the release of Xamarin 3 which includes Xamarin.Forms. Continue reading

Managing Mobile in the Workplace


We bring our phones to work now and use them for everything.  Facebook, Candy Crush, and Twitter are a great use of a smartphone but these devices are also helping us become more productive: email, file and document handling and editing, as well as contacts, calendars and integration with sales, financial, and other third-party business apps.  This creates two things:  opportunity and challenge.  We want to seize upon the opportunity of best utilizing these devices to do our jobs while addressing the challenge of the resulting exposure of company data and security.  Enterprise Mobile Management (EMM) is the overarching approach to tackle these issues.  Continue reading

Xamarin Names Lexicon Systems as Mobile Partner


Lexicon Systems was named a Xamarin Premier Consulting Partner for mobile application development.  Using Xamarin product suite, Lexicon Systems provides a cross-platform solution for mobile development using Microsoft technologies.   Built upon the open source Mono and MonoTouch for iPhone projects these technologies allow .NET developers to create mobile apps portable to Android, iOS, and Windows phones. Microsoft partnered with Xamarin in the Fall of 2013, a crucial backing for this direction. We offer guidance, training, and development using Xamarin, and assist businesses nationwide with their shift to mobile. Continue reading