Sunday 27 December 2009

Moonlight 2.0...

Decided it was time to take another look at Moonlight (since 2.0 was released on 17-Dec-09), so I grabbed a Virtual PC image download and within a few minutes was testing my existing Silverlight sites on Linux! The pre-installed software (Firefox, Moonlight, even MonoDevelop) makes 'getting started' super-easy.

Happily, works fine -- although it uses the 'CTP' of Microsoft's Map control - the RTW requires SL3 which might throw a spanner in the works :-(

The DeepEarth open-source DeepZoom-based map control does work, however, which is great.

Searcharoo's Silverlight UI breaks with Could not load type 'BufferedStreamReader' from assembly System.Json so I'll have to investigate that; might have to get a different Json lib.

Anyway, IMO Moonlight 2.0 is a great achievement by Novell and the VPC is a great way for .NET developers to learn about it... have fun!

Tuesday 10 November 2009

iPhone Obj-C books for MonoTouch devs (first look)

UPDATE 6-JUN-10:This book Professional iPhone Programming with MonoTouch and .NET/C# is available for pre-order on Amazon... one of the authors might be familiar :-)

UPDATE 2-DEC-09: the first MonoTouch-specific book (that I know of) is now available to purchase/download - Building iPhone and iPod touch Applications for the .NET/C# Developer with MonoTouch (Wrox Blox). I haven't had a chance to read closely yet, but it's good value at USD6.99 so definitely worth a look.

iPhone BooksI recently received yet another addition to my 'Objective-C books for iPhone Development' collection - initially started to learn Obj-C (never happened) they are now more of a reference while learning MonoTouch.

Firstly, I have NOT read them cover-to-cover... I've done a bit of flicking, a bit of skimming and read a chapter or two. Secondly, I'm not really evaluating them according to their original purpose - to teach Objective-C - rather I'm making a personal judgement on their suitability as reference material for .NET developers.

I've listed them in their "order of usefulness" for MonoTouch .NET devs (according to me :)

Beginning iPhone Development: Exploring the iPhone SDK [BEGINNING IPHONE DEV]
Dave Mark; Jeff LaMarche (APress)

This was the first iPhone book I purchased, so I've read it more closely than the rest. I learned quite a bit from various examples and discussions in this book - it's probably at the top of the list for this reason. The writing style is easy to read and there isn't too much emphasis on Xcode (other books do seem to focus on Xcode, the Head First one most heavily).

The initial chapters are probably best replaced with a MonoTouch 'Hello World' screencast - you don't really need to know all the Xcode, pch files and @synthesize that the book discusses (and there are quite a few free resources around that cover "your first MonoTouch app").

• Interface Builder examples are relevant
• Friendly colloquial tone
• Widest variety of topics (includes localization, accelerometer)

• Large swaths of Objective-C in some chapters
• Still need to decode Objective-C in the examples

Overall, though, my favorite of the bunch.

The iPhone Developer's Cookbook: Building Applications with the iPhone SDK
Erica Sadun (Addison Wesley)

I'm a big fan of Erica's from her blog and applications when the iPhone and iPod Touch first appeared and were programmable. Text is easy to read. Erica often references "when the iPhone first appeared" or "during the Beta period" - often interesting insights that add some fun to the text. There are also references to many 'undocumented' APIs - they're clearly highlighted to avoid confusion, but unfortunately they're even more difficult to use from MonoTouch than Objective-C... I felt a bit "left out" on first reading, although with btouch in MonoTouch 1.2 I'm wondering whether it might be easier to access these APIs now? (even though we're not supposed to...)

Chapter 2 - Views - does a really nice job of gradually introducing various concepts, and the Objective-C is minimal. That chapter on it's own is probably worth reading for anyone coming to iPhone programming. The rest of the first half is also fairly easy to follow (View Controllers, Basic Tables) - if the examples were in C# they might be my favorite 'introduction to iphone programming' :)

