Escape the ‘RM’ in ORM using MongoDB

Last week we hit the customary ORM wall when we had to model a Many-To-Many relationship in our domain model. Even with Castle ActiveRecord we were still being forced to create either association table on the database schema, or an equivalent class to leverage ActiveRecord’s automatic schema creation. Added on top the need to manage SQL Server instances, we decided to take a fresh look at storage options that will allow us to continue coding with minimal friction on persistance.

Getting a cue from a former colleague at ThoughtWork, I started looking into the NoSQL movement. MongoDB seems to be getting a fair amount of press recently so I decided to try it out. Using NoRM as the .Net driver for MongoDB, I was able to covert our (still very small) codebase from using ActiveRecord to MongoDB in about 2 hours.

The process was made easier by our use of Repository pattern so most of the changes are concentrated in all the repositories methods (CRUD and queries). One potential side benefit is that because MongoDB is so fast, it is now possible to test data queries along side regular unit tests with minimal cost in time. This is generally not possible with RDBMS data storage.

* One of the useful tip I’ve come across is how to run MongoDB as Windows service.

UITableView scrolling performance gotcha

After a few months of .NET reporting/SSIS development work, I’m back to an iPhone project this week. One enhancement I added yesterday was a better formatted table section title in a UITableView. Before, the section title is either a bunch of unformatted (also incorrectly by locale) dates (e.g. 2009-09-30), or times (e.g. 14:58) straight from the data source. The enhancement/bug fix is to format the date or time to be locale aware so the title would either be “Wed Sep, 30 2009” or “2:58 PM” if you are in the US.

Pretty straightforward I thought, and after a couple of trips to NSDateFormatter and use the output in UITableView’s titleForHeaderInSection:section method, it was all working very well in the simulator. That was until I put the app onto my iPhone for some real in-device testing.

The scrolling performance in the table was horrible! My first thought was that it had to do with the background view I added to the custom table cell view for colouring the table cell background. But after nearly an hour of debugging through the code I still couldn’t find anything wrong.

Turns out that the titleForHeaderInSection:section method is not just called once per controller instantiation. It is called once per table cell display!

Once I moved the code to format the section title into viewDidLoad and cached a copy of the nicely formatted titles in an array, the scrolling is back to normal speed.

Objective-C discourages good OO design/code?

I started learning Objective-C when Apple released the iPhone SDK over a year ago, and started programming in it seriously at the beginning of this year. While there are many things I like about Objective-C as a OO language, there is one thing that continuously bother me.

One of the four main tenant of object-oriented design is Encapsulation. Meaning, the inner working of an object is hidden from public view.

In Objective-C, an instance method can be declared in the implementation file (.m file) in the following ways:

  • Implement the method without declaring it in the header file. This is (almost) equivalent to private method in C#/Java.
  • Declare the method signature in the header file, and implement the method in the .m file. This is like declaring a method public in C#/Java.

So how does this discourages me from writing good OO code with respect to encapsulation?

If I choose the first option, I have two choices. Either I implement the method before its first usage which does no good with readability re Uncle Bob’s Clean Code‘s newspaper metaphor, OR implement it after and put up with the compiler warning about the method call may not exist.

To get the freedom of placing the method anywhere in the .m file, I have to choose the second option and declare the method signature in the header file. The downside of this is that now the method is exposed as part of the class public interface and break encapsulation. (Yes, I know that the method can still be called without the header file declaration. Again, a compiler warning greets you.)

All three options are undesirable to me. It is really a case of pick my poison! Right now, I choose option one and put the method before first usage. Readability suffers because I like reading methods after the usage but at least the header file is clean and represents the intended public interface.

Update: Martin Pilkington makes a suggestion to me via Twitter. I’ll have to try it out and see.

Update #2: Someone else on Twitter also suggests using Extension to solve this issue. The Apple’s documentation here (at the end of the page) shows how an extension of a class can be used to define private method, separated from the main class interface definition.

