KISS Architecture (part 9)

by Chris 23. January 2009 16:11

In this part, I will continue the implementation of the presentation tier for Windows Mobile, and if you want some background, please see the previous parts:

  • Part 1 was a general introduction
  • Part 2 outlined the architecture (tiers, etc)
  • Part 3 showed the benefit of loosely coupled tiers (distribution, cloud, etc)
  • Part 4 started the implementation by creating the entity data model (using ADO.NET Entity Framework)
  • Part 5 published the entity data model as a data service (using ADO.NET Data Services)
  • Part 6 implemented the business domain (using the data service)
  • Part 7 created the service (using WCF)
  • Part 8 started the implementation of the mobile client (using WCF)
  • The implemented architecture is published on CodePlex in a project called KISS Architecture, and this means that you can access the full source code as well as discuss it, come with suggested improvements, etc. As I walk you through the creation of the architecture, I suggest you keep the source code handy to check out more details.

    In the previous part (8) of this blog series, I showed how the Windows Mobile client can call a WCF service when connected to the network. However, there are a number of times when the mobile device is not connected and still need to allow the application to function. It would be really awesome if the new technologies like ADO.NET Data Services, ADO.NET Entity Framework, LINQ to Entities, etc, were available also for Windows Mobile and .NET Compact Framework, as this would mean that we could use identical code (assemblies/tiers) on the client, but unfortunately they are not (yet).

    So, what is the second best solution? I still want to make use of the entities defined by the (data) service tier, and not maintain any custom entity code. Also, I want the implementation to be as simple as possible (remember the KISS principle) and make it as easy as possible to upgrade when these new technologies are available. That means that I don't want to spend time writing my own custom framework, but rather something simple that just works.

    To allow local data storage, I create a SQL Server Compact database by adding a "Database File" named Northwind.sdf to the Kiss.Mobile project. To that database, I then add the same tables that our order (data) service defines (see part 4 of this blog series). I also add a plain class named Common.cs to the same project that is a singleton holding a single connection to the database.

    With the local database in place and a connection to it, the code for the "Get" menu item can be changed into:

    private void getMenuItem_Click(object sender, EventArgs e)
    {
       
    Customer[] customers;
       
    if(online)
        {
           
    OrderServiceClient.EndpointAddress = new EndpointAddress("http://192.168.0.100:2222/OrderService.svc");
           
    OrderServiceClient service = new OrderServiceClient();
            customers = service.GetCustomersByCity(cityTextBox.Text);
        }
       
    else
        {
           
    OrderHandler data = new OrderHandler();
            customers = data.GetCustomersByCity(cityTextBox.Text);
        }
        dataGrid.DataSource = customers;
    }

    The variable indicating connection state (online) can be either manual or automatic through SystemState.ConnectionsCount. Before we take a look at the OrderHandler class, here's the updated code for the "Update" menu item:

    private void updateMenuItem_Click(object sender, EventArgs e)
    {
       
    Customer customer = ((Customer[])dataGrid.DataSource)[0];
        customer.City = customer.City + "X";

       
    if(online)
        {
           
    OrderServiceClient service = new OrderServiceClient();
            service.UpdateCustomer(customer);
        }
       
    else
        {
           
    OrderHandler data = new OrderHandler();
            data.UpdateCustomer(customer);
        }
    }

    Ok, so with that in place, here's the implementation of the OrderHandler class:

    public class OrderHandler
    {
       
    public Customer[] GetCustomersByCity(string city)
        {
           
    //var q = from c in data.CustomerSet
            //        where c.City.Contains(city)
            //        select c;
            return HandlerHelper.GetObjects<Customer>(string.Format(
               
    "SELECT * FROM Customers WHERE City LIKE '%{0}%'", city));
        }

       
    public void UpdateCustomer(Customer customer)
        {
           
    HandlerHelper.UpdateObject<Customer>(customer, string.Format(
               
    "SELECT * FROM Customers WHERE CustomerID='{0}'", customer.CustomerID));
        }
    }

    Not much happening here except that the handler make use of a helper that I wrote to take care of the plumbing. I can use the entity type and I need to define the query as plain SQL, but note that I've kept the desired LINQ as a comment in preparation for the day when it can be used. Let's look at the implementation of the helper class:

    public static class HandlerHelper
    {
       
    public static T[] GetObjects<T>(string sql) where T : new()
        {
           
    List<T> objects = new List<T>();
           
    SqlCeCommand command = Common.Values.DatabaseConnection.CreateCommand();
            command.CommandText = sql;
           
    SqlCeDataReader reader = command.ExecuteReader();
           
    Type type = typeof(T);
           
    while(reader.Read())
            {
                T entity =
    new T();
               
    for(int i = 0; i < reader.FieldCount; i++)
                {
                    PropertyInfo propertyInfo = type.GetProperty(reader.GetName(i));
                    propertyInfo.SetValue(entity, reader[i],
    null);
                }
                objects.Add(entity);
            }
           
    return objects.ToArray();
        }

       
    public static void UpdateObject<T>(T entity, string sql)
        {
           
    SqlCeCommand command = Common.Values.DatabaseConnection.CreateCommand();
            command.CommandText = sql;
           
    SqlCeResultSet resultSet = command.ExecuteResultSet(ResultSetOptions.Updatable);
            resultSet.Read();
           
    Type type = typeof(T);
           
    for(int i = 0; i < resultSet.FieldCount; i++)
            {
               
    PropertyInfo propertyInfo = type.GetProperty(resultSet.GetName(i));
               
    object value = propertyInfo.GetValue(entity, null);
                if(!value.Equals(resultSet.GetValue(i)))
                    resultSet.SetValue(i, value);
            }
            resultSet.Update();
        }
    }

    The database connection kept by the singleton (Common.Values) is used to either query or update the local database. Both methods are implemented using generics, and reflection is used to find all the attributes (fields). To optimize performance, a data reader is used for the query and a resultset is used for the update. Both methods are somewhat simplified as some extra null handling is necessary but does not add to the discussion. Using reflection is not an ideal solution, but remember that my goal is to keep the implementation as simple as possible and also that this is not a solution for the future, it's a temporary fix in the lack of the right technologies on the device. When that day comes, the helper class can be scrapped, and the handler class either updated or even replaced by something like LINQ to Entities.

    In the next part, I will conclude this series.

    Be the first to rate this post

    • Currently 0/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5

    Tags: , , ,

    Architecture | Chris | Compact Framework | Windows Mobile

    KISS Architecture (part 2)

    by Chris 5. December 2008 15:55

    To continue this series that started with KISS Architecture (part 1), I will now talk more about a modern mobile multi-tier architecture. Because a picture always says more than a thousand words, let's start with a classic one.

    KISS n-tier architecture

    This image should be familiar to anyone who read the Application Architecture for .NET from back in 2002. Interestingly, the Microsoft's patterns & practices team are working on a new version of this guide called Application Architecture Guide 2.0 that is already in its second beta (there is also a specific pocket guide for mobile architectures). Building on the discussions in that guide, I have taken the old diagram (because I like the colors) and created an updated version with a small modification. The modification is related to the placing of the business entities, that I think belong in the data tier. The main reason for that is that the ORM technologies (in my case, LINQ to Entities or ADO.NET Entity Framework) take care of defining the business entities. For more details on multi-tier architectures, please read the guide, it's a great resource.

    A nice addition to the traditional diagram is to show how other systems ("External Systems") access my system's services that are published as service interfaces with WCF, and that is exactly how other systems ("Services") are accessed by my system.

    However, the biggest changes compared to my previous architecture blueprint are probably in the data tier. Even if I was a big fan of LINQ to SQL, the ADO.NET team have announced that the long-term plan is that in ".NET 4.0, LINQ to Entities will be the recommended data access solution for LINQ to relational scenarios". Therefore, I now use LINQ to Entities (ADO.NET Entity Framework) in the data tier.

    However, the changes in the data tier doesn't stop there. Another (probably even bigger) change is that the data tier is now made loosely coupled for the first time. Many attempts have been made in this direction (SQLXML to mention one) before, but I think that this time Microsoft got it right with ADO.NET Data Services. In short, it's a way of accessing data through a simple RESTful interface over HTTP using formats like ATOM and JSON.

    Even if this means that it becomes very easy to access the data source directly form the presentation tier, it doesn't mean that a sound architecture should use or even suggest such nonsense. It may be interesting and fun for quick demos, but doesn't belong in any serious enterprise solution - mobile or not. Therefore, the thinking that I introduced in A New Mobile N-tier Architecture (part 2) about keeping the data and logic as logically bound together as possible (in what I call domains) still holds. I strongly believe that the data should only be accessed through the logic.

    In the next part I will talk about the benefits of having tiers that are loosely coupled.

    Currently rated 4.0 by 2 people

    • Currently 4/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5

    Tags: , , , , , ,

    Architecture | Chris | Compact Framework | Windows Mobile

    KISS Architecture (part 1)

    by Chris 25. November 2008 15:51

    In March, when I started to create a new architecture for building mobile applications for Windows Mobile called Windows Mobile Architecture Blueprint, I thought that it would be possible to use the result for a while. I was both right and wrong. I was right about some of the theory and some of the technologies, but this fall (specifically this year's PDC) has changed a lot of things. I therefore realize that it's already time for yet another attempt to create an architecture blueprint. As last time, I will start with the server side (remember, almost no mobile applications live alone), and then work my way all the way out to the Windows Mobile client.

    As you may recall from the last attempt, I'm a big fan of the KISS principle. So big, in fact, that this time I have named the architecture after this principle. The reason is that I think it's of absolute necessity that the architecture is as simple as possible (but no simpler, as Einstein said). Otherwise it will not be used, and the whole point of thinking through and implementing an architecture is that someone will actually use it. Some of the other principles that also apply are YAGNI (don't implement it until you really need it) and DRY (learn to master the difficult art of partitioning a system).

    Here are some of the technologies and products that will be used in (or suitable for) the architecture:

    • .NET Framework - the treasure chest
    • C# - my language of choice
    • Visual Studio - the worlds greatest development tool
    • SQL Server - my database of choice (on both server and device)
    • ADO.NET Entity Framework and LINQ to Entities - the way forward on ORMs (for the ADO.NET team)
    • ADO.NET Data Services - how to make data access loosely coupled
    • WCF - on discussion, this is the RPC of our time
    • WinForms/ASP.NET - traditional ways of designing UXs
    • WPF/Silverlight - the new way of designing UXs
    • Azure/Live services - a new alternative to host data, services, and applications

    To get some theory and background to the use of some of the above mentioned technologies, I recommend you read the beginning of the last series (you find links to all the blog posts in the last post). This time, I will focus only on the technologies that changed since the last time, and therefore, as an example I will not talk much about WCF and how to access WCF services from a .NET CF application (covered in parts 3, 7, and 8 in the last series).

    Just as last time, this effort will be an open source venture hosted on CodePlex with the name KISS Architecture. This means that you can access the full source code as well as discuss it, come with suggested improvements, etc. As I walk you through the creation of the architecture, I suggest you keep the source code handy to check out more details.

    Accompanying the source code will be a series of blog posts starting with this one.

    Be the first to rate this post

    • Currently 0/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5

    Tags: , ,

    Architecture | Chris | Compact Framework | Windows Mobile

    A New Mobile N-tier Architecture (part 8)

    by Chris 31. October 2008 15:25

    We will continue the more practical part of this series by showing how the new mobile architecture looks in code, and if you want some background, please see the previous parts:

    • Part 1 was a general introduction
    • Part 2 talked about the changes in the lower tiers (logic + data, LINQ2SQL)
    • Part 3 discussed the changes in communication (WCF)
    • Part 4 covered important stuff in the user interface (MVC)
    • Part 5 summarized the theory and outlined the new architecture
    • Part 6 started the walkthrough of the architecture code by looking at the business domain
    • Part 7 continued the code walkthrough with a look at the service (WCF)

    The implemented architecture is published on CodePlex in a project called Windows Mobile Architecture Blueprint, and this means that you can access the full source code as well as discuss it, come with suggested improvements, etc. As I walk you through the creation of the architecture, we suggest you keep the source code handy to check out more details.

    We are now ready to consume the WCF service that we created in the previous post, and therefore we have added a new "Smart Device Project" and selected to create a Device application targeting Windows Mobile 6 Standard (a.k.a Smartphone) and the latest .NET Compact Framework (3.5).

    As the tools support is not yet in place in Visual Studio, to consume a WCF service, you need to first download and install the Power Toys for .NET Compact Framework 3.5. The tool that you are after is named NetCFSvcUtil.exe, and you use it like this...

    NetCFSvcUtil /language:cs http://localhost:5610/Service.svc

    ...and in the source code you can find a batch file (CreateServiceClient.bat) that will run this command (note that you may have to change the path to the NetCFSvcUtil utility depending on whether you're running on 32- or 64-bit). Note that the WCF service must be running when you run this command, and the out of running this batch file looks something like this...

    netcfsvcutl

    ...with the result that two files are generated (Service.cs and CFClientBase.cs). As there files are already part of the source code, they will simply be replaced and the procedure with running the batch file is the next best thing to what you would expect from integrated support in Visual Studio.

    Now, with these two files in place, we can start consuming the WCF service with code like this...

    ServiceClient.EndpointAddress = new EndpointAddress("http://192.168.0.100:5610/Service.svc/basic");
    ServiceClient service = new ServiceClient();
    Category[] categories = service.GetCategories();

    ...and the first thing we do is to set an endpoint of the service that the mobile device can reach (in this case an IP address). Then the service proxy (ServiceClient) is instantiated and used to retrieve the list of categories. Note that the business entity (Category) that was declared back in the business domain (automatically generated by LINQ2SQL, and automatically serialized by WCF) is readily available on the mobile client (thanks to the proxy we generated above).

    In future posts, we will cover more parts of the architecture blueprint implementation.

    In some projects, we have used a very simple and straightforward implementation by our former fellow MVP, Alex Yakhnin (he's now employed by Microsoft), that he published as a small blog series last fall (see part 1 and part 2).

    Currently rated 5.0 by 1 people

    • Currently 5/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5

    Tags: , , ,

    Architecture | Chris | Compact Framework | Windows Mobile

    A New Mobile N-tier Architecture (part 6)

    by Chris 17. October 2008 15:14

    In this part, I will get more practical by showing how the first parts of this new mobile architecture looks in code, and if you want some background, please see the previous parts:

    • Part 1 was a general introduction
    • Part 2 talked about the changes in the lower tiers (logic + data, LINQ2SQL)
    • Part 3 discussed the changes in communication (WCF)
    • Part 4 covered important stuff in the user interface (MVC)
    • Part 5 summarized the theory and outlined the new architecture

    The implemented architecture is published on CodePlex in a project called Windows Mobile Architecture Blueprint, and this means that you can access the full source code as well as discuss it, come with suggested improvements, etc. As I walk you through the creation of the architecture, I suggest you keep the source code handy to check out more details.

    nwdatacontext Ok, let's start building the architecture from the ground up!  To make things really simple (remember the KISS principle), I have started with a plain class library called Blueprint.Domain where I will keep my business domains. My first domain will be covering a small part of the classic Northwind database. I started by creating a LINQ2SQL data context called Northwind and dragged two of the Northwind tables into it (if you're like me, and don't have the Northwind database installed, you can get it here) as you can see on the right (note that I have removed the Picture field in the Category table to save bandwidth).

    When that is done, a neat trick that will come in very handy is to select Properties on the design canvas of the data context and set Serialization Mode to Unidirectional. By doing this simple task, the code generated for the data context will include the necessary decorations (attributes) to make the data context ready to be published by WCF. If we look at a stripped version of the generated code (in Northwind.designer.cs)...

    public partial class NorthwindDataContext : System.Data.Linq.DataContext
    {
        [DataContract()]
        public partial class Category
        {
            [DataMember(Order=1)]
           
    public int CategoryID
            {

    ...you will see that each class (entity) has a DataContract attribute, and each field (attribute) has a DataMember attribute. These attributes will be use by WCF when the entities are communicated.

    In the code above, please also note that the generated class for the data context (NorthwindDataContext) is declared "partial" which perfectly matches our intention of implementing the business logic in a parallel class. By creating such a class (Northwind.cs), and putting in some simple code like this...

    public partial class NorthwindDataContext
    {
       
    public Category[] GetCategories()
        {
            return Categories.ToArray();
        }
    }

    ...we have implemented the first (however sparse) service into our first business domain, and the functionality is that it returns the list of all categories. Note that behind the scenes, LINQ comes into play, and to show a more obvious example, we can do this instead...

    var q = from c in Categories select c;
    return q.ToArray();

    ...and this will create the same result as the code above. Worth mentioning already is the fact that even if the Category entity holds a relation to all products in that category, those child entities are not loaded by default. This is a good thing as you probably don't want to load all products with all categories, but when you want to load related entities, you can do this by explicitly call...

    var q = from c in Categories select c;
    Category[] categories = q.ToArray();
    categories[0].Products.Load();

    ...to load all the products for the first category. There are some other options for controlling how related entities are loaded, but it's out-of-scope for this blog post. In future posts in this series, I will cover more parts of the architecture blueprint implementation.

    Be the first to rate this post

    • Currently 0/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5

    Tags: , , , ,

    Architecture | Chris | Compact Framework | Windows Mobile

    A New Mobile N-tier Architecture (part 5)

    by Chris 10. October 2008 15:08

    In the previous parts of this series, I have discussed the changes that affect the architecture design. It's now time to conclude what this all leads up to architecture-wise, and I propose that the architecture should look something like this:

    newarch Most of the fundamental parts (three tiers, common services, etc), and even many of the more specific (service interfaces/agents, data access, business entities, etc) are exactly the same as in the Application Architecture for .NET that I've mentioned before in this series of blog posts.

    Note that a significant change is the merge of the lower part of the middle (business services) tier and the bottom (data services) tier. As I've outlined before, this is where the business logic and its data comes together in a nice mix called the business domains. With technologies like LINQ to SQL and WCF, most (if not all) of the data services tier are actually created using code generation. This means that any changes made to the different sources (data sources and services) can be captured by regenerating the code. The tools support is actually prepared for this kind of evolution in the integration between systems, and a simple "Update Service Reference" menu selection is all that is needed.

    Another similar change is the clear separation between the service interfaces and the business domains. Where the business domains have a clear responsibility to handle the logic and data for a certain business domain, the service interfaces (designed according to the facade pattern) has a different set of responsibilities. The primary distinction of a service interface is that it probably fulfills a specific part of the system's functionality (use case). Also, as they are the "first line of defense", they should handle things like basic security (authentication, authorization, encryption, etc) as well as secure coding techniques (parameter checking, prevent things like SQL/code injection, etc), compression, transactions, logging, etc. A consequence of the separation with the business domains is that the service can be placed in a separate assembly. This is a good thing because a service interface probably uses a number of business domains that may (or may not) exist in numerous assemblies.

    Finally, the user interface parts have been renamed to align with the use of the MVC pattern, and as already mentioned in previous posts, this will allow for better testing and the use of the same user interface logic for different clients (thin Web interfaces built with ASP.NET, rich interfaces built with WinForms, WPF or Silverlight, and of course mobile clients built with .NET CF and soon Silverlight, etc).

    In upcoming posts, I will continue with more of my thoughts on the changes in mobile architecture, and of course also some code samples to show the theory in practice. Stay tuned!

    Currently rated 4.0 by 1 people

    • Currently 4/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5

    Tags: , , , ,

    Architecture | Chris | Compact Framework | Windows Mobile

    A New Mobile N-tier Architecture (part 2)

    by Chris 22. August 2008 14:59

    To continue this series that started with A New Mobile N-tier Architecture (part 1), I will talk more about the changes in a modern mobile multi-tier architecture.  We can see that the most important changes are happening on two levels, and the first is the tighter bond between the business logic and it's data.

    classicntierBefore, we had a distinct separation in the two lower tiers between the logic and the data. The thinking was that the data services could be used by several parts of the business logic to handle basic CRUD operations. This is shown in the Application Architecture for .NET from 2002 that you see on the left where the business logic and the data access was divided into the lower two of the classic three tiers. However, the problem was that data without logic is almost useless, and even if the logic existed (in various business components) the natural relation with the data was not manifested.

    The other change is the change in the way that clients exchange information with the server (or more general, the way that two systems or peers exchange information), and that will be the focus of the next part in this series.

    newntier

    If we look at technologies like LINQ and specifically LINQ2SQL (LINQ to SQL) the traditional separation between the logic and the data is encouraged. On the right you find an illustration what is happening in the lower two of the traditional three tiers. The observant note that the business entities is moving down to he data tier (where they belong), but more importantly, the two tiers are actually moving together. With a LINQ2SQL, the business logic can be implemented in the same data context (the ORM) class (by using the ability to define partial classes). I would like to call these merged entities domain components as they define and handle both the data and the logic for a specific business domain. So, the service interface (facade) would actually work with a number of domain components to deliver functionality to its clients. The challenge is how the functionality (logic + data) is spread among the domains to make them a perfect tradeoff between versatility and reusability. The bigger, the more versatile, the smaller, the more reusable. The general message is probably to keep them small and distinct.

    In upcoming posts, I will continue with more of my thoughts on the changes in mobile architecture, and of course also some code samples to show the theory in practice.

    Currently rated 5.0 by 1 people

    • Currently 5/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5

    Tags: , , ,

    Architecture | Chris | Compact Framework | Windows Mobile

    A New Mobile N-tier Architecture (part 1)

    by Chris 13. August 2008 14:56

    When we wrote our book Pocket PC Development in the Enterprise back in 2001, one of our goals was to help developers with an architectural blueprint for building solid mobile multi-tier applications. At that time, most focus for mobile developers was on the user interface and the device side of the mobile solution.

    Since then, a lot of things have changed. The Windows Mobile development platform with .NET Compact Framework as the foundation, has evolved into a very powerful offering to mobile developers. Technologies has constantly migrated from the desktop (full) framework, even if it sometimes seems too slow when one is eagerly waiting. Who else is eager to use LINQ to SQL with SQL Server Compact, full WCF support, or build mobile Silverlight applications?

    But, some things remain the same, and one of these is the view on mobile solutions as being a part of a bigger whole. Almost no mobile applications live alone! In most cases, they are part of an integrated solution that extend existing business processes to reach further out in the hands of the employees. Therefore, a modern mobile architecture starts with a solid architecture on the server, and can be extended to support multiple channels (thin/rich clients, fixed/mobile devices, etc).

    During the years since we wrote the book, the blueprint has evolved with the changes in technology. I say evolve, because most changes only meant that the architecture was upgraded to embrace the new technologies. Recently, however, some major changes has occurred that force some more drastic changes to the architecture. The most significant are LINQ (specifically LINQ to SQL and the upcoming ADO.NET Entity Framework), WCF, and Silverlight. The observant reader notes that these technologies span the whole architecture spectrum from data access, via communcation links to UX. In addition to these, there are also a number of enhancements for the mobile developer that spice up an architecture that in addition to support traditional clients, it also needs to support mobile clients as well.

    As you will see, when we move forward in this series of blog posts, I'm a big fan of the KISS principle. Therefore, the primary goal is to keep things as simple as possible to minimize the learning curve while at the same time still create a valid architecture that is easy to implement, test, and maintain.

    In upcoming posts, I will continue with more of my thoughts on the changes in architecture in general and more specifically on architectures that suite mobile solutions.

    Currently rated 5.0 by 2 people

    • Currently 5/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5

    Tags: , , , ,

    Architecture | Chris | Compact Framework | Windows Mobile

    Powered by BlogEngine.NET 1.4.5.0
    Theme by Mads Kristensen