Towards the end of the book the amount of Objective-C does increase to a few multi-page listings that are more difficult to read (and probably beyond beginning C#ers) but overall the book is good value.

There is a 2nd edition due in January 2010 which will probably address my other main concern with this book: that it pre-dates the latest iPhone OS releases and hardware. Not a big deal really, but it's always nice to have info on the latest and greatest.

iPhone SDK Application Development: Building Applications for the AppStore
Jonathan Zdziarski (O'Reilly)

Less "reading" in this book - rather than longer explanatory paragraphs the author uses smaller chunks of text interspersed with bullet points, callouts and small and large Objective-C listings. This actually makes it better as a reference book than a front-to-back learning tool - and that makes it more suitable for MonoTouch in my view.

As with the other titles, the initial chapters cover Objective-C concepts like messaging, implementation, protocols, categories and posing(!) which you aren't likely to need as you start out with MonoTouch (although you might return to read about them later, to get your head around more complex examples).

I've used the remainder of the book to 'look up' various things that I want to learn about or need examples of, usually as a backup/alternative to the material that I've found in other books or on the web. It doesn't have the breadth of "Beginning iPhone Dev" nor the easy readability of Erica's stuff, but I have definitely picked up some useful tidbits from this book.

Head First iPhone Development: A Learner's Guide to Creating Objective-C Applications for the iPhone
Dan Pilone; Tracey Pilone (O'Reilly)

I love the Head First series from O'Reilly, so I was determined to like this book; and it definitely lives up to it's promise as a Head First title. The writing, imagery, exercises and screenshots are all as you'd expect and it is really good at explaining Objective-C, Xcode and Interface Builder concepts... however that's partly what makes this volume less useful for C#ers: the writers go out of their way to explain/show how to do everything with Xcode and Interface Builder! As a MonoTouch developer I find myself only in MonoDevelop writing code and building my interfaces in code... so to my dismay I find myself unable to put this book at the top of my list.

It is still a fun read, and the non-techy bits (of which there are many) are extremely relevant to ALL iPhone devs. The recommendation to design your UI on paper, to follow Apple's Human Interface Guidelines, to remember to test on a Touch, and much more... if I ever decide to really learn Objective-C, I'll probably come back to this book and run through all the examples from go-to-whoa since it does try to teach the language and the SDK (and I really need help with my memory management!).

iPhone Cool Projects
Bennett et al (Apress)

The most 'attractive' of the five, due to the easy-to-read typesetting and colorful (yes COLOR) layout and imagery; this book probably doesn't really even belong in the list. It is more of a 'discussion' of iPhone application design - there is a fair amount of Objective-C throughout but it's mainly used to illustrate points of discussion, and the chunks are small enough that a C# developer can easily scan them.

Definitely fun to read - but you'll want any/all of the other books first to advance your knowledge of the iPhone SDK and Objective-C before you start trying to use the examples in this book. It probably isn't a good choice as a 'reference' or a learning tool for C#ers until you've got a few apps under your belt.

As time passes and my knowledge increases my opinion of these books might change. Perhaps others have different opinions on what makes a good "Obj-C for C#" book, or have come across other titles? I'm sure there'll be C#/MonoTouch specific titles on the market eventually - it will be interesting to see how they read too!

Monday 9 November 2009

Another MonoTouch 'conference app' - PDC09

PDC09I'm not planning on making a habit of this, but having spent the time putting together the Monospace conference app and seeing tweets from various Mono people that they were heading to PDC09, I figured it wouldn't take too long to copy some PDC data into the existing MonoTouch C# app 'framework'.

A new view (Sessions), a new icon (Speakers) and a new location (Underground) are the main changes - the rest is just SQLite and graphic tweaks. The source is available for download - (124Kb).

NOTE: This is for demonstration purposes only - the Speakers data is incomplete and the Schedule & Sessions are subject to change! Use at your own risk :)

UPDATE: to be clear, this app is not available on the AppStore -- it is just an example of the kind of thing you can write in C# for the iPhone using MonoTouch from Novell. If you have a MonoTouch licence then you can download the source (124Kb) and install it on your phone.

Monday 2 November 2009

MonoTouch UINavigationController Placemat

In one of my other posts I included a 'placemat' diagram to help make sense of the code.

Someone commented that they found the presentation useful, so as a quick post today I decided to placemat the Roget's 1911 Thesaurus sample.

Rogets 1911 Placemat

Note that I'm not suggesting this is the neatest, tidiest, best-practice way to structure a MonoTouch application (I'm learning along with everyone else). This is purely to help you find your way around the example code.

For example... on thing I learned is that I didn't really need to pass an instance of the 'root' MainViewController around - each UIViewController has a NavigationController property referencing the UINavigationController that 'contains' it. Therefore any given UIViewController that has been added to a UINavigationController can call this.PushViewController (or else pass a reference to this into the UITableViewDelegate constructor to use in RowSelected.

Monday 26 October 2009

MonoTouch "Corp411" (part III: Revenge of System.Data)

As promised, the Corp411 sample app has been 'converted' from sqlite-net to System.Data. MonoTouch 1.2 isn't quite out yet, so you must follow the instructions on this page to download the System.Data assemblies to your installation, put them in the correct place AND add references to your MonoDevelop solution for Mono.Data.Sqlite.dll, Mono.Data.Tds.dll, System.Data.dll, System.Transactions.dll (I'm not sure if they're all required, but it seemed like a sensible set).

It's pretty easy to use after all that:
// db is the path to the SQLite database file
var conn = new SqliteConnection("Data Source=" + db);
listData = new List<Employee>();
// System.Data from
var sd = new SystemDataHelper("phonebook");
var connection = sd.GetConnection();
using (var cmd = connection.CreateCommand())
connection.Open ();
cmd.CommandText = "SELECT Firstname, Lastname, Work, Mobile,"
+ " Department, Email "
+ " FROM Phonebook ORDER BY Lastname";
using (var reader = cmd.ExecuteReader ())
while (reader.Read ())
var emp = new Employee();
emp.Firstname = (string)reader["Firstname"];
emp.Lastname = (string)reader["Lastname"];
emp.Work = (string)reader["Work"];
emp.Mobile = (string)reader["Mobile"];
emp.Department = (string)reader["Department"];
emp.Email = (string)reader["Email"];
Console.WriteLine("Column {0}",reader["Lastname"]);
Cool eh? Doesn't that look familiar... good old ADO.NET :-)

That's a small part of the System.Data namespace, so the code is pretty small :) here 'tis (38Kb)

... and proof it runs on a device ...

Friday 23 October 2009

MonoTouch "Corp411" (part II)

A minor update to the Corporate Phonebook incorporating the custom UITableViewCell from Simon (UITableView now shows name and department in each cell; also added a disclosure indicator). Handles RowSelected and uses OpenUrl to call and email.

The MonoDevelop solution is available to download (41Kb).

//TODO: give the new MonoTouch 1.2 System.Data implementation a try!

//HACK: System.Data example now available (26-Oct)

Wednesday 21 October 2009

MonoTouch flip-flop with UIView animation

MonospaceThanks to Beginning iPhone Development's Objective-C examples the Monospace app now does a flip-flop between two views (the map and a new list of map locations to 'pan to'). The source code is available for download (you'll also notice the UI has been made "black"... I just like the way it looks). (188Kb)

