Posts Tagged MonoDevelop

Being a .NET developer in a Mac OSX world: serializing XmlDates

I blogged before on differences in implementation between the Mono and the Microsoft implementation of the .NET framework. In this post I investigate a difference in XmlSerialization.

Dates in XSD

When you write an XSD you have (at least) 3 options to use dates and/or times:

Most of the time you probably choose the “dateTime”, since that maps nicely to the DateTime type in .NET. But you might choose “date” for a birthday for example, and you might even choose “time” for uh, well for a time of some sort…

For his post I’ll use the following XSD. It’s a bit contrived but I like this better than “MyDate” and “ADateTimeField”:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="Book" type="BookType"></xsd:element>
 
  <xsd:complexType name="BookType">
    <xsd:sequence>
      <xsd:element name="Title" type="xsd:string"/>
      <xsd:element name="Price" type="xsd:float" nillable="true"/>
      <xsd:element name="PrintedAt" type="xsd:date"/>
      <xsd:element name="SoldAt" type="xsd:dateTime"/>
      <xsd:element name="WillReadTodayAt" type="xsd:time"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

Generate classes from your XSD

Both Mono and Microsoft have command-line tools that generate classes from your XSD. Very convenient and a good thing to do when you need simple entities. We did this in a project where we had both C# and Java code. On both sides we generated the classes from the same XSD.

The syntax of both tools is more or less the same:

xsd book.xsd /classes /namespace:BookStore.Books

will work on both systems.
The outcome of both generators is quite different. The Mono version uses public fields, the MS version use properties with back-up private fields. They both adorn the fields/properties with attributes from the XmlSerialization namespace.
For Microsoft it looks like this:

namespace BookStore.Books {
    using System.Xml.Serialization;
 
    ///
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlRootAttribute("Book", Namespace="", IsNullable=false)]
    public partial class BookType {
 
        private string titleField;
        private System.Nullable priceField;
        private System.DateTime printedAtField;
        private System.DateTime soldAtField;
        private System.DateTime willReadTodayAtField;
 
        ///
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string Title {
            get {
                return this.titleField;
            }
            set {
                this.titleField = value;
            }
        }
 
        ///
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
        public System.Nullable Price {
            get {
                return this.priceField;
            }
            set {
                this.priceField = value;
            }
        }
 
        ///
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="date")]
        public System.DateTime PrintedAt {
            get {
                return this.printedAtField;
            }
            set {
                this.printedAtField = value;
            }
        }
 
        ///
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public System.DateTime SoldAt {
            get {
                return this.soldAtField;
            }
            set {
                this.soldAtField = value;
            }
        }
 
        ///
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="time")]
        public System.DateTime WillReadTodayAt {
            get {
                return this.willReadTodayAtField;
            }
            set {
                this.willReadTodayAtField = value;
            }
        }
    }
}

That could have been a bit more readable by removing all the fully-qualified namespaces (since there is a “using” at the top), the empty comments and the back-up fields (if you generate for .NET after version 3).

For Mono it is like this:

namespace BookStore.Books {
 
    ///
    [System.Xml.Serialization.XmlRootAttribute("Book", Namespace="", IsNullable=false)]
    public class BookType {
 
        ///
        public string Title;
 
