
I've given up on my old Windows Mobile phone and been looking around for a replacement. Now let me be clear, I can't have an iPhone because AT&T is clearly evil. So I decided to take the plunge on an Android phone. I've looked at a couple of the phones, but since I am on Verizon I grabbed the Motorola Droid. Its not bad for $199.
I don't intend to simply put some magic number rating of the phone, but I have some overall observations:
The Good
- The overall initial experience is excellent. I was wow'd from the minute I got the phone.
- I didn't read the manual (though I am not sure it would have helped), but the act of discovery worked really well. I had to get used to how the context menu and the back button worked (and no 'ok' buttons).
- The browser (though not tabbed) is excellent.
- Making phone calls is just great. No more worry about touching my ear to the phone and dialing just works the way I expected it to.
- Taking photos and videos are great. The phone has a better resolution than my point-n-shoot (though I am not sure it takes better pictures).
- I have been impressed by many of the Marketplace's apps. Though I am told not as slick as iPhone apps, I am very happy with most of the apps.
- The Marketplace's reviews and screenshots help a lot to find apps worth getting and their 24 hour return policy is nice. (Ahem...you listening Steam?)
- The GPS and Tower Location work great. It even worked inside my house.
- Google maps and turn by turn directions work well.
- Lots of apps I liked like TripIt, Seismic for Android, Evernote, Fish2Go, gStrings, Guitar Hero, Qik, Pandora, Shazam, YouTube and Steamy Window.
The Bad
- No integration with ActiveSync/Outlook at all. I found a great Sync2 app that would sync my contacts, but I still haven't had any luck syncing my calendar. And there is no sync of tasks whatsoever. I am told that the sync with Exchange is a lot better (I use Outlook but not Exchange). You kinda have to buy into the Google-verse to use the phone IMHO.
- The marketplace has issues. I initially could not download anything for about 1/2 day. I spent most of that time assuming it was my fault. Buying apps was even more painful as my google accounts are Google for Domains accounts. Through trial and error I found out that buying apps didn't work because I didn't have a gmail account. Once that was added, it just worked.
- The phone is very google-fied. You have to have a google account (e.g. gmail) for many of the features.
- No Flash, no Silverlight.
Mixed Bag
- Apps must be installed into internal memory (I think 256MB free), but has a 16GB SD card (upgradable) for other storage like pics.
- Like Windows Mobile, there are apps that run well on some phones and badly on others. You have to read the fine-print to see if the Droid is ok with an app (though Droid is one of the good ones most of the time).
Conclusion?
Since I just got the phone its hard to settle on a real conclusion. After a month with the phone I will have a better idea. Many of the location-aware functionality will either do well or badly in the coming weeks. I am hoping to really put the phone through its paces at the MVP Summit and at MIX. I'll let you know what I think after that.
I am going to be writing a book on Silverlight Architecture. I'd like to get my readers/followers to help me figure out what is most important to write about. Please take the following survey if you don't mind:
http://www.survsoft.com/esurv.php?s=27432&k=12845-0-28970