The view is driven by the MapFlipViewController (which is what we add to the TabViewController). It is responsible for creating/displaying the two 'flippable' views using UIView animation features.

The two views - MapViewController & MapLocationViewController - have a constructor which accepts a reference to the 'flipper' so they can call back to it's Flip() method, which looks something like this...
if (mapView.View.Superview == null)
Console.WriteLine("to map");
(UIViewAnimationTransition.FlipFromRight, this.View, true);


Console.WriteLine("to list");
(UIViewAnimationTransition.FlipFromLeft, this.View, true);


There is other code to actually set the map to a specific location - but that's actually pretty simple :)

Monday 19 October 2009

Monospace app .1 release

MonospaceThe first version of the Monospace schedule app had a few issues (extra UITableView lines, for example); here is an updated version (with at least one less bug): (183Kb)

A couple of additional features were also added...

UITabBarController More & Edit
Two of the cool things about UITabBarController are (a) when you add more than five items, it automatically creates the More... option; and (b) when the More list is visible you can also edit the order/position of items in the tab bar. Bonus!

There is a new 'Sponsors' ViewController to show this functionality:

I've used a UIWebView with images saved locally as a quick hack to get the sponsors page working. Setting the baseUrl makes is easy to reference images saved in the application bundle from local Html.
string basedir = Environment.GetFolderPath 
basedir = basedir.Replace("Documents", "");
new NSUrl(basedir+"/Sponsors/", true));
CoreLocation with MapKit
The MapViewController now also uses CoreLocation.CLLocationManager and custom delegate to track your location and calculate the distance to the conference center:

