Archief voor categorie mobility

GraniteDS and AIR for mobile

In this article I will briefly show how to resolve some obstacles I came across when I developed my first application with AIR for mobile and GraniteDS. The most noteworthy reason of using AIR to create mobile applications is of course the multi-platform deployment using a single codebase. Furthermore, with Granite you are able to disclose the services of an existing Java backend to a mobile platform without significant changes to the backend. This offers great potential for enterprises who are struggling with the fragmented mobile market and don’t want to completely rewrite their existing Java backend.

I will assume you have some familiarity with AIR for mobile and Granite. It’s mostly the same as for Flex but there are some things you have to take into account.

1. Get the right version of Granite

The latest version of Granite is 2.2.1 GA. However, in the most recent version of AIR and Flex Adobe made some changes in the API which breaks backwards compatibility for some features of Granite. Therefore this release of Granite won’t work using the newest SDK. Refer to this post on the Granite form for more info on how to make these changes yourself. If you don’t want be bothered with building Granite yourself just download this version of GraniteDS to get started immediately.

2. Connecting to the right server

A problem for AIR applications in general (both desktop and mobile) is setting the right server settings. It is quite simple when running within the browser: The server address is changed with a single reconfiguration of the swf-file and all clients are using the new address on a browser refresh. With AIR it is a bit different and you’re not always at liberty to ‘hardcode’ the service settings in the AIR distribution package.
Granite offers a method for dynamic server configuration using the server initializer component:

Tide.getInstance().addComponentWithFactory(
  "serviceInitializer",
  DefaultServiceInitializer, {
    contextRoot: '/my-app',
    serverName: “10.0.0.1”,
    serverPort: “8080});

Note that once a connection is made, it is not possible to reconnect with another configuration, because the service initializer is only used once. You have to restart the application to enable the new connection settings or reset Tide’s RemoteObject. Unfortunately Tide’s API doesn’t support this reset. I came up with a small workaround which requires you to extend the EJB class with an extra reset method with the following body:

public class Ejb extends org.granite.tide.ejb.Ejb {
  /**
   * Reset the Tide Connection to allow new server settings
   */
  public function resetConnection():void {
    if (_ro) {
      _ro.disconnect();
    }
    _ro = null;
  }
 
}

This method resets Tide’s RemoteObject so the next remote call will force a reinitialization using the current settings of serviceInitializer. Refer to Granite’s issue tracker or forum thread for more details.

3. Automatic logout

Applications running on mobile platforms are always susceptible to unpredictable interruptions. For example when a phone call or text is received. Mobile AIR applications provide a deactivate event which is dispatched when the application is halted somehow. The application I wrote was using Tide’s Identity class for user login. Therefore I added an event handler to automatically logout the user and push the LoginView on top of the navigator stack:

private function deactivateHandler(event:Event):void {
  if (identity.loggedIn) {
    identity.logout();
  }
  navigator.popAll(); // Purge the navigator history to disable back button usage
  navigator.pushView(LoginView);
}

4. Build, build, build!

This isn’t directly related to Granite or AIR for mobile. But since they can both be used for enterprise scale applications I thought I’d mention it shortly: Make sure you have a proper build script. Now, I’ve got an example from Chris Black which provides a good starting point. I’ve only added the metadata compiler options required for Tide and of course a reference to the Granite libraries and generated Actionscript classes.

 
 <mxmlc ... >
 
  <!-- .... -->
 
  <!-- location of generated as classes with gas3 -->
  <source-path path-element="${gen.src.dir}" />
 
  <compiler.library-path dir="${basedir}/libs" append="true">
    <include name="granite-essentials.swc" />   
    <include name="granite.swc" />
  </compiler.library-path>
 
  <keep-as3-metadata name="Bindable" />
  <keep-as3-metadata name="ChangeEvent" />
  <keep-as3-metadata name="Destroy" />
  <keep-as3-metadata name="Id" />
  <keep-as3-metadata name="In" />
  <keep-as3-metadata name="Inject" />
  <keep-as3-metadata name="Managed" />
  <keep-as3-metadata name="ManagedEvent" />
  <keep-as3-metadata name="Name" />
  <keep-as3-metadata name="NonCommittingChangeEvent" />
  <keep-as3-metadata name="Observer" />
  <keep-as3-metadata name="Out" />
  <keep-as3-metadata name="PostConstruct" />
  <keep-as3-metadata name="Transient" />
  <keep-as3-metadata name="Version" />
 