My initial feel? Pretty inelegant workaround to an inherited problem of Objective-C legacy linkage to C. No thanks, I’ll stick with declaring private methods before usage.

UIScrollView and Multi-Touch zooming

Let's say you have a nice, big, hi-res photo you want to show to your user on the iPhone. No doubt you want to let your user zoom in to see details of the photo and scroll around, just like the built-in Photos.app.
Most of you would probably come up with something akin to the following structure using Interface Builder:

UIView

|
–UIScrollView
|
–UIImageView
If you are coding the UI by hand, the top level UIView would probably be omitted. This may or may not be relevant to the issue you'll be encountering. See my note at the end.
Now that the view structure is setup, you will probably discover that double tapping to zoom in/out is not implemented out of the box by Apple (surprise!).
"Ok", you thought to yourself, "I just need to implement the touch events in the controller and it will all work."
So you go ahead and added touch event code to the controller class, probably something like this:

– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *touch = [touches anyObject];

NSInteger tapCount = [touch tapCount];

if (tapCount == 2) {

[scrollView_ setZoomScale:zoomScale animated:YES];

}

}

When you run the code, you'll find that the touchesEnded method never get called!
Turns out this is actually by design from Apple. touchesEnded and other touch event methods are no-op methods by default. My guess is that this is probably a performance related design decision.
Regardless of why, here is what you need to do to 'fix' this. First, create a new class that inherits from UIScrollView. Then in this new subclass, implements the touch event method that you want to use and passes on the event to the next responder in the list. Like this:

– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

{

[super touchesEnded:touches withEvent:event];

[self.nextResponder touchesEnded:touches withEvent:event];

}

This will pass on the touch event to the parent UIView in the hierarchy and thus calls the touch method in the controller.
Problem solved!
(One thing I haven't tried is to removed the top level UIView from the hierarchy, and link the UIScrollView to the view outlet in the controller. My hunch is that this may eliminate the need to subclass UIScrollView.)

Read and post comments

|

Send to a friend

Inoperative Cancel button in UIActionSheet

Let’s say you want to use UIActionSheet to show three buttons to the user with a cancel buttons in a UIView, which itself is managed by a UITabBarController:

Your code would probably look like this:

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@”Action Title” delegate:self cancelButtonTitle:@”Cancel” destructiveButtonTitle:nil otherButtonTitles:@”Option 1″@”Option 2″@”Option 3″nil];

actionSheet.actionSheetStyle = UIActionSheetStyleDefault;

[actionSheet showInView:self.view];

[actionSheet release];

And you’ll also probably find that all the 3 option buttons works, but the Cancel one doesn’t!
It is because the UIView which the UIAlertSheet belongs to is behind the UITabBarController, and the TabBar’s hitTest method gets called before the UIAlertSheet’s.
To fix this, it is just a simple matter of using the view from the UITabBarController in the showInView method. Like this:

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@”Action Title” delegate:self cancelButtonTitle:@”Cancel” destructiveButtonTitle:nil otherButtonTitles:@”Option 1″@”Option 2″@”Option 3″nil];

actionSheet.actionSheetStyle = UIActionSheetStyleDefault;

UIApplicationDelegate *appDelegate = (UIApplicationDelegate *)[[UIApplication sharedApplication] delegate];

UITabBarController *tabBarController = appDelegate.tabBarController;

[actionSheet showInView:tabBarController.view];

[actionSheet release];

iPhone development talk in Philly

Last Tuesday I travelled down to Philadelphia to speak at the Philly ALT.NET meeting. Brian Donahue, the group organiser, invited me to talk about my experience of developing iPhone application from a .NET perspective. Over 20 people turned up and I was surprised that most of them already owned an iPhone and a Mac (remember this is a .NET group afterall).

I began with listing out the things require for iPhone development (hardware and software), then moved onto comparing Objective-C/Xcode with C#/Visual Studio. I showed a quick code demo to illustrate my points on language and environment differences. Finally I talked about the good, bad, and ugly things I feel about iPhone development up to this point.