Since I am never at home anyway, I figured it would make sense to more conferences this year. I love doing talks at these conferences and getting the hard questions from attendees. If you're at any of these events, don't be shy about coming up and saying hi. I'll be at a number of events talking my favorite topics: Silverlight and Data!
Here are the upcoming events:
MIX10
March 15-17, 2010 - Las Vegas, NV
The Designer/Developer/Web conference put on by Microsoft. Always a good time! I will be presenting two talks this year:
- Securing Silverlight
- Debugging Silverlight
(Note that due to overlap between my MVVM Talk and Nikhil Kothari's MVVM talk, I have agreed to switch my talk to one on Silverlight Security).
TechDays Sweden
March 22-23, 2010 - Örebro, Sweden
No, I don't know swedish but I am looking forward to seeing my Svensk fans. Its a great conference with great speakers. I'll be doing one talk at the event:
DevConnections
April 12-14, 2010 - Las Vegas, NV
This is the event where Visual Studio 2010 will be launched. I will be doing a number of talks at this event:
- Building Behaviors for Silverlight 4
- Ninja Data Binding
- Validating Data in Silverlight
- Will It Blend?
The way that events are handled in Silverlight occassionally surprises people. For the uninitiated there are two types of events in Silverlight, direct and routed. Essentially direct events are events that one one type of element can fire and do not support any type of bubbling. The MediaEnded event on the MediaElement is a good example of this. The other type of event is a routed event. In this type of event, the event is bubbled through the visual tree. In Silverlight, the way it works is exactly the opposite of what you might expect from Win32 programming (e.g. WinForms, VB6, MFC, etc.) Routed event bubble from the most deeply nested element to the shallowest element. For example, when a MouseLeftButtonUp event is fired (mouse and keyboard events are routed events), the item directly under the mouse gets the event first, then its parent and so on:
Any control along the way can tell the routed event that it is handled which stops the bubbling from happening. While this is generally good practice (so everyone doesn't need to know about something if someone has done something about it). Many of the standard controls handle events that they need. For example, the Button class handles the MouseLeftButtonUp routed event. But what happens when you want to be notified even if it has been handled? Luckily there is a way.
The trick is to use the AddHandler method on UIElement. For example, consider this XAML:
<StackPanel x:Name="LayoutRoot"
Background="White">
<Button Height="25"
Width="100"
Content="Click Me!"
x:Name="clickButton"/>
<Button Height="25"
Width="100"
Content="AddHandler"
x:Name="addButton" />
</StackPanel>
When we handle the MouseLeftButtonUp event on the LayoutRoot, we can click on the clickButton and the event never fires. But if we click outside the button, it works. To be able to handle 'handled' events, you have to use the UIElement.AddHandler method. This method takes a routed event, a delegate of the correct type and an optional argument to specify whether the handler should be called for 'handled' events:
LayoutRoot.AddHandler(
// Must be a RoutedEvent
UIElement.MouseLeftButtonUpEvent,
// Specify the right Handler
new MouseButtonEventHandler((o, args) =>
{
MessageBox.Show("Worked even though it was handled!");
}),
// Respond to "Handled" events
true);
Once the AddHandler is added, the click on the button will also call the MouseLeftButtonUp event specified in AddHandler. Grab the code and take a look yourself! (NOTE: This is a SL4/VS2010 example but the same code would work in Silverlight 3)
http://wildermuth.com/downloads/HandledWithCare.zip
For those of you who have been living in the world of WPF, this post will be old-hat, but for the purely Silverlight folks I am hoping to help you change the way you add functionality to your applications. To do this, I will use Silverlight 4's new support for Commands.
Commands are a way to data bind to specific operations in your application. A command is any class that supports the ICommand interface. The ICommand interface supports three pieces of functionality:
public interface ICommand
{
void Execute(object parameter);
bool CanExecute(object parameter);
event EventHandler CanExecuteChanged;
}
First and foremost, the interface supports an execute method that supports the actual operation that you want to execute. The next piece of functionality is a test to see if the command is valid. Lastly, the command supports an event handler so that the command can notify users that the command needs to be re-evaluated to be sure the "CanExecute" is still valid.
The basic idea here is that if you expose commands and use data binding to attach them to your user interface (XAML). This avoid the normal procedure of writing button click handlers and figuring out how to execute some piece of functionality. In addition, the command can tell the controls whether the command is valid at a central point in time (this means no more messing with IsEnabled).
In Silverlight 4, ButtonBase (and all its derived versions) and HyperlinkButton now support Command and CommandParameter to tie ICommand implementations. For example, in XAML I can tie two different buttons to the SaveCommand that I have on some object i've bound to my UI:
<Border BorderBrush="LightGray"
BorderThickness="1">
<StackPanel Orientation="Horizontal">
<TextBlock>Tools:</TextBlock>
<Button Command="{Binding SaveCommand}"
CommandParameter="{Binding Person}"
Content="Save" />
</StackPanel>
</Border>
<StackPanel Grid.Row="1">
<TextBlock FontWeight="Bold"
Text="Person" />
<TextBlock Text="Name" />
<TextBox Text="{Binding Person.Name, Mode=TwoWay}" />
<TextBlock Text="Occupation" />
<TextBox Text="{Binding Person.Occupation, Mode=TwoWay}" />
<Button Command="{Binding SaveCommand}"
CommandParameter="{Binding Person}"
Width="100"
HorizontalAlignment="Right"
Content="Save" />
</StackPanel>
By binding a SaveCommand to both of these buttons, whenever either of the buttons is pressed, the command will be executed. But perhaps even more important is that as the command isn't valid (perhaps when the Person doesn't have changes), the buttons will be disabled.
To implement the command, I used Laurent Bugnion's MVVM Light framework. He exposes a simple way to create commands with the RelayCommand<T> class. When you create a RelayCommand<T> you simply specify lambda's for the Execute and optionally the CanExecute. For example creating the SaveCommand is as simple as:
// Command for Saving
SaveCommand = new RelayCommand<Person>(p =>
{
// Just accept the changes
// (though we'd really save the changes)
p.AcceptChanges();
// Cause the command to be reevaluated.
SaveCommand.RaiseCanExecuteChanged();
},
p => p != null && p.HasChanges);
The first lambda represents the code that will run when the command is executed. The second lambda represents the code that is executed (returning a Boolean) to indicate whether the command is valid. That means that if the person we're using in the command is either not null and has changes to save, then the buttons that this command is attached to should be valid. When the command is data bound, it evaluates the "CanExcute" lambda but to make this work the way we want, we'll need to cause that to be re-evaluated as necessary. This is done with the RelayCommand<T>'s RaiseCanExecuteChanged. This means that as our object is modified, we can simply re-evaluate the command's CanExecute. Since the Person class implements INotifyPropertyChanged, I can use that behavior to test for CanExecute:
// If the person changes,
// recheck the CanExecute part of the command
Person.PropertyChanged +=
(s, e) => SaveCommand.RaiseCanExecuteChanged();
Go grab the code and play with it. I think you will be compelled to use this in your next Silverlight application!
http://wildermuth.com/downloads/funwithcommanding.zip

I am happy to announce that one of my entries in the MIX 10's Open Call for content was selected by the community to be delivered at the event. The entry that was choosen is:
"RIA Services and MVVM: It Can Happen!"
In this session I'll be showing how to architect a Silverlight application using RIA Services. If you're planning on building with RIA Services, stop by and see how I think it should be done.
Are you coming?

I like to write blog posts where I offer some pragmatic advice. In most posts I try to include tons of code samples and example projects...but this post is different. I am trying to get my head around something so I want to share what is in my head so I can get a conversation started with my readers to help me out. Once you read this post, please comment...
The other day I was responding to a tweet from Doug Purdy. He had posted a link to some new EF 4.0 features by the boss at Microsoft's DevDiv. I, as usual, complained instead of lauded the list. I started a conversation about lazy loading and the potential danger of it, but quickly Doug mentioned that ORM's maybe were the wrong approach in general. That got me thinking (not always a good idea).
Those of you who have followed me for a long time are apt to remember that I go back to ADO (actually even farther back) to a time when writing your own data access layer was the norm. And using that data access layer against your business objects was what we all did.
Things are really different today as most of us now use an Object Relational Mapper (ORM) of one sort or another. Entity Framework, LINQ to SQL, nHibernate, LLBGenPro, etc. They all essentially do the same thing (but in very different ways). The problem is that to some it feels like ORMs are business objects. In fact, ORMs are just data access. Are they making our jobs easier? It depends...
Most ORMs lean heavily on code generation to create entities and other code. The mapping is generally trying to take some relational model and create an object oriented model. It works this way because this is what we've done for a couple of decades. But is it helpful? Perhaps not. But because we build class-based (or object oriented) software today that seems plausable to do.
Object orientation is at a cross-roads in many ways. We've been told for a couple of decades now that it is the way that you can benefit from reuse, ease of development and modeling. Of course, like all magic pills, applying it to every problem space doesn't help. In the case of ORM's, its always felt like we were putting a round peg into a square box.
Don't get me wrong, mapping a rectagular result (e.g. SELECT * FROM Foo) makes a lot of sense. But the problem is that the mapping happens between *related* entities which is hard. Relationships in data stores are not as simple as 1..n, 1..1, or 0..1. By shaping the relational model into a class structure, we're losing fidelity. You can see if you're losing fidelity when an ORM is going to allow you to get deep inside to hint at the actual queries. At that point we're fighting the tools.
I am not anti-ORM at all and I can clearly see how ORMs help build smaller projects easier. This is especially true if your relational model looks like the object model (or as is common in DDD, using the class model to push down the schema). Great if you're building small projects, but when those same techniques are used on large or enterprise solutions, the stack gets big fast (see right). The problem is that we end up with in-memory classes that represent entities, then we need business objects that apply business rules, then DTOs to communicate the shape of hte data across the wire and in some cases data contract classes outside the firewall. Under the ORM entity objects, the ADO.NET managed providers still exist and sometimes an unmanaged stack too. Sometimes that a lot of code to worry about.
My big worry here is that ORMs are seductive. When you start a project and build a data layer with a couple of clicks you can focus on building the benefit to the business. Like most development issues, the real cost is in the maintenance. I fear that much of the work in this space is done by consultants because typically consultants help get a solution built and move on. Its not that consultants are bad, but because they can go from greenfield to greenfield project (I certainly have been guilty of this before), the pain of maintaining this code isn't always obvious. What happens when the database is overwhelmed with data. What happens when you try to add indexing to an existing application as the use cases change and mean that adding index hints is hard (though in SQL Server 2008 you can do this without modifying the calls).
That comes back to Doug Purdy and other folks in the twitterverse. What's the next wave of solutions out there? I admittedly haven't spent enough time playing with solutions like ActiveRecord, but they feel like dynamic classes which doesn't feel like it will solve the problem. I have heard that maybe getting away from relational databases is the solution, but the object database/non-SQL/BigTable solutions I've seen never seem to scale to high transaction systems or work well with reporting.
Your turn...what's your take?

If you would like to hear me blather on at MIX about how to create Silverlight applications, feel free to go visit the MIX site and vote for my sessions. I submitted seven talks so feel free to pick your favorites. You'll have the opportunity to vote for five of your favorite sessions. Remember, even if you don't think you can go, these are the sessions that will be recorded and available after MIX...so everyone gets a chance to vote!
You can see my sessions by visiting:
http://visitmix.com/opencallvote/?query=Shawn%20Wildermuth

I just found out that in Silverlight 4, the fonts are no longer whitelisted to the ten fonts out of the box. Silverlight will now use any font that it can find on a machine without embedding. For example, in my RIA Services sample, I changed the font to Elysian (a font I have installed) and it picked it up:

I am told that soon you'll be able to iterate through the fonts to allow users to pick fonts, but it doesn't look like its included yet.
Wow...

Welcome the part 4 of my three-part series on architecting with RIA Services. In the last part of the series, I thought I was done with the example and some of my readers challenged me to help them understand how to handle Add/Delete scenarios. Since I was at it, I figured I should show paging and IsDirty scenarios as well, I decided to make a part four.
Remember this example is based on my current thoughts, its not dogma. I will change my mind at times and learn from the community (as has even happened during this series). Hopefully this example can help you think about how the patterns match your current business problems. No tithe, no sermon, no damnation....I promise ;)
Supporting IsDirty
To be able to support some functionality (like using it in some Commands' CanExecute call), I wanted to test the model for whether it had saveable entities. My first try was to ask the RIA Services' context HasChanges property:
public bool HasChanges
{
get { return Context.HasChanges; }
}
This works *but* the problem is that this property tests to see if the context has any changes. Why does this matter? I realized that as I made additional queries that the context was holding on to every object I retrieved. This means that if I changed an object and switched the Genre, the object was still in memory unchanged. More importantly, the size of the cache in the context was growing every time. I didn't want this so I changed the way I was handling the returned values.
The context has a collection of EntitySet objects. Each EntitySet is for a particular data type. I wanted to change the behavior to only have a single set of games at any particular time. This way my call to HasChanges was only testing the current set of games, not every game I've ever loaded. To do this, I made one small change:
void PerformGameQuery()
{
// Clear the games so we don't consume a lot of memory
Context.Games.Clear();
...
}
This allows us to remove games we no longer care about.
Server Paging
We should start with the paging story since that affects the design of the add/delete functionality. In RIA Services paging is pretty simple. Since the query to the server can contain some very simple LINQ expressions, we can use the Skip and Take expressions to shape the result (Where and OrderBy are also supported). For example if we want to get the second page where the page size is ten records:
// Generate the query with paging
var qry = Context.GetGamesByGenreQuery("Shooters")
.Skip(10)
.Take(10);
Context.Load<T>(qry, OnGamesLoadedComplete);
The Skip expression tells RIA Services to look at the result (on the server) and skip those records; The Take expression tells RIA Services to limit the number of results returned (like a TOP clause in SQL). Using them together allows us to page. But I like the hide the paging in the Model. Sure the ViewModels will need to know about the paging, but they shouldn't control the size or method of paging. To achieve this, I've added a couple of properties to my model:
public class GamesModel : IGamesModel
{
private int _currentGamesPage = 0;
private readonly int GAMESPAGESIZE = 15;
private string _lastGenre;
...
Using these parts of the model, I can handle the size and current page. One problem with this design though is that its emparting state into the Model. But since our Model already has the data context which holds onto references to returned elements, I think this is an acceptable solution.
The paging then becomes pretty simple, when GetGamesByGenre is called, we get the first page (and reset the paging mechanism):
public void GetGamesByGenreAsync(string genre)
{
_currentGamesPage = 0;
_lastGenre = genre;
// Generate the query with paging
var qry = Context.GetGamesByGenreQuery(_lastGenre)
.Skip(_currentGamesPage * GAMESPAGESIZE)
.Take(GAMESPAGESIZE);
...
When the initial call to GetGamesByGenreAsync happens, we reset the paging and store the last genre (so we can use it when we get subsequent pages). In the query, we calculate the page and execute that query. When NextPage/PrevPage are called, we use this same data to calculate the subsequent pages:
public void GetPrevPageGamesAsync()
{
if (_currentGamesPage > 0)
{
_currentGamesPage--;
// Generate the query with paging
var qry = Context.GetGamesByGenreQuery(_lastGenre)
.Skip(_currentGamesPage * GAMESPAGESIZE)
.Take(GAMESPAGESIZE);
}
}
public void GetNextPageGamesAsync()
{
_currentGamesPage++;
// Generate the query with paging
var qry = Context.GetGamesByGenreQuery(_lastGenre)
.Skip(_currentGamesPage * GAMESPAGESIZE)
.Take(GAMESPAGESIZE);
}
Once the model supports this, the ViewModel can use it via a Command:
RelayCommand _prevPageCommand = null;
public RelayCommand PreviousPage
{
get
{
if (_prevPageCommand == null)
{
_prevPageCommand = new RelayCommand(
() => _model.GetPrevPageGamesAsync(),
() => Games != null && Games.Count() > 0);
}
return _prevPageCommand;
}
}
private RelayCommand _nextPageCommand = null;
public RelayCommand NextPage
{
get
{
if (_nextPageCommand == null)
{
_nextPageCommand = new RelayCommand(
() => _model.GetNextPageGamesAsync(),
() => Games != null && Games.Count() > 0);
}
return _nextPageCommand;
}
}
Then these commands can be data bound to controls (in my case buttons). Typically I am immediately asked about how to know when you've reached the end of paging. This is a little wierd because you could handle it by determining if the number returned is less than a full page but because it *can* be the last page and return the full number of the page you can't rely on it. The other solution is to determine it on the server, but in most cases (as the server results can change in a Transactional System), I just try and get the next page and if the number of results equals zero, I move the page counter back one and reload the results. Its not as efficent but it is only non-efficient in an edge case (returning exactly the page size as the last page. In the Model I handle this like so:
else if (r.Entities.Count() == 0 && _currentGamesPage > 0)
{
// If the page returned no results we
// reached the end of a page edge
// (important since we're not getting
// full result counts from the server)
GetPrevPageGamesAsync();
}
Dealing with Add/Delete
While I differ from the RIA teams view, I like to isolate the RIA Service layer inside the Model completely. That means that the model can be responsible for the actual adding removing of the items. But this represents a problem. In our earlier parts to this series, I returned the results of the loading query directly to the ViewModel to use as it's data. The datatype we returned was an IEnumerable<T> object. Ordinarily this works but since we're supporting adding and removing, the IEnumerable<T> object doesn't support that. So I dug a little deeper to see if the actual returning object supported ICollection or ICollection<T>. Nope. In fact, the underlying object is a ReadOnlyCollection<T>. Yup, read-only. So our original assumption to return the results wasn't helpful Instead, I changed this to return the EntitySet directly from the RIA Services' Context object:
// Returning the raw Games collection since the
// entity results are a ReadOnly collection
evt(this, new EntityResultsArgs<Game>(Context.Games));
Since the underlying type that the EntityResultsHandler is expecting is still IEnumerable<T> we could do one of two things, either change the event to allow a richer object (e.g. ICollection) or let the model to be reponsible for Adding/Removing of objects. I chose the latter:
public class GamesModel : IGamesModel
{
...
public Game AddNewGame()
{
var g = new Game()
{
GameID = 0,
Name = "*TODO*"
};
Context.Games.Add(g);
return g;
}
public void DeleteGame(Game g)
{
Context.Games.Remove(g);
}
...
}
I don't prefer this solution. I would prefer to have a monitored ObservableCollection<T> that is watched for add/delete operations but since RIA Services doesn't work that way, this work around is acceptable.
To allow for any of the views to issue these commands, I chose to use another application message like we dicussed in prior parts of this series. In this case, while the model is doing the real work of adding and removing, there is still some work to be done once the game is added or deleted. For example here is the event for adding an item:
AppMessages.AddNewGameMessage.Register(this,
ignore =>
{
CurrentGame = _model.AddNewGame();
});
In the MVVM Light implementation of their Messenger, they don't allow for no actual data being sent with the message, so I just use an object and in the lambda I named it ignore so you could tell that it was a dummy piece of data. Inside the message handler, you can see I am calling the model to add the new game, but then setting the current game to be the new game (so that it can be immediately edited). All of this happens in the GamesListViewModel so by setting the new game as the CurrentGame we get both that the ListBox in the view is selected as well as a message is being sent out (that the GameEditViewModel listens for) that a new CurrentGame has been selected which allows it to be edited. Again, the model is responsible for the record-keeping, but the view model continues to work as expected to communicate with the actual view.
The delete message is the same:
AppMessages.DeleteCurrentGameMessage.Register(this,
ignore =>
{
_model.DeleteGame(CurrentGame);
CurrentGame = null;
});
In this case we tell the model to delete the game and mark the current game as a null reference which prevents the editing in the edit view as well as deselects the item from the ListBox in the List view. This pattern should allow you to continue separating your concerns between the different layers.
You can get the final version of the example here:
http://wildermuth.com/downloads/riaxboxgames.zip