</mxmlc>

One plus one

I can imagine one must be thinking: ‘Everyone could have figured that out!’ And I totally agree, because that’s exactly what this article is about. With some experience with Flex, a developer can write a mobile application on top of a Java EE backend. It doesn’t take much to utilize an existing backend from a mobile platform. Since the latest release of AIR the performance for iOS and Android is pretty good and together with the Granite Enterprise Platform the barrier to emerge an enterprise application to a mobile platform has become much lower.

, , , , , , ,

2 reacties

Introduction to AIR for mobile

A couple of weeks ago, Adobe released a preview of the new Flash Builder and SDK. One of the new features is support for mobile devices using AIR. For now, only Android 2.2 is capable of running mobile AIR applications, but since Steve has changed the rules again, AIR on iOS is nearby, according to Adobe. Time to take a test drive with a tutorial.

Goal

We will create a simple RSS reader. Not a very exciting example, but already shows some nice features of AIR for mobile. I’ll assume you have experience with Flex or AIR, but I think you will manage with some level of programming experience. If not, feel free to leave a reply if you have any questions or take a look at the full source.

Setup

Empty project contents

Download and install the preview release of Flash Builder called Burrito It provides a wizard to start an empty mobile application. By default the wizard creates two mxml files containing a MobileApplication and a View component.

The MobileApplication class is inherited from the Application class used for desktop AIR. The mobile version provides, among other things, an action bar and a navigator. Furthermore its firstView property points to the empty view component. The view component is a normal group, but optimized for mobile use as well.

Article list

Open the main view component (called <projectName>Home.mxml). Create a List component in the main view. Provide positioning constraints to let it occupy the whole screen.

<s:List left="0" top="0" bottom="0" right="0" />

To retrieve the feed, create an HTTPService pointing to the RSS feed in the declaration section of the view. Add a resultHandler function to parse the feed-data. Parsing xml data is quite simple. You can just navigate to the DOM-tree as it were a normal ActionScript object. Use the data property of the view to store the articles locally. Using this property will provide some benefits with navigation, which will become clear in a bit.

<fx:Script>
  <![CDATA[
    import mx.rpc.events.ResultEvent;
 
    protected function service_resultHandler(event:ResultEvent):void {
      data = event.result.rss.channel.item;
    }
  ]]>
</fx:Script>
<fx:Declarations>
  <s:HTTPService
    id="service"
    url="http://lsd.luminis.nl/feed/"
    result="service_resultHandler(event)" />
</fx:Declarations>

Now there are only a couple of things left to do. Invoke the server and provide the list with the articles and instructions to show them.

Both are quite simple. The feeds are retrieved by invoking the send() method of the service. To automatically retrieve them, this method should be invoked when the view is created so we will use the creationComplete handler.

<s:View
  xmlns:fx="http://ns.adobe.com/mxml/2009" 
  xmlns:s="library://ns.adobe.com/flex/spark"
  title="Home"
  creationComplete="service.send()">

Finally, bind the data property to the dataProvider of the list and set its labelField attribute to ‘title’.

<s:List
  dataProvider="{data}"
  labelField="title"
  left="0" top="0" bottom="0" right="0" />

Your view will probably look something like this.

<?xml version="1.0" encoding="utf-8"?>
<s:View
  xmlns:fx="http://ns.adobe.com/mxml/2009" 
  xmlns:s="library://ns.adobe.com/flex/spark"
  title="Home"
  creationComplete="service.send()">
 
  <fx:Script>
    <![CDATA[
      import mx.rpc.events.ResultEvent;
 
      protected function service_resultHandler(event:ResultEvent):void {
        data = event.result.rss.channel.item;
      }
 
    ]]>
  </fx:Script>
 
  <fx:Declarations>
    <s:HTTPService
      id="service"
      url="http://lsd.luminis.nl/feed/"
      result="service_resultHandler(event)" />
  </fx:Declarations>
 
  <s:List
    dataProvider="{data}"
    labelField="title"
    left="0" top="0" bottom="0" right="0" />
 
</s:View>

Emulator

Emulate hardware buttons

Emulate hardware buttons


Now it is time to run a first test. Click the Run button and select ‘On Desktop’ as launch method in run configuration dialog. Also choose a device to simulate and run the application.

When the emulator is launched it shows a list of articles after a couple of seconds. Now you can select Rotate Right from the Device menu to display the landscape view. You will also notice the list is able to scroll up and down when dragging your mouse pointer (Which of course is the emulated equivalent of a one-finger swipe)

Article details

Next is to create a detailed view showing the full content of an article. Close the emulator and return to Flash Builder. In the views package, create a new component and call it DetailView. Bind the title attribute to data.title. Add a label as well and bind the text property to data.description. Don’t forget to specify the positioning constraints.

<s:View
  xmlns:fx="http://ns.adobe.com/mxml/2009" 
  xmlns:s="library://ns.adobe.com/flex/spark"
  title="{data.title}">
 
  <s:Label
    text="{data.description}"
    left="20" right="20" bottom="20" top="20" />
</s:View>

All view components provide a navigator object. We will use this in the change event handler of the article list. This event is fired when the user selects an article from the list. It looks as follows:

import spark.events.IndexChangeEvent;
 
protected function articleList_changeHandler(event:IndexChangeEvent):void {
  navigator.pushView(DetailView, data[event.newIndex]);
}

It simply instructs the navigator to create a new DetailView and push it on top of of the navigation stack. Furthermore the selected item from the article list is passed on to the data property of the DetailView.

Add the change handler and assign it to the change event of the article list:

<s:List
  dataProvider="{data}"
  labelField="title"
  change="articleList_changeHandler(event)"
  left="0" top="0" bottom="0" right="0" />

Article list inside the emulator

Article list inside the emulator

For performance optimization, AIR destroys the view when a user navigates away and recreates it when he returns. Only the contents of the data property is saved and passed into a recreated view of the same type. This is why we used it to store the articles. Otherwise the user has to wait for a reload when he returns to the main view.

When you launch the new version in the emulator, you will notice the application slides to the detail view when an article is selected. Click Back from the Device menu to simulate a click on the hardware back button.

Last but not least: action buttons

One thing our application is missing, is a button to go to the original webpage showing the full article. This button is placed inside the header of our detail view, next to the title.
To achieve this, add the button inside the actionContent of the detail view. Give the button an icon (I used one from the Tango project) and set the click handler to open the url of the article.

<s:actionContent>
  <s:Button
    click="{navigateToURL(new URLRequest(data.link))}"
    icon="@Embed('/assets/internet-web-browser.png')"/>
</s:actionContent>

Of course you might want an additional button to return to the article list instead of using the ‘hardware button’. Place this button inside the navigationContent. This will place the back button at the upper left corner. The click event of this button will invoke the navigation.popView() method to remove the current view from the stack and return to the previous one.

<s:navigationContent>
  <s:Button
    click="navigator.popView()"
    icon="@Embed('/assets/go-previous.png')"/>		
</s:navigationContent>
Action and navigator buttons

Action and navigator buttons

If you launch the application you will notice the buttons are nicely aligned at the top of the screen.

What’s next?

The next step will be to package the application to an apk file so you could install it on an Android device. This is done by the Export Release build wizard inside the Project menu of Flash Builder. It includes the ability to sign your application to allow distribution through the Android Market.

Another nice feature which I will not discuss in detail is to add gesture based navigation. Take a look at this article from Adobe to find out more. The approach discussed should be working for mobile AIR applications as well.

Unfortunately the most interesting benefit of using AIR for mobile didn’t become clear with this tutorial. It would be nice to deploy our application on other mobile plastforms as well. However the cross compiler for iOS isn’t available yet and the same goes for AIR on Windows Phone, BlackBerry or Symbian. We will just have to wait when Adobe is ready so we can fully benefit from the “Write once, run anywhere” promise.

, , , ,

3 reacties

Getting to know CouchDB – 2/x

Last time around, we were able to store the OSGi log messages into a CouchDB. Now I want to tap into the _changes API that CouchDB offers. The options are simple, connect to the ‘_changes’ document in a CouchDB database and you will be presented with a log of all changes that have occurred on the database.

http://localhost:5984/db/_changes

{"results":[
{"seq":3,"id":"_design/app","changes":[{"rev":"2-0dc1002d841221e8d8d7f325b87ffd67"}]},
{"seq":196,"id":"994cf6817a74882cecda6425e8001a96","changes":[{"rev":"193-083ec5c1e1359789eb2cf09c46097fee"}]}
,
"last_seq":196}

For each document in the database only the last change is presented. This could result in quite a lot of information. It is therefore also possible to fetch changes while applying a server-side filter. For this to work, you first need to define a filter in a design document. Mine looks like this:

function(doc, req) {
    if (doc.type == "EVENT") { return true; }
    return false;
}

and is stored (using couchapp) in a design document called ‘app’. The name of the filter is ‘events’. The filters’ meaning should obvious: pass through all documents for which the function returns ‘true’. The proper URL for accessing the changes will now be:

http://localhost:5984/db/_changes?filter=app/events

{"results":[
{"seq":196,"id":"994cf6817a74882cecda6425e8001a96","changes":[{"rev":"193-083ec5c1e1359789eb2cf09c46097fee"}]}
],
"last_seq":196}

The “last_seq” part can be used for bookkeeping: If you plan to make  multiple calls to the _changes feed (say every hour) then it is nice to be able to skip the ones you already saw during a previous call. So, the second time you call the _changes feed, you can skip all previous changes by employing the following URL:

http://localhost:5984/db/_changes?filter=app/events&since=196

{"results":[

],
"last_seq":196}

Obviously, no update has occurred since we accessed the _changes feed for the first time. If, however we now add a new document to the database (with doc.type == “EVENT”) and call the _changes feed again:

http://localhost:5984/db/_changes?filter=app/events&since=196

{"results":[
{"seq":197,"id":"f0a4a559fac65ab3cca87baf1c014fa7","changes":[{"rev":"1-c8dfffec4e08ca8db2b95f30613e213d"}]}
],
"last_seq":197}

Also, a call to “http://localhost:5984/db” will result in a JSON object, where “update_seq” provides the current update sequence. This comes in handy if you’re really not interested in previous changes:

http://localhost:5984/db

{"db_name":"db","doc_count":4,"doc_del_count":0,"update_seq":196,
"purge_seq":0,"compact_running":false,"disk_size":1871961,
"instance_start_time":"1282049630257719","disk_format_version":5,
"committed_update_seq":196}

This is all great functionality if your time granularity is in the order of hours or days. But hardly optimal if you want to be notified immediately of changes to the database. Fortunately, by supplying “feed=continuous” to the URL, CouchDB will keep your socket connection open and supply the changes as soon as they become available. Each change is represented by a well-formatted JSON line. This breaks from the previous examples, where the complete response consisted of well-formatted JSON, so beware!

http://localhost:5984/db/_changes?filter=app/events&since=196&feed=continuous

{"seq":197,"id":"f0a4a559fac65ab3cca87baf1c014fa7","changes":[{"rev":"1-c8dfffec4e08ca8db2b95f30613e213d"}]}
...
...
{"last_seq":197}

Eventually, if no changes have been sent for 60 secs, the socket connection closes. Before it does so, it spits out the last_seq, again for bookkeeping purposes.

I was wondering if it would be possible to create a simple iPhone/iPad application that is able to report specific events on a MapView using the _changes feed from CouchDB. All one then has to do as iPhone/ iPad application is connect to the continuous feed, parse the JSON data and display the events on your MKMapView. Server-side, all one has to do is insert/ update documents in the database. How easy!

So I started off by connecting to the _changes feed using an asynchronous NSURLConnection, expecting that its delegate would receive connection:didReceiveData: calls on each change. Unfortunately, this did not work: The NSURLConnection employs buffering internally that cannot be circumvented. Thus only after about 5 or 6 updates the delegate received some data. This is definitely not good enough. Some searching pointed me to the CFSocket/NSStream class. This class fortunately employs some more basic (read: unbuffered) socket handling, allowing me to receive data from the socket as soon as it becomes available!

    //open the socket
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)[theURL host], [[theURL port] intValue], &readStream, &writeStream);

    inputStream = (NSInputStream *)readStream;
    outputStream = (NSOutputStream *)writeStream;

    [inputStream setDelegate: self];
    [outputStream setDelegate :self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [outputStream open];    

The containing class is set as delegate for both the NSInputStream and NSOutputStream. This causes the following method being called, based on events that occur on the streams:

/* stream eventing */
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {

    switch(eventCode) {
        case NSStreamEventOpenCompleted:
            [self connection: nil didReceiveResponse: nil];
			break;

		case NSStreamEventErrorOccurred:
            [self connection: nil didFailWithError: [stream streamError]];
			break;

		case NSStreamEventEndEncountered:
            [stream close];
            [stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            [stream release];
            inputStream = nil;
            outputStream = nil;
            [self connectionDidFinishLoading: nil];
			break;            

        case NSStreamEventHasSpaceAvailable:
        {
            if (stream == outputStream) {
                [self connection: nil willSendRequest: [NSURLRequest requestWithURL: theURL] redirectResponse: nil];

                NSString *str = [NSString stringWithFormat: @"GET %@?%@ HTTP/1.0\r\n\r\n", [theURL path], [theURL query]];
                const uint8_t *rawstring = (const uint8_t *)[str UTF8String];
                [outputStream write:rawstring maxLength: [str length]];
                [outputStream close];
            }
        }
            break;
		case NSStreamEventHasBytesAvailable:
        {
			if (stream == inputStream)
			{
				uint8_t buffer[1024];
				int len;
				while ([inputStream hasBytesAvailable])
				{
					len = [inputStream read: buffer maxLength: sizeof(buffer)];
					if (len > 0)
					{
						NSData *theData = [[NSData alloc] initWithBytes: buffer length:len];
                        [self connection: nil didReceiveData: theData];
					}
				}
			}
        }
            break;
    }
}

As you can see, this method kind of delegates the occurring events to calls to the NSURLConnectionDelegate (which the containing class also implements, due to my initial effort to read the changes feed using a normal NSURLConnection).

Then, the connection:didReceiveData method handles the actual changes:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSString *str = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];

    NSArray *ary = [str componentsSeparatedByString:@"\n"];
    for (NSString *line in ary) {
        if ([line length] > 0 && [line characterAtIndex: 0] == '{') {
            id json = [line JSONValue];

            NSDictionary *dict = (NSDictionary*)json;
            NSObject *seq = [dict objectForKey: @"seq"];

            if (seq && delegate) {
                [delegate changeReceived: dict];
            }
            NSObject *last_seq = [dict objectForKey: @"last_seq"];
            if (last_seq && delegate) {
                int last = [((NSNumber*)last_seq) intValue];
                [delegate lastSequence: last];
            }
        }
    }

}

This method converts the JSON data to a NSDictionary and forwards these changes to a (self-defined) @protocol called ChangesDelegate:

@protocol ChangesDelegate

@optional

-(void) changeReceived:(NSDictionary*) dict;
-(void) lastSequence:(int) last;
-(void) changesComplete:(NSError*)error;

@end

The implementation that performs the actual calls to CouchDB can be created using:

    m_changes = [[Changes alloc] initWithHost: @"localhost" database: @"db" andFilter: @"app/events"];
    m_changes.delegate = self;

    m_lastSeq = [m_changes last_seq];

Since the calling class also implements the ChangesDelegate @protocol, it will receive the changes events. I am currently using it to display MKAnnotations onto a MKMapView and it works like a charm!

Thank you CouchDB for making life easy!

p.s. I’ve made the Changes class available through github: changesfeed_xcode. Enjoy!

, , ,

Nog geen reacties

PhoneGap, een alternatief voor native mobiele applicaties

PhoneGap, een alternatief voor native mobiele applicaties

PhoneGap is een interessante open source alternatief voor het schrijven van native applicaties voor elk (mobiel) platform dat er is. In het kort komt het erop neer dat PhoneGap zorgt dat je een HTML applicatie met javascript.  De specifiek API, zoals location, contact, e.d. worden afgeschermd door een standaard API van PhoneGap.

iPhone

Voor de iPhone kan de HTML applicatie gewoon worden aangeboden via de appstore. Dit is dan ook direct de truc waardoor er voldoende rechten zijn om de hardware aan te spreken. Er zijn al vele applicatie geplaatst in de appstore (zie een selectie in www.phonegap.com/apps).  Er is tevens een getting started en er zijn  extra plugins beschikbaar

Ondersteunde platformen

Naast iPhone wordt zowel Android, Blackberry, Symbian, Palm, N900 en Windows Mobile. Ook Windows Mobile 7 is zodra dit uitkomt eenvoudig te ondersteunen en ze zullen ook geen blokkade opwerpen in het voordeel van silverlight. Interesante gedachte is natuurlijk ook de iets minder mobiele system met Linux, Windows MacOS hebben ook allemaal een browser.

IPHONE ANDROID BLACKBERRY SYMBIAN PALM
GEO LOCATION
VIBRATION
ACCELEROMETER OS 4.7
SOUND
CONTACT SUPPORT N/A

Voor meer informatie zie www.phonegap.com

, , , , , ,

1 reactie

Windows Phone 7 Developer Hub

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.

, ,

Nog geen reacties

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 reacties

Online video presentatie: Android & Augmented Reality

