Android Development – Architecture (MVVM or MVP)




/* Style Definitions */
{mso-style-name:”Table Normal”;
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-bidi-font-family:”Times New Roman”;

Some Background

Most of my experience has been doing .net development. For the last few years I have done client development: WPF, Silverlight, and Windows Forms. Prior to that I was doing mostly development.

I recently started getting my feet wet in Android development and one of the first steps in any platform is to get comfortable with the parts of the applications and how they talk to each other.

Android is new to me so I will define some terms to start off with.


Activities: application component that provides a screen with which users can interact in order to do something.

Layout:  A layout is the architecture for the User Interface. Either defined by XML or in Code.

Intents: Messaging object that can be used inside of an application or from application to application.

The Xml layouts allows for methods to be implicitly wired to methods in the  Activity that loaded the resource.  Similar to Commanding in XAML.

How do you classify an Activity in terms of UI patterns?
Is it a Controller, View, Model, ViewModel, Presenter, does it fall outside of a UI Pattern, or is it a combination of many?

Is it a Controller?
In an MVC application you have a request come in and the controller handles the routing. It is pretty clear example of a controller.  It is entirely possible that you could write the app in a way that when an Activity is called it determines the view, but this seems like a stretch. I would see the relationship between an Activity and a View to be One-to-One.

In this case I would see the OS being the Controller.

So in my opinion it is not a Controller.

Is it a View?

Since you can create UI’s in an Activity using code, you could have a situation where it acts like a view, but you would lose the separation of concerns gained by using XML.


Is it a Presenter or a ViewModel?

If you consider the notification and management of the listadapter as Binding then it would be a ViewModel

ArrayAdapter<Customer> adapter = new ArrayAdapter<Customer>(this,android.R.layout.simple_list_item_1,customers);



If you don’t consider this a form of binding then it is probably more of a presenter.

In my opinion it feels more like MVVM but then my background in WPF could be skewing my opinion.


MVVM vs. MVP vs. MVC

F# Baby Steps – Fibonacci


F# is the kind of language that can really energize someone who is excited about just sitting down and powering out a solution.

Here is an example of how to sum some fibonacci numbers.


let rec fibonacci n = 

    if n < 2 then 1 

    else fibonacci (n-2) + fibonacci(n-1)


//create a recursive function called fibonacci

//that takes the parameter n 

// if n < 2 then 1  so this is the base case.

//else fib (n – 2) + fib (n – 1)


printfn "fibonacci = %A" (fibonacci 10)

Silverlight and Windows Mobile 7

Looks like Silverlight will be available on Windows Mobile 7

Excerpt from

The above document confirms both Silverlight and XNA development.  Silverlight is interesting, as we know it will not be present in the browser yet. XNA is however more interesting, as it is the same language used to program the ZuneHD and more importantly X-Box Live games, suggesting cross compatibility between the 3 platforms.

Adding properties to the App Class

If you want to add properties to your App class (App : Application) and actually access them in your application.

Make sure to override Current to return an App instead of an Application.


        public static new App Current
                return Application.Current as App;



Finding a place for WCF RIA in existing applications

Works with Entity Framework 4.0 CTP 2

My application so far …

The premise of this application is to create a way for one or more people to create a common practice routine, set goals, and compare their progress.

I started this application with the intention of using Entity Framework 4 and RIA.

I started having problem with inserting from the server side, so I decided to start with a more basic model, and work my way into RIA and EF.

My data model looks like this


I started with the problem of how do I save disconnected entities across a service boundary.

I found that converting to Self Tracking Entities solved this problem very elegantly.

Problem Number 2
Option 1(The hard way)

I want the entire object graph on the client side, and I would like to be able dynamically generate a graph using a collection of Task Items.

I could do this by creating a silvlerlight class library sharing the objects(once they are converted to POCO’s) and using linking to share the objects between layers.

I would then have to build up the structure on the client side, using a series of async loads.

This is a lot of work. I have done it before, and every time I do it, I feel like I just wasted time I will never get back.

Option 2 – Use RIA and POCO.

I know that RIA sits in between the Server and the Client


(Shamelessly stolen from Brad Abrahams excellent RIA Services video)

So how do I add RIA to this project?


Setting up your POCO entities

I have an entity class for Tasks

namespace PracticeManager.Common.Entities
    public class Task
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual DateTime CreatedTime { get; set; }
        public virtual DateTime ModifiedTime { get; set; }
        public virtual string Status { get; set; }
        public virtual string MeasurementUnit { get; set; }
        public virtual string UserName { get; set; }
        public virtual int? CommentId { get; set; }

        public ICollection<TaskItem> TaskItems { get; set; }
        public ICollection<Goal> Goals { get; set; }
        public Comment Comment { get; set; }
        public ICollection<Taunt> Taunts { get; set; }
        public ICollection<Challenge> Challenges { get; set; }
        public ICollection<Challenge> Challenges_1 { get; set; }


I have my context class.

namespace PracticeManager.Server.Business.DataContext
    public class TaskDataContext : ObjectContext
        private ObjectSet<Task> _tasks;

        public TaskDataContext(string connectionString)
            : base(connectionString, "PracticeModelContainer")

        public ObjectSet<Task> Tasks
                return _tasks ?? (_tasks = base.CreateObjectSet<Task>());




This covers the data loading portion.

Hooking up RIA Services

In your Web Project add a Domain Service class.

A wizard will appear, I avoided the wizard. I want to do this programmatically.


My domain class is pretty simple, for now I just want a list of tasks.

public class PracticeManagerDomainService : DomainService
    private TaskDataContext taskContext;

    public IEnumerable<Task> GetTasks()
        var cnxString = ConfigurationManager.ConnectionStrings["PracticeModelContainer"].ConnectionString;
        taskContext = new TaskDataContext(cnxString);
        var tasks = taskContext.Tasks;

        return tasks;


This is far from pretty, I need to move my connection string out of the method, but this will work.

On the client side

In my code behind I have two methods.

public void LoadTasks()
    EntityQuery<Task> taskQuery = _practiceManagerDomainContext.GetTasksQuery();
    _practiceManagerDomainContext.Load(taskQuery, this.OnTasksLoaded, null);

private void OnTasksLoaded(LoadOperation<Task> loadOperation)
    nameComboBox.ItemsSource = _practiceManagerDomainContext.Tasks;

This takes care of the async load and connecting to the service.

The Task object comes across because of its exposure in the domain service class.

The namespace is even the same as the server side, which indicates it is the same object. Not just a service proxy.

Once I call the LoadTasks method, I will get a dropdown populated with tasks.

That is all I need to do.

Using Self Tracking Entities in Entity Framework 4 to fix the error – The object could not be added or attached …

Works with Entity Framework 4 CTP 2 and Visual Studio 2010 Beta 2

{"The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object."}

I am able to to insert the first record.

But subsequent records give the above error.

The structure is: Tasks have Task Items. I am trying to save task items.

 In this example my silverlight application is initiating this service call.
The task object is set by a dropdown on the client  side.


        public void InsertTaskItem(Task task, string value, DateTime dateTime)
            TaskItem taskItem = new TaskItem();

            taskItem.Task = task;
            taskItem.TaskId = task.Id;
            taskItem.Value = value;
            taskItem.OccurrenceTime = dateTime;

            taskItem.CreatedTime = DateTime.Now;
            taskItem.ModifiedTime = DateTime.Now;


First Attempt Lets just atttach the object, it should be that easy right?

        public void InsertTaskItem(Task task, string value, DateTime dateTime)
            TaskItem taskItem = new TaskItem();

            taskItem.Task = task;
            taskItem.TaskId = task.Id;
            taskItem.Value = value;
            taskItem.OccurrenceTime = dateTime;

            taskItem.CreatedTime = DateTime.Now;
            taskItem.ModifiedTime = DateTime.Now;

            objectContext.AttachTo("PracticeManager.Server.Business.Data.PracticeModelContainer.TaskItem", taskItem);


I received the error.

The provided EntitySet name must be qualified by the EntityContainer name, such as 'EntityContainerName.EntitySetName', or the DefaultContainerName property must be set for the ObjectContext.
Parameter name: entitySetName

I tried both the fully qualified type name, and the entity set name.

Since I am using .Net 4.0 and the Entity Framework,  I realized I can use some of the POCO functionality they added to facilitate this specific scenario.

I can refactor and use Self Tracking Entities to accomplish my goal the right way.

The first step is download the Entity Framework 4 CTP 2  – It did not make it into VS 2010 Beta 2.

Navigate to your model, and Add New Code Generation Item.

Select ADO.NET Self Tracking Entity Generator.

        public void InsertTaskItem(Task task, string value, DateTime dateTime)
            TaskItem taskItem = new TaskItem();

            taskItem.Task = task;
            taskItem.TaskId = task.Id;
            taskItem.Value = value;
            taskItem.OccurrenceTime = dateTime;

            taskItem.CreatedTime = DateTime.Now;
            taskItem.ModifiedTime = DateTime.Now;

            using (var context = new PracticeModelContainer())

Once I added the context save changes, the task item now save.

One problem is when setting the task property it is triggering the creation of a new entity, and then overwriting the foreign key with the key of the newly created task.

Once the line

taskItem.Task = task;

is commented out the save works as expected.

WCF RIA and Server and Client Side Authentication

Works with Silverlight 4.0 beta 1, Visual Studio 2010, and the Silverlight Business Application Template

In WCF Ria you can decorate your service methods with the

[RequiresAuthentication] attribute to denote the user must be authenticated.

This comes from the System.Web.DomainServices namespace.

This same functionality is not available on the client side.

One method is to pop the login form when a user navigates to a restricted page.

I am not using roles, but you could just as easily use IsInRole(string role) instead.

        protected override void OnNavigatedTo(NavigationEventArgs e)
            LoginUI.LoginRegistrationWindow loginWindow = new LoginUI.LoginRegistrationWindow();

            if (!WebContext.Current.User.IsAuthenticated)


The user can still see that the page exists.

In order to hide the page you can use the events from WebContext.Current.Authentication

        public MainPage()
            this.loginContainer.Child = new LoginStatus();

            WebContext.Current.Authentication.LoggedIn += new System.EventHandler(Authentication_LoggedIn);
            WebContext.Current.Authentication.LoggedOut += new System.EventHandler(Authentication_LoggedOut);


        void Authentication_LoggedOut(object sender, System.Windows.Ria.ApplicationServices.AuthenticationEventArgs e)

        void Authentication_LoggedIn(object sender, System.Windows.Ria.ApplicationServices.AuthenticationEventArgs e)

        private void ManageMenu()
            if (!WebContext.Current.User.IsAuthenticated)
                dashboardDivider.Visibility = System.Windows.Visibility.Collapsed;
                dashboardLink.Visibility = System.Windows.Visibility.Collapsed;
                dashboardDivider.Visibility = System.Windows.Visibility.Visible;
                dashboardLink.Visibility = System.Windows.Visibility.Visible;


WCF Ria Authentication and SqlMembershipProvider


Getting the Authentication working is a snap, if you remember how to specify the connection string for the SqlMembershipProvider.


I had forgotten.

So it was back to 2.0 even though I have an Application built with Silverlight 4.0.

Since WCF RIA Authentication uses the membership provider, and now the web.config is greatly simplified.

The default membership stuff is not in there anymore.


If you are using the SqlMembershipProvider don't forget to add the provider configuration in your web.config.

After you run aspnet_regsql of courseJ


<add name="PracticeModelUsers" type="System.Web.Security.SqlRoleProvider, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" applicationName="PracticeManager" connectionStringName="PracticeModel" />



<membership defaultProvider="PracticeManagerUserProvider">


<add name="PracticeManagerUserProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" applicationName="PracticeManager" connectionStringName="PracticeModel" enablePasswordReset="false" enablePasswordRetrieval="false" passwordFormat="Clear" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" />





<add name="FriendlyName" />



<add name="PracticeProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" applicationName="Practice Manager" connectionStringName="PracticeModel" />



Entity Framework and Sql Server Database Projects

Entity Framework 4 adds a bunch of new features this time around.
One of which is to push model changes back to the database.

If you are using one of the Database projects included in the Database Edition you may wonder how you are going to bridge the gap between the two projects.

Unfortunately there is no good way to do this.
Right now MS is prescribing to generate alter scripts from the EDMX model and add as a script to the database project.

Acceptance Test Engineering Guidance

The Patterns and Practices team at Microsoft has just released a guide to engineering acceptance tests.

  • Some things that are covered.
  • How to Plan for Acceptance Testing
  • What Kinds of Acceptance Tests to Run
  • How to Create and Run Acceptance Tests
  • Defining What “Done” Means
  • How to Justify Your Approach

It is book both for someone creating a testing plan, and the person actually writing the tests.

Get it now