This is the first time I gave this talk and feel the Philly audience got good value from my experience. The event was hosted at Drexel University campus and a few of the iSchool students were in the audience. One of them even came up to me afterward and asked whether I’d be interested in doing more talks on iPhone development for iSchool!

Here are the slides I presented:

 

 

 

One of the attendee also took some videos and I’ll post them as soon as I receive the link.

 

Alt.NET Seattle ’09

Couple of weekends ago, I was at Redmond for the Alt.NET Seattle conference. As this was my second time there, I was no longer a Open Space/Alt.NET virgin. Just like last year, an amazing amount of discussions were packed into two full days. It was very difficult to pick which sessions to attend, having to decide whether to sit in a technical discussion or a meta-discussion. But with so many people recording videos, it is almost possible to not miss anything. We are not quiet there yet, but I am sure in the future every session would be recorded/streamed in some manner.
Ward Cunningham Keynote

Ward Cunningham showed us the work he did during his time with the Eclipse project on unit testing on a new level of complexity. He calls it SWIM and was implemented in PHP/HTML/CSS/JavaScript. He proposed to start a new open source project to implement the same concept in .NET. This create enough interest to spawn off a separate session later this weekend. (The test case runner was provisionally named Swim Runner. Personally I think it should be named Swimmer!)
Encouraging Open Source in .NET

Last year in Seattle, a similar session was convened to discuss how to create more buzz and interest in open source projects in .Net space. This year’s session centered around how we can get more open source projects to start, worked on, and succeed. Scott Hanselman hosted this session and asked what the community can do. Should Microsoft give Oren Eini a mail-order bride so he can finish LINQ-to-NHibernate? (Joke) What about OSS projects adaption by VB.NET developers?
.NET/Mono on Mac, Linux, and iPhone

Miguel de Icaza of the Mono Project hosted the session. He showed us the tooling and technique to develop iPhone app/game using the Mono stack on the Mac. He also demonstrated autogeneration of linux bootable image with pre-configured apps. (Side observation #1: only a few people at last year Alt.NET Seattle had iPhones, this year very few people has phones that *isn’t* an iPhone. Since this year’s event was just before MVP Summit, there are lots of MVPs there with iPhones! Just to show loyalty does not lie with brand but usability! #2: Less than 1/3 of attendees aware of Twitter last year, this year, very few are *not* on Twitter.)
Why so mean?

Hosted by Scott Hanselman. We explored why there is an perception of elitism in the software developer community. Why C# developers talk down to VB.NET developers, why average Microsoft developers are dimmed un-savable. This discussion led to a new session on Sunday about teaching, ALT.NET Pedagogy.
Oxite Retrospective #2

When the Oxite project (a sample blogging engine created using ASP.NET MVC framework) was put up on CodePlex, it created a huge controversy in the Alt.NET community. This is the second part of the retrospective on the project and the aftermath. One of the Oxite team member from Microsoft joined us on Sunday and gave his point of view from the inside.
When to use F#?

With F# being the first class language within the Visual Studio ecosystem, functional programming is gathering more interest. When is functional programming be appropriate for a .NET project? What type of problem would it solve better than plain old C#/VB.NET? Why not just use F# for everything?
Abstract Test Assertions

The ASP.NET MVC Contrib project relies heavily, of course, on TDD. An interesting problem arise when contributors want to develop using different unit testing framework. This session explored the idea of abstracting test assertions so that any frameworks can be used for the project, and what technique should be employed to achieve that.
I’ve recorded all these sessions on video for those who couldn’t attend. Scott Hanselman also streamed live via Kyte.tv for a number of sessions. My videos can be viewed on Vimeo, with the rest of video links on the Alt.NET wiki.

 

iPhone Developer’s Cookbook review

When learning a new language/platform/framework, sometimes learning from a book is a good approach. But that depends heavily on picking the 'right' book. What I mean is that the book contains the 'right' amount of content for the reader's skill level. So when I looked for book to learn more about iPhone development, I have something specific in my mind already.

With Apple's original rather restrictive NDA placed on iPhone developers, all the iPhone development books were placed on hold until Apple changed of mind a few months back. One of the book that I received good recommendation from fellow ThoughtWorkers who were also interested in iPhone development was Erica Sudan's iPhone Developer's Cookbook. I bought it earlier this month along with Christmas presents so I can read it during the holiday vacation.

The book is not thick at all, coming just under 340 pages, and took me couple of afternoons to read through. It is written half in traditional cover-to-cover manner and half in 'recipe' manner where developers can find solutions to problem quickly. Perhaps because I've been part of the iPhone SDK program since the beginning and had seen the evolution from the first beta, most of the book content (I'd say 90%) is not new to me. Particularly the sections on table, advanced table, and UI controls are areas that I am already very familiar with after poking around the SDK for over 6 months. I did learn some valuable tips on media and animation, which I've not spent any time on yet.
I'm kind of disappointed by the book because I was hoping I would learn how to create great iPhone app. Particular I was looking for code examples of common application requirements (e.g. how to implement options screen) with in-depth discussion on the limitations imposed by the public API, alternative ways to work around them using legitimate means, as well as undocumented API. I am also hoping to see some mention of unit testing with OCUnit or Google's unit testing framework, profiling using Instrument, and other libraries that would fill in the API gaps. Instead, the book only provides isolated information on each topic and spends to my mind, a disproportion amount of time on undocumented API thus giving it an implicit approval. (On the topic of private/undocumented API, I am in the camp of John Gruber of Daring Fireball)
In the end, I would give this book 3 out of 5 because it provides a lot of valuable information for any one starting out with iPhone development. But it does not provide any insight into building great iPhone application, which I think is sorely missing in this area.

Read and post comments |
Send to a friend

Spit and Polish

A few months back, I started working on an iPhone app using the beta version of the iPhone SDK. Since then various things got in the way (not to mention the restriction of the old TOS placed on developers so everyone were working in the dark) and I didn't spend any time on it to really finish the app. My interest was revived when I attended the iPhone Tech Talk event in NYC last Tuesday. The sessions were interesting but nothing technical or coding. I learnt a lot more about the process of provisioning an iPhone for development testing and distribution, as well as how to submit app to the iTunes App Store. Most importantly though were that I was able to resolve issues around my personal's Standard and ThoughtWorks' Enterprise applications to the iPhone Developer Program. Now I am able to distribute and test my app on actual phone(s)!

Since Tuesday, I've been spending lots of my free time on polishing up the CCPhone app so I can start distributing it to the masses. One main change from the original vision is the colour theme change. This stems from the advice in the "iPhone User Interface Design" session, where dark colour theme is the preferred colour for apps that people use for short period of time (and possibly under the table/desk).

Another I've found is that the SDK has improved in many ways since the 2.0 days. Now it is easy to find the relevant sample code from the API reference documentation since the links to the sample apps are hyperlinked! There are also a lot more documentation on how to use various type of controls/classes in an advanced manner, much more than just the simple basis stuff. And from talking to all the Apple staff in the Tech Talk, I was impressed by how receptive they are to feedback. Even the really stupid stuff that they shouldn't have released in the first place.
And get this. I ran across a problem with the iPhone Developer Portal on Wednesday when I tried to set myself up with both my personal account and the ThoughtWorks' enterprise account. Somehow I was not able to switch between the two and when I un-assigned myself from the TW's account, I no longer had access to my personal one! With no recourse, I ended up sending an email to Apple and waited. That evening around 5PM, I got a surprise phone call from Apple inquiring about my problem. By that time, the problem had mysteriously resolved itself so I gave the lady on the phone my feedback on the Portal instead. Imagine that, someone actually calls the developer to resolve an issue!
CCPhone is just my way of dipping my toes in the water, testing the temperature. Now I need some more ideas for apps that I can work on.

Read and post comments |
Send to a friend

Blog at WordPress.com.

Up ↑

%d bloggers like this: