Posts Tagged .NET
Being a .NET developer in a Mac OSX world: connecting Mono to SQL Server
Posted by Richard de Zwart in .NET, technical on July 12th, 2010
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.
Step two: configure SQL Server
First, make sure the SQL browser is running.
Then enable TCP/IP in the Client Protocols
And check that the Default Port is on 1433.
In SQL Server Management Console open the properties of the server and make sure you have 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:


Windows Phone 7 Developer Hub
Posted by Erik Sanders in .NET, mobility on June 11th, 2010
Ik heb vorige week de Windows Phone 7 Developer Hub bijgewoond met de verwachting in een keer een compleet overzicht te krijgen van de nieuwe Microsoft smartphone. Ik heb niet de intentie in deze blog alles even uit te leggen, dat kan Microsoft prima zelf. Ik wil hier alleen het beeld dat ik heb gekregen schetsen vanuit het perspectief van de gebruiker, ontwikkelaar en business.
Gebruiker
Ik heb de telefoon niet zelf bedient maar heb toch een redelijke indruk gekregen. Zelf ben ik een iPhone gebruiker en zie wel wat verbeteringen en interessante ontwikkelingen
- Het gebruik is opgezet rond hubs. Er is bijvoorbeeld een social hub, op deze hub komt alle sociale media bij elkaar en bieden ze mogelijkheden tot integratie. Er zijn dus geen aparte ingangen meer voor linked-in, contacts, facebook e.d. maar alle informatie wordt gebundeld weergegeven.
- Drie verplichte toetsen op de telefoon waarbij naast de enige toets op de iPhone om applicaties te starten er ook een zoek toets is die de standaard zoek functionaliteit heeft maar ook kan worden gebruikt voor zoeken binnen de applicatie. Daarnaast is er de back toets hiermee kan je terug naar de applicatie die een andere heeft aangeroepen. Een typisch voorbeeld waar ik mij vaak aan heb geërgerd is: Je leest je mail daar staat een link in die je opent en vervolgens zit je in safari. De enige manier om die te verlaten is stoppen en je mail opnieuw opstarten.
- Het metro concept van de user interface (Kort samengevat: beperkt grafisch en meer tekst) aangevuld met een panorama view en pivot view is wel een verfrissende aanpak waarbij je direct informatie ziet die je nodig hebt en niet alleen een menu.
Ontwikkelaar
Voor een .Net ontwikkelaar is er eigenlijk niets nieuws. Je kunt namelijk gewoon ontwikkelen met je opgedane kennis in XAML (WPF en Silverlight) in je vertrouwde ontwikkelomgeving. Ik wil echter wel een aantal punten benadrukken
- Een virtuele machine met de phone OS op de ontwikkel PC dus geen emulator of simulator dus betere test omgeving
- Naast API’s die telefoonfunctionaliteit geven zijn er ook API’s voor bijbehorende services in de cloud
- Er is een gratis omgeving bestaande uit visual studio express voor ontwikkelaars en Blend express voor designers
Het lijkt mij een eitje om de look en feel van de quote eetgids (een iphone app gemaakt door luminis) te bouwen voor W7
Business
- Beperkt aantal modellen en veel verplichte onderdelen zoals een grafische processor en sensoren als GPS e.d. Dit maakt de herkenbaarheid groter
- Geen exclusieve contracten met KPN’s en de TMobile’s
- Vergelijkbare appstore als Apple waarin een applicatie gegarandeerd binnen dagen wordt geplaatst.
- Office applicaties en zelf een sharepoint front-end
Het evenement
Het evenement zelf was wat mij betreft teleurstellend. Op een developer event verwacht ik concrete presentaties met duidelijke concepten en voorbeelden. Helaas bleven de presentaties erg oppervlakkig ook al aangemoedigd door de vele bizarre vragen die gesteld werden. Wat mij wel duidelijk is geworden dat Microsoft serieus hun best doet om weer aansluiting te vinden of zoals ze zelf beweren een voorsprong te nemen maar dat ze nog heel goed hun best moeten doen om alles in de winkels te krijgen voor de kerst.
Building iPad applications using MonoTouch: the UISplitView
Posted by Richard de Zwart in .NET, mobility, technical on April 3rd, 2010
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:
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:

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:
I then added outlets to the AppDelegate for the map, the tableview and the splitview:
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:
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.
ASP.NET MVC: Editor Templates
Posted by Richard de Zwart in .NET, technical on March 27th, 2010
Last week I sat with a colleague who is building an ASP.NET MVC application. Since I’m currently on a not-so-interesting application, I was really jealous and decided to out-smart him, showing off with some hard-core MVC code.
Here we go.
What’s your problem, dude?
Well, we are all very Web 2.0 and so, using Ajax and jQuery and maybe even single-page-applications, but on almost any site I fill in a form, a textbox is just a plain textbox. You can type text, like digits and characters, even if they need only my age. Come-on guys, an age is expressed as a number, so why allow me to type in anything else but digits?
Sure, you validate at the server and maybe even at the client, but still I can make errors that I have to fix later. Please, help me by preventing the error up-front.
The solution, part 1: jQuery-plugin
The solution starts with a nice jQuery-plugin by Paulo P. Marinas called jQuery AlphaNumeric. There is also a nice MaskedInput-plugin, but I found that too limiting.
It is simple to hook it up to my textbox:
$("#mytextboxid").numeric();
And voila, nothing but digits allowed!
Cool, I want that on all the fields that I know are numbers, but I surely don’t want to repeat the above Javascript.
The solution, part 2: EditorFor
Starting with MVC 2 there is an Html-helper called Html.EditorFor(). It uses a lambda as a parameter and derives a lot of interesting information from that. If you type
<%= Html.EditorFor(model => model.Length) %>
You get code generated like this:
<div class="editor-field"> <input id="Length" name="Length" type="text" value="7" /></div>
De ViewEngine determines that you have a Integer field, generates a textbox with the name/id of the field and sets the value. If you have client-side data-validation on, you get the extra span-tag for the validation message. More on that in a minute. Maybe this doesn’t look like much, but you get different output for different field types; like radio-buttons for a Boolean field and appropriate formatting for a Decimal field.
The EditorForModel() method even generates code for all the fields on your class.
The solution, part 3: Turning validation on
I was hoping that the EditorFor() method would be all I needed. It supports validation, both client-side and server-side, and (as argued before) what better client-side validation then preventing false input to begin with!
Alas, it doesn’t do that. But in combination with DataAnnotations (Scott Guthrie has a nice blog about that) it adds range-checks to your Integer-field. So if I can limit the characters that can be typed into my textbox with a line of jQueury and can check for the upper- and lower-limit of the value with client-side validation, then I’m happy!
But that means that I have to change the behavior of the EditorFor() method. Can that be done? Well……, sort of.
The solution, part 4: Convention over configuration
The nice thing about the MVC framework is that it takes convention over configuration, meaning you do not have to configure anything to get a working application, as long as you adhere to the rules/conventions. Nothing new for Ruby on Rails programmers maybe, but for me as a long-time Microsoft-ee it is close to revolutionary.
In this case, the interesting convention is that there can be a EditorTemplates sub-directory in my View directory. If it is in a normal View directory it works for only those Views, but if you put it in the Shared directory it works for all your views:

If you have a user-control in there named Decimal.ascx it will be used everywhere the EditorFor() encounters a Decimal property. There is a bunch of default user-controls that are described by Brad Wilson.
What I would have liked to be “The solution, part 5: Overloading the decimal template”
Since I like the server-side formatting of the default template, and only want to add some jQuery, I would have liked to do the following:
<%@ Control Language="C#" AutoEventWireup="true" Inherits="System.Web.Mvc.ViewUserControl" %> <%= Html.EditorFor(Model) %> <script type="text/javascript"> $("#mytextboxid").numeric(); </script>
I simply delegate to the original implementation, passing in the data I have available. But that doesn’t work since the EditorFor() expects a lambda as a first parameter. And I don’t know any way to convert the data I have at that point in time to a lambda. If you know, please tell me and you’ll be my hero (hmmmm, I hope it’s not going to be that colleague coming up with the solution, that would really ruin my post…).
The actual “The solution, part 5: Overloading the decimal template”
The best I could do was copying the default template for the Decimal from the blogpost of Brad Wilson. Yes that’s a shame, copying code, having to maintain code that isn’t even mine, not profiting of the improvements Microsoft makes in the default template. Nevertheless, here it is:
<%@ Control Language="C#" AutoEventWireup="true" Inherits="System.Web.Mvc.ViewUserControl" %> <script runat="server"> private object ModelValue { get { if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model) { return String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:0.00}", ViewData.ModelMetadata.Model); } return ViewData.TemplateInfo.FormattedModelValue; } } </script> <%= Html.TextBox("", ModelValue, new { @class = "text-box single-line" }) %> <script type="text/javascript"> $('#<%= ViewData.ModelMetadata.PropertyName %>').numeric({ allow: '<%= System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator %>'}); </script>
So, there is some server-side code that I copied, and then some client-side code I added myself.
There are two interesting things to mention about my own single line of code:
- The jQuery selector references the name of the property, thus guaranteeing that the javascript is coupled to the right text-box. Other solutions make you use a fixed class or prefix or postfix, but that only opens the possibility of name clashes. The name-property is available in the model-metadata. See the Bradd Wilson series mentioned above for more info
- The allowed character (the decimal separator) for entering money is retrieved from the CurrentCulture and not hard-coded. Of course.
As ScottGu would say: hope this helps.
Building iPhone applications using MonoTouch, howto: using a view without a controller
Posted by Richard de Zwart in .NET, mobility, technical on January 25th, 2010
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:
- All the UI is done with the Interface Builder. That allows me to leave the actual design to someone who knows designing.
- Every view is in a separate NIB. That way not all the UI has to be loaded at startup, which improves user-perceived performance
- 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”:
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!
Building iPhone applications using MonoTouch, part 5: software design considerations
Posted by Richard de Zwart in .NET, mobility, technical on November 21st, 2009
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:
- make sure your classes don’t know things that they don’t need to know
- 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:
- Single Responsibility Principle
- Open Closed Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- 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”:
That’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 => 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:
- as an internal property in my WordsTableViewController
- 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.
Building iPhone applications using MonoTouch, part 4: the UISearchDisplayController
Posted by Richard de Zwart in .NET, mobility, technical on November 3rd, 2009
In my previous post I wrote about the Interface Builder and things like outlets. Last night (with the help of some colleagues) I cracked one of the more advanced Classes in the Interface Builder: the UISearchDisplayController.
In the previous version of my application I had a UITableView and a UISearchBar. I hooked them up with some code and it worked fine. But I didn’t get the effect that you see in (for instance) the iPod application. When you scroll up, uncover the search-bar and start typing, the original view is greyed-out. And when your search gives no result, you get a “No Results” message. Like this:
For that, you need the UISearchDisplayController. This controller does the work of hooking up a couple of UI-elements for you:
- The search bar
- The view with the results from the search (called the searchContentsController)
- The delegate that handles all the events that come from the search bar and the results view (called the searchResultsDelegate)
- The data source that provides the data to search in (called the searchResultsDataSource)
- Your original view
When you drag a UISearchDisplayController and drop it at the top of your UITableViewController, all the outlets get connected to your controller automatically. Apparently the Interface Builder thinks that your class can play all these roles. This makes sense when you program Objective-C, since that language is quite capable of inheriting from lots of base classes (as is so eloquently explained in the Cocao With Love blog), but asks some more attention when used from MonoTouch.
Designers should not write code, and vice versa
I will explain again what Interface Builder does for you. Maybe you already know, but I had to get used to it, and have to keep reminding myself that you use it to, well, build interfaces. Nothing else. Interface Builder provides a clean separation between the GUI and the code, and that’s a good thing, right? Right. I love Design Patterns, and I try to convince as much progammers as possible to take at least notice of them. But iPhone apps are mostly very small apps with one or two screens, being very good in just one or two things. Do I need to implement this whole pattern for my simple app? Well, apparently. And so will you, so let me try to help you find out how to do some of these things.
Steps to follow
Begin with a UITableViewController. Then go to the Library Window, the Objects button and drag-n-drop a UISearchDisplayController just at the top of your UITableViewController.
In the MainWindow you will have the UISearchDisplayController added. Click it there, and then go to the Outlets-tab in the Inspector Window. You will see that all the outlets will be connected to your UITableViewController, except for the searchBar-outlet since that is of course connected to the SearchBar.
When you run your app, you will have the Table-View and the SearchBar above it. When you tap the text-field you will see the desired gray-out and the “No Result” if you enter some text. So far so good.
Providing the view with data
Now we need to hook up some of our own code to the events that the UISearchDisplayController fires. Let’s start with some data in our own TableView to filter on.
As said in one of my first posts, data for a view is delivered by a DataSource. In this case a UITableViewDataSource. So add a class to your project that inherits from UITableViewDataSource. Something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class LeesPlankjeDataSource : UITableViewDataSource { private string[] woordjes = new string[] {"aap", "noot", "mies"}; public LeesPlankjeDataSource() { } public LeesPlankjeDataSource(string filter) { woordjes = woordjes.Where(f => f.StartsWith(filter)).ToArray(); } 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; } } |
The complete code of this solution is at the bottom of this post.
The class has two constructors. The default constructor (at line 5) is called when initializing our own view, the constructor that takes a string (at line 9) will be called when filtering is started.
The GetCell() and RowsInSection() methods need to be implemented to make your data source work. The implementation is pretty straightforward. The GetCell() method will be called “RowsInSection” times. The call to DequeueReusableCell() is some trick to limit the amount of resources that your iPhone application will use. Just make sure you pass in some string that you reuse a few lines down.
To be able to set this datasource on the table-view we have to have some programmatic access to the view. Well, we did that before in the previous post. Go to Interface Builder, select the AppDelegate in the Library Window, add an outlet and connect it to your UITableViewController. Then you can have code like this in your main.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public partial class AppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication app, NSDictionary options) { tableView.DataSource = new LeesPlankjeDataSource(); // If you have defined a view, add it here: window.AddSubview (tableView); window.MakeKeyAndVisible (); return true; } // This method is required in iPhoneOS 3.0 public override void OnActivated (UIApplication application) { } } |
We simply set the DataSource on the tableView to our own DataSource and then add the tableView to the current window. Run your app and you will have some data in your view!
Building the delegate
Now we need some code to handle the events of the search bar. The most interesting event is “ShouldReloadForSearchtring()”. No that is not a typo, there really is an “S” missing in the method name. I filed a bug with the MonoTouch guys, so it is probably fixed in the next release, but we’ll have to live with it for now. And to be honest, that is not too hard.
Add a new class to your project that inherits from UISearchDisplayDelegate. The code should look something like this:
1 2 3 4 5 6 7 8 9 10 11 | [MonoTouch.Foundation.Register("LeesPlankjeDelegate")] public class LeesPlankjeDelegate : UISearchDisplayDelegate { public override bool ShouldReloadForSearchtring (UISearchDisplayController controller, string forSearchString) { Console.WriteLine("In ShouldReloadForSearchtring"); controller.SearchResultsDataSource = new LeesPlankjeDataSource(forSearchString); return true; //return base.ShouldReloadForSearchtring (controller, forSearchString); } } |
The first line is interesting. This is the magic that brings your classes into the Interface Builder. By registering the name of your class it will be added to the XIB (although not visible in the designer file). I’ll show you in a minute what you do with this in Interface Builder.
In the override of the ShouldReloadForSearchtring() I instantiate a new data source using the constructor that accepts a filter string. I set this on the SearchResultsDataSource property of the passed in controller object. As you can see in the code of the LeesPlankjeDataSource it will use a Lambda to filter the fixed array of words.
Hooking up the UISearchDisplayController with your Delegate
The Register-attribute on your delegate class makes it available in Interface Builder. So you go to the Library Window, choose the Objects button, then Controllers folder and then the general NSObject. Something like this: 
Drag it to the MainWindow, select it there, go to the Inspector, choose the Identity tab. Now change the class field to the name of your own class. LeesPlankjeDelegate in my case. Your class will not be listed, but that doesn’t matter. When you hit Enter, you’ll see in the MainWindow that both the class name and the instance name have changed. That is just fine.
Now the next magical thing: you have to connect the default delegate of the UISearchDisplayController to your Delegate class. Here is how: select the UISearchDisplayController in the MainWindow, go to the inspector, select the Outlets tab. The first outlet there is called “delegate” and is connected to your TableView. Now remove that connection by clicking the X. Then connect this delegate to your own Delegate class in the MainWindow.
Save in Interface Builder, go to MonoDevelop, run! Type something in the search and “Lo and behold!” it works!
Ain’t live sweet?
If it doesn’t work, feel free to leave a comment. I’ll see if I can help you.
P.S.
The last step is actually more complex than it should have been. If I make my UISearchDisplayController visible to my AppDelegate by adding an outlet, I can do with just one more line of code in my main.cs:
searchDisplayController.Delegate = new LeesPlankjeDelegate();
That way I go one-way: from Interface Builder to MonoTouch. But I thought it more interesting to go the other way too: from MonoTouch to Interface Builder.
Search Engine Optimization (SEO) Toolkit
Posted by Erik Sanders in .NET on October 30th, 2009
De search engine optimization toolkit die microsoft (zie ook de SEOToolkit site) biedt vele mogelijkheden om je IIS websites te optimaliseren. Je kunt je vindbaarheid verhogen door:
- Sitemaps en site indexes te maken
- Robot verkeer te regelen
- Analyseren van de site
Het analyseren beperkt zich niet tot een IIS site maar kan op een willekeurige site worden losgelaten. Ik heb dit direct losgelaten op onze nieuwe ‘out of the box’ WordPress installatie en was vervolgens erg snel klaar met de analyse. De robot.txt blokkeerde alles. Dit was natuurlijk snel opgelost maar dit geeft maar aan dat controle van je site niet overbodig is.
De toolkit is zeer eenvoudig te installeren via de Microsoft Web platform installer (dowload) applicatie. Met deze applicatie is het beheren van je webserver zeer eenvoudig.
Building iPhone applications using MonoTouch, part 3 : The Interface Builder
Posted by Richard de Zwart in .NET, mobility, technical on October 24th, 2009
So it’s about time I tell something about the Interface Builder. As I mentioned in my previous post, I fled from the Interface Builder at first. I’m not a designer, so interfaces are hard for me anyway. But I built some in WinForms and in ASP.NET and I got used to the simple system of putting buttons and fields on forms and then hooking them up with the business-logic with things like click-events.
Interface Builder is different. I think the idea is that you use it for nothing else than your GUI. There is no way to put any code anywhere. All handling of UI-events is done in delegates and the trick is to learn how to link your GUI to your code.
I hope you will have a better insight in how to do this, after this post. I learned the most from one of the videos on MonoTouch.Info, by Code Snack. I literally played it frame by frame, carefully watching what he did and what could be learned from the code on the background. Highly recommended.
So, let us build an interface with a tab-bar-controller. You might know this type of application from the default iPhone clock.
Start a new application in MonoDevelop, an “iPhone MonoTouch Project”. Double-click the MainWindow.xib and Interface Builder will start.
The empty window you get is important because it is the window that is referenced from AppDelegate. You will add all your own stuff to it as subwindows. But for now you can ignore it.
Make sure the Library Window is open (Tools / Library) and selected like this:
Now drag a Tab Bar Controller and drop it on the MainWindow (that looks a bit like a solution explorer) just below “Window”. The MainWindow will look like this:
And you get a new window looking like this:

It is not to hard to change some of the settings of the tab bar. Open Tools/Inspector, select the Attributes tab, make sure you have the right part active in the Tab Bar Window and change the Identifier Pull-down to “Search”. You will get a default Search Tab, including the search image.
Make the first tab a Search tab and the second a History tab. Now save the project and check the MainWindow.xib.designer.cs. Nothing interesting, except for a mapping to the window called “Window”. If you run your application now, nothing interesting.
That is because we have to add our new view as sub-views to the main window. In code like this:
1 2 3 4 5 6 7 8 | public override bool FinishedLaunching (UIApplication app, NSDictionary options) { // If you have defined a view, add it here: window.AddSubview (tabBar.View); window.MakeKeyAndVisible (); return true; } |
But we have no variable named “tabBar”. Well, now we’re coming to the very important part where we hook up our GUI to our code. Interface Builder does that with something they call “outlets”. And defining them is one of the weirdest experiences in your live as a programmer.
Ok, since I want to have a reference in my AppDelegate to the Tab Bar Controller, I go back to Inteface Builder, to the Library Window and select the Classes button. All the way on the top, there is a AppDelegate. Select it. Then look on the bottom of the window. Select the Outlets button. Now you see that the AppDelegate has an outlet called “window” which is mapped in the designer file in MonoDevelop to a property of type UIWindow with the name “window”. That is how the code above can reference a “window” object. We need to add an outlet by clicking the + button. Give it a name like “tabBar”. The change the type to UITabBarController.
Now we have a definition of an outlet. But it is not linked to any UI-element yet. So go to the MainWindow and select the AppDelegate there. Now go to the Inspector Window and select the Connections tab. You will see that the connection from the tabBar outlet is still open:
Now comes the magic. You drag the open circle to the Tab Bar Controller window. While getting there you will notice that only windows that are of the right type (UITabBarController) will be an acceptable drop-target. Now drop it, save it and go to MonoDevelop. In the designer file you will see that a new mapping is made. If you change the code in your main.cs to reflect the code above and run your application, you will have your tab bars!
Ok, so far for this post. Next post I will add a search-bar to the search window on the search tab and try to hook them all up to each other and to the code.
Building iPhone applications with MonoTouch, part 2 : The AppDelegate
Posted by Richard de Zwart in .NET, mobility, technical on October 20th, 2009
This is part 2 of a series. In the first post I said something about the application structure.
A word about Twitter
I’m going to digress a little before telling you more about iPhone application structure. It is not essential for this series, but it is essential to completely describe the adventure that this first application brought on me.
When I found out about the MonoTouch project, it was in Beta and you had to apply to be admitted. I filled in the form (from my iPhone, just to impress them) and then waited. Nothing for a couple of days. I applied again, just to make sure you know. Nothing. Now I’m a modern guy, so I tweet. I tweeted my frustration (in Dutch), since I really wanted to get started. But hey, what where the 3 followers I have gonna do about that? Then it turned out that this guy Joseph Hill, somehow monitors all tweets in the world for the MonoTouch keyword. Joseph is one of the people in the MonoTouch project that is really a Person. He pulled some strings and presto! I got my Beta-account.
For me, that’s just amazing. I didn’t think that Twitter would give me much more than just the latest tips from Scott Guthrie, but this is a totally new way to bring people together and build communities.
The AppDelegate
When you create a new iPhone solution in MonoDevelop, you get a couple of things:

New Solution
- A xib file called MainWindow.xib. This is where your user-interface is defined. It is an XML file that can be used by the Interface Builder. Simply double-click it and the Interface Builder opens up. More about the Interface Builder later. MonoDevelop monitors the file and regenerates the accompanying designer file when the XIB is changed by Interface Builder. The designer file maps the elements from the user-interface to the classes in your project.
- A main.cs that contains the entry-point to your code. There is a partial class called AppDelegate that is mapped to the main window of your UI. The most important method there is “FinishedLaunching”. It gets called when the iPhone is done with all the stuff it does when loading an application. The name is a bit misleading. Your application is definitely not done launching, at best it is done loading. All the stuff that you need to do yourself still has to happen. Like loading some files, initializing your controllers, setting-up your model classes.
Loading your application
There’s more to say about the loading process. Since it takes some time before you even get control about what happens, you have the option to show an image while loading. Add a file to your project with the name “Default.png” and set it’s properties to “Build Action – Content” and it will be picked up by the loader. Your supposed (according to the designer guidelines) to use an image of your app in action, but it is often abused to show a company logo or something. Some applications make a screen-shot of themselves when the application closes and save that as Default.png. That way, the next time you start your app it looks like it quickly continues where it left off.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // The name AppDelegate is referenced in the MainWindow.xib file. public partial class AppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication app, NSDictionary options) { Console.WriteLine("Launched"); window.AddSubview(yourViewHere); window.MakeKeyAndVisible(); return true; } // This method is required in iPhoneOS 3.0 public override void OnActivated (UIApplication application) { } } |
You should not be doing too much work in this method. The loader times the duration of this method and kills your application when it takes more than 10 seconds. Or so they say, I never tried it out.
You can use this method to build up your user-interface in code. I went that way first. I had such a hard time getting my head around the Interface Builder that I decided to drop it and build my interface by hand. That worked reasonably but caused unexpected crashes. I knew it had something to do with the way I hooked up the different views, so I went back to Interface Builder and tried and tried and tried. I got it, more or less, and my interface (using a tab-bar) is now stable. In the next episode I will dive into the Interface Builder.