It also includes a new UISegmentedControl to change the map style.

Sunday 18 October 2009

MonoTouch sans Interface Builder

I have nothing against Interface Builder per se, but as I've said before when developing with Visual Studio I shun the design surface (if you've used the Xaml preview feature prior to 2010 you'll understand why). I also think you get a better understanding of your environment (and a greater ability to customize your UI) if you can create it in code.

But for new MonoTouch developers it can be difficult to figure out how to create something in code. I've just been through this adding a UISegmentedControl to the Monospace app... here are my (rather obvious) suggestions:
  • Autocomplete/Intellisense™ - the easiest and most obvious thing to try is reading through the properties and methods available to you via MonoDevelop. I got the UITabBarController (mostly) working this way.
  • Interface Builder - look closely at the IB Inspector windows to get some ideas about the properties exposed.
  • XIB file - further to the Inspector windows, the XIB file (in its weird XMLish format) might also give you some hints. Obviously this means you need to 'draw' the control/s in IB, but just roughly for inspiration...
  • Objective-C references - for now most search results will be from Objective-C devs; it isn't hard to decode them (usually) so don't be dissuaded because it "looks different" :)
    Try Miguel's Rosetta stone decoder for Objective-C classes/properties → MonoTouch
  • MonoTouch docs - last but not least, the documentation will help you. Bookmark it now.
XIB and Inspector

UISegmentedControl in c#
// Don't forget your using statements 
// this example uses MonoTouch.MapKit
// as well as UIKit and Foundation
var segmentedControl = new UISegmentedControl();
segmentedControl.Frame = new RectangleF(20, 350, 282,44);
segmentedControl.InsertSegment("Map", 0, false);
segmentedControl.InsertSegment("Satellite", 1, false);
segmentedControl.InsertSegment("Hybrid", 2, false);
segmentedControl.SelectedSegment = 0;
segmentedControl.ControlStyle = UISegmentedControlStyle.Plain;