        ///
        [System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
        public System.Single Price;
 
        ///
        [System.Xml.Serialization.XmlElementAttribute(DataType="date")]
        public System.DateTime PrintedAt;
 
        ///
        public System.DateTime SoldAt;
 
        ///
        [System.Xml.Serialization.XmlElementAttribute(DataType="time")]
        public System.DateTime WillReadTodayAt;
    }
}

Much more concise. But with an important omission: the Price has the right XmlAttribute, but should have been defined as “Nullable”. I’ve seen some remarks on this in the mailing-list/forum for Mono, but could not find out if this was already fixed. So I use the Microsoft XSD.exe whenever my XSD changes, copy paste the result to my MonoDevelop environment and recompile. I would rather call the MonoXSD on the background whenever my XSD changes (has anyone used scripts as Custom Tools in MonoDevelop?) so that the class gets re-generated automatically. Maybe the upcoming Mono 2.8 will fix it.

It’s all a DateTime

As you can see, all the fields are generated as DateTimes. Makes sense, since there is nothing else in the framework to hold time-related information. So what happens when you read an Xml file and serialize the Xml into a Book object?

Take this Xml:

<Book>
    <Title>How to be a Mac Developer</Title>
    <PrintedAt>1965-02-16</PrintedAt>
    <SoldAt>1965-02-16</SoldAt>
    <WillReadTodayAt>11:00:01</WillReadTodayAt>
</Book>

And process it with this code:

    class MainClass
    {
        public static void Main (string[] args)
        {
            string bookXml = @"
            <Book>
                <Title>How to be a Mac Developer</Title>
                <PrintedAt>1965-02-16</PrintedAt>
                <SoldAt>1965-02-16</SoldAt>
                <WillReadTodayAt>11:00:01</WillReadTodayAt>
            </Book>
            ";
 
            BookType book = (BookType) ToObject(bookXml, typeof(BookType), Encoding.Default);
            Console.WriteLine("PrintedAt:{0}", book.PrintedAt);
            Console.WriteLine("SoldAt:{0}", book.SoldAt);
            Console.WriteLine("WillReadAt:{0}", book.WillReadTodayAt);
            Console.ReadLine();
        }
 
        public static object ToObject(string xml, Type xmlObjectType, Encoding encoding)
        {
            MemoryStream xmlStream = new MemoryStream(encoding.GetBytes(xml));
            StreamReader reader = new StreamReader(xmlStream, encoding, false);
            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.CloseInput = true;
            XmlReader xmlReader = XmlReader.Create(reader, readerSettings);
            XmlSerializer xmlSerializer = new XmlSerializer(xmlObjectType);
            return xmlSerializer.Deserialize(xmlReader);
        }
    }

Different ideas on default dates

You get this output in Windows (running the exe build by MonoDevelop directly on my VMWare-WindozeXP):
Screen shot 2010-09-21 at 11.26.27 AM

And this output on the Mac:
Screen shot 2010-09-21 at 11.30.34 AM

Interesting difference, right? Windows sets the date part of “WillReadTodayAt” to DateTime.MinValue and Mono assumes it is today. It doesn’t matter that much, since I’m going to ignore the date-part anyway for that property.
The time part of the date-olny property “PrintedAt” is set to “12:00:00AM” in Windows and “00:00:00″ in Mono. Again, I’m going to ignore the time-part, but what will happen when I compare dates for equality? I prefer the Mono setting.

Invalid time data

Take this slightly modified Xml:

<Book>
    <Title>How to be a Mac Developer</Title>
    <PrintedAt>1965-02-16</PrintedAt>
    <WillReadTodayAt>2010-09-21T11:00:01</WillReadTodayAt>
    <SoldAt>1965-02-16</SoldAt>
</Book>

Running this on Mono result in an FormatException: Screen shot 2010-09-21 at 11.41.53 AM
Fair enough, the data in the xml is not a Time, it is a DateTime. So an exception makes sense.

Wonder what Windows will do? After you have started an instance of Visual Studio to see the error, you get this:
Screen shot 2010-09-21 at 11.45.46 AM

So both platforms agree that the data is invalid. Unfortunately the position that Windows gives us is right after the offending data, at not before as I was expecting. So it took some time (way more than an hour) to realize that the problem was not in the “SoldAt”, but in the “WillReadTodayAt” just before it. Be warned.

Invalid date data

Now pass in a date-with-time on the field that expects only a date:

<Book>
    <Title>How to be a Mac Developer</Title>
    <PrintedAt>1965-02-16T08:01:03</PrintedAt>
    <WillReadTodayAt>11:00:01</WillReadTodayAt>
    <SoldAt>1965-02-16T09:00:02</SoldAt>
</Book>

Mono doesn’t like it. Same error as before, no indication on what line and what xml-tag, alas.
Windows doesn’t like it either. Same error as before, positioned right before “WillReadTodayAt”.

Conclusions

There’s a big difference in the C# classes that get generated. The Mono implementation is missing the support for nullables, the MS implementation is a bit too verbose.
The handling of incorrect date/time information is okay in both systems.
The date-part in a xsd:time gets defaulted to “1-1-1″ in MS and “today” in Mono. The time-part gets defaulted to “0:0:0″ in Mono and “12:0:0AM” in MS.

The code for this article

, , ,

No Comments

Being a .NET developer in a Mac OSX world: connecting Mono to SQL Server

How did I get here?

I’m a long time Windows developer. Started with VB3 en FoxPro and such, and couldn’t imagine needing another plaform. Like the Mac that my geeky artistic brother-in-law loved so much. Windows was cool and I knew all about it and the Mac was for people that didn’t know how to use a PC.

The dawn of a new era

Then I came with my current employer and they provided a mobile phone and a laptop of course (like all companies in Dutch IT do). But this was about an iPhone and a MacBook Pro.
I decided to leave OSX on the machine, although I could have erased the disk and installed Windows Something, it’s got an Intel processor after all.
But leaving OSX on it, meant I had to install VMWare and run Windows and Visual Studio and such within that. And even though my machine is pretty fast, you notice the performance hit.

I kept trying, and started to like OSX and the applications on it. But what I liked most of all: hardly any updates and no reboots. I shut down my machine once a week or once every two weeks because I feel it’s something I should do. But I don’t have to: OSX keeps on running. Just close the lid, simply know that everything is suspended and know that everything will run as before when you open the lid the next day.

Amazing! I would shut down my Windows machine every night, just to make sure I had a stable system the next morning. My wife still has a Windows machine and to ensure that she makes backups every day, we configured the backup software to run “on system shutdown”. Because that is what you do every day, as a Windows user.

And then there was Mono

I’ve written about the Mono project before, albeit in the context of MonoTouch and iPhone development. Mono brings .NET to a lot of platforms, including Mac OSX. And it is really good. The Mono team is really close behind the Microsoft team in porting new API’s and Framework versions. .NET 4.0 is recently available on Windows, but Mono is already compatible.
And the amazing thing is that you can take your Windows assemblies and use them straight away on OSX! That might not be very imported for assemblies that you have the sources for, but it is very convenient for third party libraries you use, like log4net (although that has a Mono version) and Rhino Mocks.
And one of the best things the Mono team delivers is MonoDevelop: an excellent IDE for .NET development that will feel really comfortable when you come from Visual Studio.

Being a .NET developer, not necessarily a Windows developer

I still like the .NET framework, but I no longer feel that automatically implies I am a Windows developer. There are so many good tools that allow you to do everything on the Mac that you are normally doing on Windows. So I decided that in the new project I recently started (in which we will deliver on Windows) I will try to go as far as possible to develop my code on Mac OSX.
I will blog about my experiences in a series of posts. This first one is about connecting to SQL Server.

I can’t do without SQL Server

We will deliver our project an a SQL Server database, so it makes sense to use that during development also. It’s not that you have to, there are other options. If you have something like a nice Data Access Layer, you can run any SQLLite or MySql database and easily move to SQL Server later.
There also is a file-based no-install version of SQL Server these days that might run on Mono. Haven’t tried it yet, but could be promising.
But if you need SQL Server, you can still work in MonoDevelop in your comfortable Mac environment.

Inside the VM

SQL Server will run on Windows in your VM, but that will be the only thing you’ll need your VM for. SImply minimize the window after all the configuration is done and don’t think about it anymore.

Step one: opening up your Windows

You need access to your VM from your Mac, so you have to open up some things.

Go into Control Panel and choose Windows Firewall. Go to the advanced tab and add some ports. Port 1433 for SQL Server over TCP/IP and port 1434 for SQL Server over UDP. Maybe you can do without the UDP version, haven’t tried yet.

Firewall Exceptions

Step two: configure SQL Server

First, make sure the SQL browser is running.

SQL Browser

Then enable TCP/IP in the Client Protocols

Protocols

And check that the Default Port is on 1433.

Poort

In SQL Server Management Console open the properties of the server and make sure you have mixed authentication.

Mixed Authentication

Step three: connect from your code or MonoDevelop

In your connection string use the IP-address of your VMWare instance. Something like

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<connectionStrings>
		<add name="dossiers" connectionString="Server=172.16.86.128;Database=mydefaultdatabase;User ID=sa;Password=bladiebla" providerName="System.Data.SqlClient"/>
	</connectionStrings>
</configuration>

That is! You can test your connection from MonoDevelop: Go to Tools/Database/Add database connection/SQL server:
MonoDevelopDatabaseTools
Screen shot 2010-07-18 at 9.33.05 PM

, , , ,

4 Comments

Building iPad applications using MonoTouch: the UISplitView

First of all, I bow deeply to the people that bring us MonoTouch. It was less than 2 days after the introduction of the iPad and the release of a beta of the iPhone/iPad SDK that a version of MonoTouch (and MonoDevelop) was available that covers the new API.

To build iPad apps, you need a couple of things that are all listed on the MonoTouch iPad page.

I couldn’t wait to build something that used the way bigger UI-surface that the iPad has. The first thing that attracted my attention when I fired up the Interface Builder was the UISplitViewController.
The idea behind the SplitView is that you have some navigation on the left (like a NavigationController, or just a TableViewController) and a data view on the right. That is, only when the display is in landscape mode. As soon as you turn the iPad (the iPad SImulator, of course) to portrait, the left side disappears and all the screen is available to the data view.
That behaviour is entirely taken care of by the UISplitViewController, at least if you stick to the conventions!

I decided to make a simple app with a list of places on the left side, and a map-view on the right:

LandscapePortait version of the UI

The obvious start

When you start a new iPad application from the New Project menu, you get the well-known set-up of files in your project. Double-click the MainWindow.xib to fire up Interface Builder. Then drag the Split View Controller from the Library Window and drop it below the Window object in de MainWindow:
MainWindow

As you can see, you get a lot for free, including stuff you don’t want. Now it gets less obvious. After clicking Cmd-Backspace a thousand times and positioning my cursor everywhere, I had an epiphany. Since the SplitViewController won’t work without two other controllers I had to add something new before I could remove the old!

No kidding, that was really the solution. So I added a UITableViewController, Interface Builder magically removed the default NavigationController, and I added a MKMapView to the view-controller on the right.

This is the result:

SplitView I then added outlets to the AppDelegate for the map, the tableview and the splitview:

Outlets

The less obvious code

To make the controllers react properly when the orientation of the UI changes, you need to override the ShouldAutorotateToInterfaceOrientation() method in each of your controllers. How do you do that?
The first step is to add a class to your project, make it inherit from your controller (a UITableViewController in my case) and override the ShouldAutorotateToInterfaceOrientation() method as below:

public class PlacesController : UITableViewController
{
	public PlacesController ()
	{
	}
 
	public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
	{
		return true;
	}
}

Repeat the step for the second controller:

public class Map : UIViewController
{
	public Map ()
	{
	}
 
	public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
	{
		return true;
	}
}

This should still compile. But it doesn’t work yet.

The even less obvious link from the code to the UI

The objects in the Interface Builder are standard objects. They need to be of the types that we just defined, to make the overridden methods work. See we need to make our own classes known to Interface Builder. That’s done by adding a Register-atribute and overriding the constructor with one that accepts an IntPtr.
The Map class changed in something like this:

[Register("Map")]
public class Map : UIViewController
{
	public Map ()
	{
	}
 
	public Map(IntPtr p) : base(p)
	{
	}
 
	public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
	{
		return true;
	}
}

The final step is setting the right class on the controller. Go to Interface Builder, select the UIViewController (e.g.) in the MainWindow, then go to the Inspector Window and type your classname over the default one:

Inspector

And then it works! The map will re-orientate itself when the iPad is turned, and the Table View appears and disappears.
Of course you want some location data in the table and the map to show the locations when clicked on, but that’s all in the code you can download.

Enjoy making software for a device that makes you need to rethink the way you always made software…!!!

Mmmmh. re-reading that last line, I realize it’s a little hard to read. What I meant was something like Joe Hewitt wrote.

, , , , ,

4 Comments

Building iPhone applications using MonoTouch, howto: using a view without a controller

Of course, a view without a controller is not very useful in itself, but in this post I want to show you how I solved a small re-usability problem.

I’m working on a small open-source project on Codeplex that aims to build a player for the Hanselminutes podcasts. It is nothing very special, but it gives me a nice playground to find out new stuff.

So there is a “Loading playlist” message and a “Buffering audio” message displayed at the appropriate moments. You can do that in a lot of ways, but in this application, a semi-transparent view was chosen that is overlaying the current view. It has a text (of course) and a UIActivityIndicatorView (who comes up with these names????).

I try to follow three rules when building the UI:

  1. All the UI is done with the Interface Builder. That allows me to leave the actual design to someone who knows designing.
  2. Every view is in a separate NIB. That way not all the UI has to be loaded at startup, which improves user-perceived performance
  3. Loosely couple the view, to make reuse easier. That means a simple interface (as in ‘programming interface’) to the rest of the world, and all the view-related code inside the NIB

In this case I want a view that can be called from different controllers (re-usability), so when I add a file to my MonoDevelop project I choose “View Interface Definition”:

Screen shot 2010-01-25 at 8.34.03 PM

It’s no so different form what you do (at least, what I do) most of the time when you choose View Interface Definition with Controller. You add your UI-elements, define some outlets, but then  you want to activate this view from some controller, any controller.

What I came up with, is the following.

public class UIHelper
{
  UIViewController _controller;
  BusyView _busyView;
  public UIHelper (UIViewController controller)
  {
    _controller = controller;
    NSArray views = NSBundle.MainBundle.LoadNib("BusyView", _controller, null);
 
    _busyView = new BusyView(views.ValueAt(0));
    _controller.View.AddSubview(views);
    _controller.View.SendSubviewToBack(_busyView);
  }
}

It is a helper class that loads the view at construction time. It gets passed in the controller that will display the view. Then I load the NIB where the view is in. This gives me back an array. Of what? Well as the documentation says:

An array containing the top-level objects in the nib file. The array does not contain references to the File’s Owner or any proxy objects; it contains only those objects that were instantiated when the nib file was unarchived. You should retain either the returned array or the objects it contains manually to prevent the nib file objects from being released prematurely.

So you get the top-elements (actually: the IntPtr’s of them) from the NIB. In a file with only one view the first one is probably (…fingers crossed) the right one.
I add the view to the SubViews of the controller and make sure it does not show before it was meant to.

Showing the view

Whenever I need the view to display I call:

	_busyView.Show(message);
	_controller.View.BringSubviewToFront(_busyView);

The first line calls a method on the partial class in the NIB to set the text of a label. The second line makes the view visible.

What’s not to like about this solution

Well, the magical string with the name of the NIB, “BusyView”. And the magical number 0 the denotes the right object in the list of objects in the NIB.

Any ideas for improvement? Please react!

Download the code

, , , , , ,

5 Comments

Building iPhone applications using MonoTouch, part 5: software design considerations

In the previous 4 posts (4, 3, 2, 1) I gave a lot of attention to the overall structure of an iPhone application. In this post I want to talk about a topic that is more concerned with general software design issues: where do I do what?

Get SOLID

There are two things that I always try to keep in mind when making software: loose coupling and tight cohesion. In other words:

  1. make sure your classes don’t know things that they don’t need to know
  2. make sure your classes are good at one thing and one thing only

These guidelines are part of the 5 SOLID principles of class design by Uncle Bob Martin:

  1. Single Responsibility Principle
  2. Open Closed Principle
  3. Liskov Substitution Principle
  4. Interface Segregation Principle
  5. Dependency Inversion Principle

This stuff is really interesting and sort-of scientific, but it is also like making your database comply to the 5-th Normal Form: nobody does that. You’re happy with a 3rd Normal Form database. So I’m happy when I see code that complies with at least two of the above principles.

So what I do when building my iPhone apps is constantly asking myself: should this code be in this place? Sometimes I know right away that the answer is No, but still leave it there until I have a better idea on where to put it then. And with the (for me) rather unusual structure that the Cocao Framework forces upon me, it may take some time before I eventually find out where to put it.

Let me give you an example.

When you want to load data into a UITableView you must create a UITableViewDataSource and assign that to the DataSource property of your UITableViewController. Like this:

public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
	tableView.DataSource = new LeesPlankjeDataSource();
	window.AddSubview (tableView);
	window.MakeKeyAndVisible ();
	return true;
}

The class instantiated at line 3 is something like this:

public class LeesPlankjeDataSource : UITableViewDataSource
{
	private string[] woordjes = new string[] {"aap", "noot", "mies"};
	public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
	{
		UITableViewCell cell = tableView.DequeueReusableCell("plankje");
		if (cell == null)
		{
			cell = new UITableViewCell(UITableViewCellStyle.Default, "plankje");
		}
		cell.TextLabel.Text = woordjes[indexPath.Row];
		return cell;
	}
 
	public override int RowsInSection (UITableView tableview, int section)
	{
		return woordjes.Length;
	}
}

On line 3 you see the actual “data store”, and on line 4 an important override. This method gets called by Cocoa when loading data in your UITableView. So the controller has a data source and the appropriate methods get called by the framework.

On to a more realistic implementation

If I want to advance my class a bit, I could imagine that the data is not a fixed array of strings, but gets passed in at construction time. Maybe I read from a file or from a URL.

That changes my class to this:

public class LeesPlankjeDataSource : UITableViewDataSource
{
	private string[] _dataStorage;
 
	public LeesPlankjeDataSource(string[] data)
	{
		_dataStorage = data;
	}
 
	public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
	{
		UITableViewCell cell = tableView.DequeueReusableCell("plankje");
		if (cell == null)
		{
			cell = new UITableViewCell(UITableViewCellStyle.Default, "plankje");
		}
		cell.TextLabel.Text = _dataStorage[indexPath.Row];
		return cell;
	}
 
	public override int RowsInSection (UITableView tableview, int section)
	{
		return _dataStorage.Length;
	}
}

And the main.cs gets these lines:

	string[] woordjes = File.ReadAllLines("woordjes.txt");
 
	tableView.DataSource = new LeesPlankjeDataSource(woordjes);

Make sure when you have files that you want to be deployed with your app to set the build-action on the file to “content”:

BuildActionThat’s all neat. The DataSource gets it data from the outside and doesn’t care if it comes from a file or a network-connection.

So now we want some action when the user taps a row. You have no choice but to implement this in a delegate (a UITableViewDelegate of course) and then override the RowSelected() method. This method is called for you by Cocoa and as parameters you get a UITableView that the tapping happened on and the Row number that was tapped:

public class LeesPlankjeViewDelegate : UITableViewDelegate
{
	public override void RowSelected (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
	{
	}
}

But what can I do in this method? Let’s say I want to do a MessageBox-ish thing to show what word was chosen. All I have is an index to the row in my data source. But I don’t have the data source itself in this class. I need some way to acces my original data store.

I could do somehting like this:

public override void RowSelected (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
	string message = tableView.DataSource.GetCell(tableView,  indexPath).TextLabel.Text;
	using (var alert = new UIAlertView ("", message, null, "OK", null))
	{
		alert.Show ();
	}
}

So I ask the TableView for its data source, then ask the data source to give me the cell that is on the given index, and then ask the cell for the text of the label. It works, but it is butt-ugly. Why? Because now the delegate knows about the data source too. And I think it shouldn’t, because all the delegate needs to do is handle UI-interactions from the user. It should say “Hey, someone tapped me on this row, do something with it” and then leave the actual work to someone else.

I think it would be reasonable to leave the work to the controller. For me, a controller is always the man-in-the-middle, doing the real work brokering between the model and the view. But if I choose that, I have to pass in the controller when constructing the Delegate, like this:

tableView.Delegate = new LeesPlankjeViewDelegate(tableViewController);

And since the tableViewController is only known so far in the Interface Builder, I have to make the controller available in my code by creating an outlet. Sigh…. even more code in my FinishedLaunching() method. I don’t want that, I want to hook up UI-parts with each other using the Interface Builder, not in code.

So, what to do now? I don’t know yet. Let me first deal with a problem that I didn’t tell you about yet. It is in the code of the LeesPlankjeDataSource. I gave my LeesPlankjeDataSource a constuctor that accepts a string array, thereby enabling me to pass in the data that the data source needs to build a UITableView from.

The problem is, that the UISearchDisplayController re-uses my UITableViewController, including the DataSource. When I click search, it first simply overlays my view, but when I start typing in the search box, the ShouldReloadForSearchString () method gets called and that one resets the SearchResultDataSource with a filtered version of my LeesPlankjeDataSource:

public override bool ShouldReloadForSearchString (UISearchDisplayController controller, string forSearchString)
{
	Console.WriteLine("In ShouldReloadForSearchtring");
	controller.SearchResultsDataSource = new LeesPlankjeDataSource(forSearchString);
	return true;
}

And how am I gonna feed this baby with the right data? How is the SearchResultsDataSource going to get a filtered list of the words in my “woordjes.txt” file? I chose to filter by using an overloaded constructor, but I could move that code to a normal method. That allows me to use the other constructor, passing in the data as before in the main.cs:

public override bool ShouldReloadForSearchString (UISearchDisplayController controller, string forSearchString)
{
	Console.WriteLine("In ShouldReloadForSearchString");
	var woordjes = ?????????
	var data = new LeesPlankjeDataSource(woordjes);
	controller.SearchResultsDataSource = data.FilterOn(forSearchString);
	return true;
}

But where am I gonna get the “woordjes” variable from? Should I load the file again, like I did in main.cs? Or maybe my DataSource should know something about the model? In that case I will not pass data from the outside, but let the DataSource find out itself where to get the data. But that is so against the Dependency Inversion Principle (or Inversion of Control)! If classes depend on other classes, these dependencies had best be passed in from the outside, probably on construction time.

Shoot, I love the IoC pattern. Should I let it go, for the sake of simplicity? After all, I argued before that even the MVC-pattern was maybe to much of a burden for the simple applications we build on the iPhone most of the time.

For tonight, I give up. The code you can download contains the solution that goes against IoC, but works none the less.

I would love to hear your ideas about how to build iPhone applications that are tightly coherent and loosely coupled. I know that we can get in some philosophical or religious discussions, but we’ll see what to do then. I just want to learn from you guys, as much as I want to teach you where I can.

P.S.
Thanks to Alex York’s excellent post (see his comment below) I was able to improve on my code. I had seen the idea of nesting the DataSource and Delegate into the UITableViewController before, but didn’t like it then. That dislike mostly came from the fact that you have to inherit from another class. There is no tighter couling between two classes then inheritance, so I believe you should only use it when absolutely necessary. Well, by now I think that it is absolutely necessary to inherit from the classes in the Cocoa framework. It is simply the way you work.

When working on the new solution I also renamed some classes (no more Dutch names, only Dutch words in the data…) and added a class that implements the model:

public class WordsModel
{
	private List _dataStorage;
 
	public WordsModel ()
	{
		_dataStorage = File.ReadAllLines("woordjes.txt").ToList();
		_dataStorage.Sort();
	}
 
	public string[] Data {
		get { return _dataStorage.ToArray();}
	}
 
	public string[] FilterOn(string searchText)
	{
		searchText = searchText.ToLower();
		var result = _dataStorage.Where(t =&gt; t.ToLowerInvariant().StartsWith(searchText));
		return result.ToArray();
	}
}

It is the place where the knowledge of words, where they come from and how you filter them, resides.

But Alex’s solution did not solve the problem that is typical of the use of the UISearchDisplayController: you have two instances of your DataSource: the one for your initial view, that just displays all the data (words in my case), and the one that is called upon by the UISearchDelegate when you start to search and filter.

I solved this by implementing a general WordsDataSource that uses the WordsModel and has a constuctor for normal use and for filtering:

public class WordsDataSource : UITableViewDataSource
{
	private WordsModel model = new WordsModel();
	private string[] _dataStorage;
 
	public WordsDataSource()
	{
		_dataStorage = model.Data;
	}
 
	public WordsDataSource(string filter) : this()
	{
		_dataStorage = model.FilterOn(filter);
	}
 
	public string GetAt(int position)
	{
		return _dataStorage[position];
	}
 
	public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
	{
		UITableViewCell cell = tableView.DequeueReusableCell("plankje");
		if (cell == null)
		{
			cell = new UITableViewCell(UITableViewCellStyle.Default, "plankje");
		}
		cell.TextLabel.Text = _dataStorage[indexPath.Row];
		return cell;
	}
 
	public override int RowsInSection (UITableView tableview, int section)
	{
		return _dataStorage.Length;
	}
}

It inherits (yep I used the I-word) from UITableViewDataSource so can be called upon by the Cocoa framework when rendering the data for the UITableView.

And then I used that class in two places:

  1. as an internal property in my WordsTableViewController
  2. as a helper-class in the delegate of the UISearchDisplayController.
[MonoTouch.Foundation.Register("WordsTableViewController")]
public partial class WordsTableViewController : UITableViewController
{
    // Constructor invoked from the NIB loader
    public WordsTableViewController (IntPtr p) : base (p)
    {
    }
 
    // The data source for our TableView
    private WordsDataSource TableDataSource
    {
	get { return this.TableView.DataSource as WordsDataSource; }
	set { this.TableView.DataSource = value; }
    }
 
    // This class receives notifications that happen on the UITableView
    class TableDelegate : UITableViewDelegate
    {
	WordsTableViewController parentView;
        public TableDelegate (WordsTableViewController tableViewController)
        {
		parentView = tableViewController;
        }
 
        public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
        {
		string selectedWord = parentView.TableDataSource.GetAt(indexPath.Row);
		using (var alert = new UIAlertView ("Selected", selectedWord, null, "OK", null))
			alert.Show ();
        }
    }
 
    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
 
        TableView.Delegate = new TableDelegate (this);
        this.TableDataSource = new WordsDataSource ();
    }
}
[MonoTouch.Foundation.Register("WordSearchDelegate")]
public class WordSearchDelegate : UISearchDisplayDelegate
{
	public override bool ShouldReloadForSearchString (UISearchDisplayController controller, string forSearchString)
	{
		UITableViewDataSource data = new WordsDataSource(forSearchString);
		controller.SearchResultsDataSource = data;
		return true;
	}
}

I’m pretty happy with what I got by now. You can download the new version, if you like.

, , , , , , ,

9 Comments