I made an app for Windows Phone 8

It’s winter and I’m on a holiday so I have lots of free time at my hands. I thought that maybe I could spend it in a productive fashion, so I wrote an app for Windows Phone 8.

The app itself is a GitHub client, which lets you check out your repositories, view files and diffs and do other stuff. It’s open source, of course, and hosted on GitHub. Check out the source code!

Connecting to the API

I knew it won’t be a walk in the park, but there’s a very nice project on GitHub which lets you use the whole API, called OctoKit.NET.  It even has a portable library for Windows Store. But not for Windows Phone, so you have to take portable as in portable to another Windows 8 PC. Something is seriously messed up here, and we’re heading towards a new kind of DLL hell.

But it’s not the fault of the guys behind OctoKit, this is the current ecosystem. I thought that I’d fork their project and do some changes to make it a portable library for Windows Phone 8. Nope, that’s not going to happen. Networking code is not part of the portable stuff, you have to do that in your Windows Phone project.

So I did that there. Wrote a client for the API parts I actually needed, and used that. It wasn’t a huge work, and JSON.NET made it very easy as well.


There’s decent MVVM support in the WP8 controls, but I ran into some horrible stuff which seriously messes up properly architectured code. One being the ApplicationBar control, which doesn’t support bindings. Even the sample project has that horrible commented out stub like BuildLocalizedAppBar. Also it doesn’t support commands, so you’ve to have event handlers in your XAML code behind, instead using the ViewModel for this stuff. That’s a shame. I hope that Microsoft fleshes this out in some upcoming release.

Some limitations

I wanted to build a page for viewing your source code files and diffs. I’m a fan of short files with one class in them, but there’s a perfectly fine chance that files grow bigger. The idea was to grab a TextBlock and bind it to the file text. Later when I feel like syntax highlighting, I’d ditch the TextBlock and try something else.

However I noticed that a TextBlock (or any other control, by the way) tends to cut off its content after some height. It turned out that the maximal control height in WP8 is about 2040 pixels. So I wrote an abomination to split the stuff into small chunks and add it dynamically to a StackPanel. Ugly and broke MVVM brutally. I know about a control written for WP7 that doesn’t cut off stuff, but there were some changes between the versions, and it wasn’t worth the effort to adapt it for a fun project like this.

Lack of unit testing support

Now this almost made me gave up the project. I wondered what can be the Windows Phone 8 Unit Tests template in Visual Studio, but I never thought that they want me to run my tests on my actual phone (or buy Windows 8 Pro and use an emulator). Am I supposed to connect a phone to a build server and run the tests there if I’m serious about WP8 development?

The excuse was laughable at best: WP8 code relies so much on WP8 libraries that the unit tests will surely touch libraries depending on the platform. I did a fairly big amount of SharePoint unit testing, which enforces that too, but never needed to run my tests in a SharePoint server. The whole point of unit tests would be to test a unit of code, and if you really need it, provide some mocks or stubs for the dependencies. I think that Microsoft got this one really bad.

So what’s the point?

Windows Phone 8 as a development platform doesn’t seem that mature for me. There are lots of quirks and you have to do lots of workarounds for simple stuff. A template project requiring workarounds is something I haven’t seen yet anywhere else.

The development tools on the other hand are fairly robust, it’s a pleasure to write mobile apps with Visual Studio at last. However Microsoft doesn’t seem to be in a position to ship incomplete libraries for developers, as this clearly won’t help overcome their chicken and egg problem of nobody develops on the platform because there are not enough users because nobody develops apps.

I think I’d consider iOS as my primary mobile development platform, and write some fun side projects if I have the time and resources for WP8.


Mobile event viewer: User Interface

This is the second post of a series of tutorials for creating an event viewer for iOS. You can find the first post, which deals with basic architecture an network connections, here.

There’s also an accompanying Github project.

This post will be about the user interface. Since no built-in control exist for mimicking the calendar day view in iOS (neither in Android) and I’m not very great drawing controls, I started checking for open source implementations. There’s a very easy to use project on Github by muhku, called calendar-ui.

What we need from it is the MADayView class, along with MAEvent. MADayView, as the name suggests provides a view which renders the calendar day view. It has a delegate and a datasource property. In my example, I rigged both, but only used the datasource. Here’s how I set up the view.

EventListViewController.h changed a little:

As you can see, I imported MADayView.h, and added its datasource and delegate protocols to the header. I also added an IBOutlet for MADayView, and connected it to its counterpart in EventListViewController.xib. Basically the UITableView implementation was replaced to an MADayView implementation. In EventListViewController.m there are some changes too:

The main change here is that instead of UITableView I use MADayView. Its datasource protocol is very easy to satisfy, only a method with the signature: (NSArray*)dayView:(MADayView*)dayView eventsForDate:(NSDate*)startDate needs to be implemented.

This method unfortunately needs to return an array of MAEvent objects. I like to separate third party code from my, so I created a mapper which maps my own Event class to an MAEvent (a variant of the Adapter pattern). This way, if the very unlikely day would come when I want to change the UI in this tutorial, I could do with minimal changes. There are also two callback methods from MADayView which I put in there for paging: nextDate and previousDate. These should be the part of the delegate protocol, but I was sloppy and just use two selectors for the effect.

What may be interesting in these methods are the [actualDate yesterday] and [actualDate tomorrow] calls. These are implemented in a category on NSDate. The code looks like the following:

It simply uses NSDateComponents to increment or decrement the date on which it’s called (thus working with daylight saving times, leap years, etc.).

In the following post, I’ll show how to scroll between days to implement a truly native experience.

Mobile event viewer: basic architecture and retrieving events

This is the first post of a series of tutorials for creating an event viewer for iOS and Android. In this post, we’ll examine the high-level application architecture. The project is located at https://github.com/gergelykoncz/Events.iOS.

The objective of the app is to display events in a view similar to the built-in daily calendar view. Since there are no public APIs for this neither on iOS nor on Android, we’ll roll out our own solutions, but first let’s plan the application.

We’ll work with only one entity (for now), which I decided to call Event. The event class looks like this:

As you can see, it has an identifier, a start and end date, a summary, a description, and a flag indicating if it’s an all day event. Nothing particularly difficult.

Events will come from a web service in JSON format, but it’s an implementation detail. I don’t really care where they come from at this point, but I’ve a firm belief that every class should do one and only one thing (the Single Responsibility Principle), so there should be a class that I can call and it gives me back some events. This is in fact an already named pattern, called Repository. Thus I created a class named EventRepository, which will serve my events whatever way it finds best.

Note: I don’t want to get too enterprisey at this point, but if we’d have more sources for our events, then we could create some more repositories (one for each source, with a common interface/base class), and use a Facade as a coordinator class which would delegate the event retrieval for based on whatever logic we find best.

So let’s review this EventRepository. As I stated before, the events come from a web service, in JSON format. Since it uses the network and this can (and will) introduce so much delay that our app would be very unresponsive if we would want to wait until data is loaded (if it’ll be loaded at all). That’s why I use NSURLConnection in an asynchronous fashion. When someone calls EventRepository to load the dates, it builds an NSURLConnection, set its delegate to itself and fires the request. After this the main thread is free to do whatever meaningful work instead of waiting for the request to complete.

There are two common cases at this point: the request fails, or it succeeds. In both cases we should notify the caller, but first let’s see the cases in detail.

If the request succeeds, we parse the result as JSON, using the NSJSONSerialization class. Since our API returns an array of events, we iterate over each JSON object in the array, and create an instance of Event using a different class, EventMapper. As its name suggests, EventMapper is a mapper. You can find this concept under many names (here is a discussion on the topic, and here’s a recent post of mine regarding mappers), the gist of it is that it is a class that it builds entities based on some input.

After we have our collection of events, we simply notify the caller through a delegate. If anything goes wrong, we use the same delegate as well. There are multiple ways of doing this, we could have used the NSNotificationCenter, but the Cocoa framework uses the Delegation pattern more extensively, and I got very used to it. The concept is exactly the same as with EventRepository and NSURLConnection. EventRepository simply delegates the task of retrieving events to NSURLConnection, and provides a way (in this case, a reference) to NSURLConnection to notify it when it’s done.

EventRepository offers this thing in its loadEventsForDate method. It accepts a date, naturally, and a delegate object which it’ll notify if it has a result (or any error occurs in the process).

Here’s the protocol (EventsDelegate) that is being used:

And we’re almost done! There’s a final piece without our work does nothing: we need a ViewController. And our ViewController has to implement the EventsDelegate so that it can be notified by EventRepository. The example class EventListViewController is for demonstration purposes only. It won’t render our shiny events in the promised daily calendar view format (that is the topic of an upcoming post), rather it uses a mere UITableView. Here is the source:

As you can see, by using the right patterns and careful delegation, we ended up with a short and maintainable view controller. In fact, less than ten lines (blanks included) are responsible for loading events and  reporting errors. Most of the class deals with the UITableView delegates.

I hope that I managed to emphasize how clean your design can become when you use the appropriate patterns and concepts. I think that by creating smaller classes with only truly one goal you can end up with a more maintainable (and thus, cost-effective) codebase. Of course there are some vital functions missing here, like error handling and logging, but I tried to make the examples more concise.

But don’t forget that the point of this is not the admiration of patterns and best practices, but to make an app that works. I’ll follow up this post (and the GitHub project) when I implemented the view I promised.

AD searching and the Template Method design pattern

A while back I had the funny task to obtain users from the AD and do present them in a neatly designed list. Since neatly organized employee lists hold a certain coolness factor, soon other departments grew jealous and wanted peeking their own employees, only with more info available and more neatly organized.

Now nothing holds more fun to the everyday developer than maintaining classes that does the same thing, only in a slightly different way. So I thought the logic can be made reusable, and by employing the magic of generics combined with the template method design pattern, the soon-to-come new departments needing slightly different info for their neatly organized employee lists could be taken care very fast.

So what is a template method and how does it work? Template method is just a fancy name for a method that your base class will call, and you can override its implementation in subclasses. I created a sample project and pushed it to GitHub, so let’s review what’s in there.

The gist of the template method is found in the class ADUserFinderAbstract<T>. Here’s how it’s looks like:

As you see, there’s a method called GetUser which goes into the AD and try to find a user. Then it calls an abstract method in the same class, called convertPrincipal, and passes the found user (or null, to be entirely correct) to this method. You can easily guess what is the point of this whole thing: override the abstract method in a subclass, and provide different implementations depending on various business needs. That’s what is done in the solution.

There are two implementations, one (EmailADUserFinder) simply returns the e-mail address of the user, the other (ComplexADUserFinder) does a lot more work, and tries to load department information, too.

And why go generic? In this particular business case, a generic implementation was more than ideal. I could map to the UserPrincipal object whatever entity I wanted, and do work with that. But template methods doesn’t necessary have to be generic methods of course. It only grants more power in this case.

I hope you’ll find this post useful, don’t forget to check out the GitHub project again!

The Specification Pattern

A recurring problem in my job is designing composite search forms. I guess it’s a fairly common scenario to receive a specification of a massive form with tons of checkboxes, textboxes and other UI controls for filtering your model. I knew there has to be a good way to do this, and I found the specification pattern which does just that.

Imagine your average repository :

It’s a barely testable, tightly coupled something which behaviour you cannot easily modify. It’s our starting point. We’ll have something like this when we finish:

The main concept of the pattern is to abstract away each search criteria into its dedicated class. The resulting classes then can be unit-testable, easily modifiable and even reusable. Reusability came very handy in my last project where I built a class for each search criteria then I just composed them in various ways to satisfy the business need.

The core of the specification pattern is an interface or an abstract class, depending on your personal taste, which looks like this:

This does nothing particular, just a generic interface with a single bool method taking a parameter of the type you want to filter. This is the absolute minimum you need to start working.

But the power of the pattern is that you can combine your classes with bool logic. A common choice is to have a base CompostieSpecification class, but if you have an abstract Specification class you can combine the two. CompositeSpecification looks like this in my example project:

Notice that it has three methods, And, Or and Not which returns concrete specification subclasses. Here’s how the AndSpecification class looks like, I’m pretty sure you’ll get the idea of the other two after this:

This was the abstract part of our implementation. You can find all of the above in my accompanying GitHub Specification sample project. They come fully covered with unit tests, too.

Now let’s look at our concrete person example. The sample project loads a bunch of randomly created person objects and lets you filter them by name, age and job title. Here’s the PersonNameSpecification implementation which is responsible for filtering by name:

The significant gain is that now you can unit test this search filter. I included a bunch of tests (the specifications themselves fully covered) so you can check out them.

In my sample project the creation of the specifications is the job of the SpecificationBuilder class, and it does a less than stellar job, and complicate things unnecessarily so I wouldn’t recommend that as a valuable example. This code fragment focuses on the pattern much better:

Specification is suited for otherwise complicated filtering, and typically a database is involved. In this case you’d prefer to use the IQueryable interface instead of IEnumerable and let your ORM build an optimal query instead of pulling everything into memory and filtering there. My sample isn’t suited for that, you’ll need additional work. You’ll need to build an expression tree from your specifications. Fortunately there’s a nice project on CodePlex called LinqSpecs which just does that. In my next post I’ll show you how to modify this example to work with it.

Sample project on Specification pattern

Today I spent the afternoon building a sample project to demonstrate the power of the Specification pattern. I’m not done yet, but I uploaded sample project on github. This pattern comes particularly handy if you have a lot of search conditions and you’d like to isolate them and make them testable.

About the implementation: ASP.NET MVC 3 running dependency injection on Castle Windsor. I didn’t take the time to include a database so I just created a fake Repository. I used a Façade for abstracting data access away, and there’s a Builder to create the appropriate specification objects based on user input. And user input is aggregated into a query object to enhance loose coupling.

And of course there’s a home-brew implementation of the Specification pattern and the project comes with pretty good test coverage, too. Note that I’d never recommend writing your own implementation, this project is for educational purposes only. In a following post I’ll describe the Good Way™ which I use in work.

The one thing that bothers me with this project is that I had the thought that having interfaces for every class is a nice example of YAGNI, so I only added one when it was absolutely needed. This lead to difficulties in testing and an awkward feeling working with these concrete classes. I guess that I’m yet to find the balance in this question.

So next week I’ll post how the Specification pattern is usable and how to implement it.