Op 11 november 2009 gaf Arjan Schaaf op de NLJUG een presentatie over Android en Augmented Reality. De video van deze presentatie is inmiddels online beschikbaar. De gehele presentatie van 50 minuten kan je hier (175mb) downloaden. Maar de eerste tien minuten zijn hieronder gelijk op YouTube te bekijken.

English: The whole presentation can be downloaded here (175mb).

Augmented Reality op mobiele devices heeft een enorme vlucht genomen met de introductie van Google Android. Android biedt out-of-the-box de componenten om met augmented reality aan de slag te gaan. In deze sessie staan we stil bij de frameworks die beschikbaar zijn om augemented reality applicaties / content te deployen op Android. Aan de hand van een voorbeeld applicatie gaan we in op de mogelijkheden om zelf een augmented reality applicatie te ontwikkelen met de faciliteiten die door Android worden geboden. Praktische uitdagingen waarmee wij zijn geconfronteerd worden gedeeld en geven inzicht in de mogelijkheden en onmogelijkheden van het Android platform. Opbouw van de presentatie:

  • Introductie over augmented reality: location based vs beeldherkenning;
  • Wat is te krijgen in de markt? Layar, Wikitude, etc;
  • Wat zijn de mogelijkheden om applicaties te ontwikkelen met de beschikbare frameworks;
  • Hoe ontwikkel je zelf een augmented reality applicatie op Android?

De slides van de presentatie zijn te vinden op de NLJUG website.

, , , , , , , , , ,

Nog geen reacties

About Non-Disclosure Argeements

Last night I wrote a blogpost about the first application I built for the iPad. I’m so happy with the (coming of) the new gadget and the possibilities that the MonoTouch created to rite .NET code for it, that I could not wait to write a sample app and to share my experiences with the rest of the world.

So at 11 o’clock I sent out a tweet with a link to the blog. About 60 seconds later I got a reply from someone that I trust knows what he is talking about, that I better remove the post since I agreed on a NDA.

Wow, did I? Yes, I did. When you download the beta of the iPhone 3.2 SDK there’s the following text:

NDA

Yep, the beta is considered Apple Confidential Information. So I removed the post and went out to discover what I could and could not do under this NDA. Tried searching apple.com on the exact string “Apple Confidential Information”. No hits. Searched the legal department at apple.com/legal, no hits on beta software

Finally came up with the idea to search on the sub-site of the Apple Developer Centre. On the page on Pre-release software there is the rather clear text:

Pre-release software is Apple Confidential Information and your use of such software is subject to the Apple Developer Connection Terms and Conditions, including the Prototype License and Confidentiality Agreement attached thereto. Distributing the software to anyone other than an ADC member who is working for the same entity as you is considered a violation of your agreement with Apple and is damaging to both Apple and those who develop for the Apple platform. We sincerely appreciate your efforts to keep this software Confidential.

The last part I understand: no distribution of the software. No problem. But I think the Confidentiality Agreement must hold more information. There is a “Terms and Conditions” PDF that has a section 7 on Pre-release software that essentially tells you that “You certify that pre-release software will only be used for testing and development purposes”. Fine so far, but it also refers to the attached Prototype License and Confidentiality Agreement. So where is that agreement and what does it say?

The PLCA (as they lovingly call it) is on page 5 of the PDF and has a section 4 on non-disclosure:

You agree not to disclose, publish, or disseminate Confidential Information to anyone other than employees and contractors working for the same entity as you who have an existing ADC membership

Well, there it is. No right to publish Confidential Information, which means no stuff that Apple hadn’t already published about. So I can write about the iPad, I can write about the existence of the SDK, but I cannot write about a certain new UI-control that I used to build my demo app. Even though I like this new UI-control and love what it does for me.

Is this really necessary? What good does it do Apple when I don’t write about their products? About a product that they most certainly want as much coverage of as they can get: the brand new iPad?

Should I really be worried that they will sue me when I break my Vow of Silence? Of course, being Dutch, growing up in a country that is known around the world to be liberal, it is hard to believe someone will really sue you. Especially when you write nice about them.

I don’t like secrets, I don’t like lawyer stuff that tries to protect (imprison?) ideas. I do like what Jeff Atwood wrote about ideas: ideas in itself are not very valuable, it is how you execute them. So my message to Apple: liberate your ideas, they are great, I love them. Allow others to rave and rant about them, who cares? You are the one that is going to execute them in the most profitable way, any way. Right? And if you’re not going to, then don’t blame the blogger, blame yourself.

, , ,

Nog geen reacties

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 reacties

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 reacties