segmentedControl.ValueChanged += delegate {
if (segmentedControl.SelectedSegment == 0)
mapView.MapType = MonoTouch.MapKit.MKMapType.Standard;
else if (segmentedControl.SelectedSegment == 1)
mapView.MapType = MonoTouch.MapKit.MKMapType.Satellite;
else if (segmentedControl.SelectedSegment == 2)
mapView.MapType = MonoTouch.MapKit.MKMapType.Hybrid;
// And further down the code, don't forget to Add it!

Saturday 17 October 2009

MonoTouch for Monospace

MonospaceMonospace is coming up fast, with a whole day's worth of MonoTouch sessions. With that in mind, it seems kinda obvious to make the Monospace schedule available as a MonoTouch app...

Here are some screenshots:

In short, it provides:
  • Conference schedule (day/session/detail views)
  • Speakers (list/detail)
  • Access to the monospaceconf blog
  • Access to @monospace_conf's stream on Twitter
  • A map of the conference location
Some of the fun MonoTouch things I learned along the way include:
  • Creating a UITabBarController in code (no IB)
  • Making icons for UITabBarItem (hint)
  • Creating an 'image watermark' with UIImage behind a UITableView (thanks Mike)
  • Using Linq for Xml to parse Atom feeds (like RSS)
  • Implementing the latest SQLite wrapper from Frank
  • Changing the default UITableViewCell layout in code (eg mutiple lines)
  • Creating a custom UITableViewCell with LoadNib (thanks Simon)
I hope to write some more detail on each of these items... but for now you can download and run the code for yourself: (94Kb)

UPDATE 19-Oct: newer version available (183Kb)

UPDATE 21-Oct: even newer version available (188Kb)

and here's an annotated class diagram/placemat to help make sense of it all:

WARNING: there are plenty of shortcomings/hacks/missing features including: weird lines on the Speaker UITableView, no reloading of data from Blogger or Twitter without restarting, heaps of weird "pointer being freed was not allocated" errors accompanying the SQLite code (only visible in the Application Output window) and probably a pile of bugs I'm not aware of.

Thursday 8 October 2009

MonoTouch "Roget's 1911 Thesaurus"

This sample was inspired by Roget’s Hierarchical Thesaurus in a Silverlight App. I highly recommend you check out the Silverlight Thesaurus 'visualization' as it will give you some idea about why it seemed like a good match for the iPhone UINavigationController (ie. a hierarchy). The fact that it's not a uniform depth just makes the problem more interesting.

Charles very generously provided me with the source data he worked on to produce the Silverlight app (and the associated C# classes). It's great that MonoTouch allows existing .NET source to be re-used so easily.

Here are some screenshots of the iPhone app:

Xml de-serialization is easy...
Loading 2.6Mb of Xml data into an object graph is so easy with the System.Xml.Serialization support in MonoTouch!
using (TextReader reader = new StreamReader("roget15aCategories.xml"))
XmlSerializer serializer = new XmlSerializer(typeof(RogetCategories));
Categories = (RogetCategories)serializer.Deserialize(reader);
...but don't forget the linker
When you create the classes you will be de-serializing "into", don't forget to mark them with the MonoTouch.Foundation attribute [Preserve(AllMembers=true)]. This prevents the compiler/linker from 'optimising away' parts of your class that don't "appear" to be referenced in code (eg. the constructor) because they are only getting called at runtime as part of the deserialization process. Instead of marking the class declaration, you could alternatively mark specific members with [Preserve] to give you greater control over the final output.

Use Linq
Another great piece of .NET support is Linq. It isn't referenced in MonoDevelop MonoTouch solutions by default, so don't forget to right-click your References and tick System.Xml.Linq then add the using clause and Linq away...
public List GetRange (string start, string end)
Console.WriteLine("Get {0} to {1}", start, end);
var l = from c in Categories
where c.Index >= start.ToNumber() && c.Index <= end.ToNumber()
select c;
return l.ToList();
Use Extension Methods
Obviously if Linq works, so do extension methods. ToNumber() is a very simple (contrived, even) example of an extension method in MonoTouch:
public static class RogetExtensions
public static int ToNumber(this string num)
string s = num.Replace("a","");
int index;
if (int.TryParse(s, out index))
return index;
return -1;
"Look ma, no Interface Builder"
As I .NET developer I usually shun the design surface (in Xaml you don't really have a choice) so I was keen to try building an iPhone app without Interface Builder. It's a little difficult knowing where to start, but this UITableView in code example was immensely helpful.

There are four ViewControllers, and the basic format is the same for each: inherit from UIViewController (or a subclass), build up some controls in ViewDidLoad() and implement any additional delegates required.

The scrolling table views look like this:
// no XIB !
tableView = new UITableView()
Delegate = new TableViewDelegate(Classes, this),
DataSource = new TableViewDataSource(Classes, this),
AutoresizingMask = UIViewAutoresizing.FlexibleHeight|
BackgroundColor = UIColor.White,
tableView.Frame = new RectangleF (
0, 0, this.View.Frame.Width, this.View.Frame.Height);
and the 'details view' like this:
// no XIB !
webView = new UIWebView()
ScalesPageToFit = false
webView.LoadHtmlString(FormatText(), new NSUrl());
webView.Frame = new RectangleF (
0, 0, this.View.Frame.Width, this.View.Frame.Height);
Look in MainViewController.cs and AppController.cs to see how they are all wired together. The other ViewControllers pass around a reference to MainViewController so they can call mvc.NavigationController.PushViewController (????, true); which makes the navigation work (automatic 'back' buttons, animation between views, etc). I've no idea if this is the best way to do it, but hey it works :)

This sample code would not have been possible without the hard work of others. It also uses content which can have copyright/ownership implications.
  • Thank you to Charles Petzold for (a) researching/parsing the text (b) writing and supplying the .NET classes used to access it and (c) allowing his work to be included in this derivative
  • Acknowledgement to Project Gutenburg for providing the original text. The copyright status is listed as Not copyrighted in the United States. If you live elsewhere check the laws of your country before downloading this ebook. - I presume the same applies to users of this derivative work
  • Sabon Rai MonoTouch posts including UITableView in code taught me a lot.
Anyway, you can download the MonoDevelop solution and try it for yourself.

These two class diagrams show the structure of the code. The first shows the classes that are used to deserialize the Xml data:

while this shows the application and viewcontroller implementations:

Tuesday 6 October 2009

MonoTouch "iSOFlair" 2.0

The original iSOFlair post was purely a demonstration of using Settings.bundle root.plist to drive the iPhone Settings application. It's just a bit of fun with the "Flair" feature of and related sites.

Since then I've incorporated:
  • Simon's Page Control sample (with added Page Control handling)
  • Download and save image via HTTP
  • Shake gesture support
  • Screen capture to Photos, filesystem
  • Set the badge on the application's icon
This is what it looks like:

and you can download the MonoTouch v1.1 source code to try for yourself.

Settings via root.plist
Configuring the iSOFlair application to show a particular user's statistics is done by the built-in iPhone Settings on the home screen. Creating the Settings.bundle and root.plist is covered in this post.

Page Control
Simon's sample makes it easy to set-up a Page Control with swiping however it's also possible to move between 'pages' by touching to the left or right of the dots. I added this delegate to FinishedLaunching to handle that case:
// handler for when the user navigates via the pager, rather than swiping
pageControl.ValueChanged += delegate(object sender, EventArgs e) {
var pc = (UIPageControl)sender;
double fromPage = Math.Floor((scrollView.ContentOffset.X - scrollView.Frame.Width / 2) / scrollView.Frame.Width) + 1;
var toPage = pc.CurrentPage;
var pageOffset = scrollView.ContentOffset.X + scrollView.Frame.Width;
Console.WriteLine("fromPage " + fromPage + " toPage " + toPage);
if (fromPage > toPage)
pageOffset = scrollView.ContentOffset.X - scrollView.Frame.Width;
PointF p = new PointF(pageOffset, 0);
list[toPage].ViewController.BecomeFirstResponder(); // so it can "accept" shakes
// so we can change the 'badge' on the application icon
maxPageVisited = maxPageVisited<toPage?toPage:maxPageVisited;
Download, save and display PNG in UIImage
With using System.Net added to the file, the following code will download a remote image, save to the filesystem on the iPhone and set that image to display in a UIImage control on your view:
string ImagePath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
ImagePath = Path.Combine (DocumentsDirectory, Site.PreferencesPrefix+"gravatar.png");
WebClient wc = new WebClient();
Uri uri = new Uri(gravatarUrl);
wc.DownloadFile (uri, ImagePath); // saves to filesystem
catch (Exception ex1) {Console.Write("oops");}
//UIImage img = UIImage.FromFile (ImagePath); // WHY does this break???
UIImage img = UIImage.FromFileUncached(ImagePath); // BUT this works???
if (img != null)
this.imageAvatar.Image = img; // displays on View
Shake gesture
Responding to the iPhone OS 3.0 'shake' gesture was covered in this post. As I said before, showing the network activity indicator UIApplication.SharedApplication.NetworkActivityIndicatorVisible=true; and then false is a good idea so the user knows that something is going on!

Screen capture
Using UIGraphics ImageContext to take a screenshot was covered in this post.

Set badge
The 'badge' is pretty contrived in this example. Every time the application starts (in FinishedLaunching) I start the badge at '4' then during paging we reduce the count for each page that has been viewed. Just before the app closes (in WillTerminate) we set the badge via
UIApplication.SharedApplication.ApplicationIconBadgeNumber = 3 - maxPageVisited;
so that it is effectively showing the number of 'unviewed' panels in the application for the last execution.

You can download the MonoDevelop solution to try it for yourself. The c# files are also listed below for your perusal: