Category Archives: Architecture

Transferring Data via Bluetooth on Android (android-btxfr)

Recently, I’ve been working on some code to transfer images and other data between Android devices using Bluetooth.  While I could have used the Basic Imaging Profile (BIP) of the Bluetooth 4.0 specification, this particular application has specific requirements that would have been difficult to implement using BIP.  To overcome this, I ended up building an application that instead relies on the Serial Port Profile (SPP), exchanging data using the RFCOMM protocol.  

The SPP implementation on Android is nice, but only offers the fundamentals of an InputStream and OutputStream.  While this provides the basics of sending and receiving bytes, it doesn’t handle data integrity, progress updates, threading, or any of the other requirements often needed when sending data between two devices.

The result from my recent work is an Android library called android-btxfr, which I’m happy to share through my Github repository.  android-btxfr is lightweight library designed to send and receive any type of data between Android (API 15 and higher).  It can be used to exchange text, files, photos, videos, sounds, and literally any other type of binary data.  The library supports anything that can be put into a byte stream and includes digest checking to ensure data integrity.

The library exposes two thread types (ClientThread and ServerThread) depending on whether you are sending or receiving data.

Receiving data is easy. Simply run the server thread, passing the paired bluetooth device and handler. The handler will be then called with the following messages:

DATA_PROGRESS_UPDATE – Data is being received by the other device. The message contains the progress of the data being received.
DATA_RECEIVED – Data has been fully received from the other device. The message will contain the actual payload (a byte stream of the image, video, etc.)

There are other message types to handle failure conditions.

The client thread works in a similar fashion. To send data, invoke the client thread, passing the paired bluetooth device and handler. The handler will be called with the following messages:

READY_FOR_DATA – Indicates that the connection has been established, and data can be sent.
SENDING_DATA - Indicates that data is being sent to the other device.
DATA_SENT_OK – Indicates that the recipient received the payload.

Again, there are other message types to handle failures.

To show all of this in action, I’ve put together a sample application, which can be found here.  This app uses the android-btxfr library to send captured photos between devices. 

NewImageNewImage

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Enabling x86 Android Emulation

If you’ve undertaken any Android development, you’ll have likely found that the Android emulator can be painfully slow – to the point where the majority of developers I know use a physical device to do any development at all.  The primary reason behind this is that the default emulator is emulating an ARM based chipset on x86 hardware, and the translation between these two architectures is of course costly.  What many of these developers may not realize (and I didn’t until very recently) is that Intel have released a x86 Android emulator.  The x86 emulator has a few caveats (and of course cannot run any ARM-only libraries, such as the Google Play APIs), but overall can be used to speed up the performance of testing apps in the emulator by leaps and bounds.
This is how to get it working:
1.  In the Android SDK Manager, ensure you have API Level 15 or higher installed.  Under the API of your choice, install the Intel x86 Atom System Image:
NewImage
2.  Under the Extras folder, install the Intel x86 Emulator Accelerator (HAXM) module:
NewImage
3.  After you add the HAXM support through the SDK manager, you still need to install the HAXM package.  To do this, navigate to the Extras/Intel/Hardware_Accelerated_Execution_Manager folder under your installed Android SDK path.  Run the .dmg in this folder to install the support.  As part of the installation, you’ll be asked how much RAM to allocate/partition.  On my 16Gb MBP, I have chosen a 2Gb allocation.
4.  This is really important (for Mac OS X Mountain Lion users).  Go to this knowledge library page on Intel’s HAXM site and install the 1.0.4 hotfix.  If you do not install this hotfix, you will likely get a kernel panic when you try to start the AVD.
5.  Create a new AVD, or edit an existing AVD.  Ensure that the CPU/ABI is set to Intel Atom (x86).
NewImage
You can also increase the RAM up to the limit that you set during the HAXM installation.  Also, you should ensure that the “Use Host GPU” check box is enabled as this will allow the emulator to use OpenGL ES on the host for increased performance.
 
With that you should be set!  If you are editing an existing AVD, I recommend checking the “Wipe user data” checkbox before starting the image.  (Otherwise you might find that the emulator will hang during start up).  
 
NewImage
If everything is working OK, you should receive a message that HAXM has been enabled, and your AVD should boot in several seconds (as opposed to several minutes) and be lightning quick to use!
  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

An Objective View of MEAPs

I recently had the opportunity to put together some research for a customer who has been interested in the MEAP (Mobile Enterprise Application Platform) space. My premise is that the market has become flooded with MEAPs (Mobile Enterprise Application Platforms, as coined by Gartner), yet most of them are fundamentally taking organizations and developers down the wrong path when it comes to developing mobile applications. The problem is that MEAPs demo really well in front of the CIO… “Wow! You just hit F5, and your application is compiled and deployed to iOS, Android, Blackberry devices… Where do I sign?” – yet the reality is very different. Namely:

Language Abstraction – Many MEAPs have their own language that claim to be similar to Java or a flavor of JavaScript. Even if it is the same language, there is always something new to learn. Also, developers tend to shy away from learning any language that’s vendor specific (APEX on Force.com anyone? ;–)

Language Limitations – When you create a language that abstracts other languages you always end up serving only the lowest common denominator. Often there are ways of coding styles and nuances supported in the native language that the MEAP won’t expose because it’s not on other platforms.

Platform Limitations – Time has shown that platform abstraction doesn’t work (do a search on Wikipedia for cross platform RAD tools if you don’t believe me). Also, platforms change quickly. What happens if/when the next version of iOS is released? You have to wait for your MEAP vendor to catchup before you can use any of the features.

UI Limitations – Following on from the previous point, many of the controls that MEAPs offer also follow the lowest common denominator rule. For example, Cocoa Touch has a neat feature called a “Half Page Curl Transition”. If you abstract your UI to a MEAP vendor, how is this supported on other platforms? Either a) it’s not (so by default you can’t use it on iOS), b) you can only use it on iOS (which breaks the promise of a MEAP) or c) it’s implemented as a hack job on all platforms.

Tooling – MEAP tooling is often Web based, or bundled as an Eclipse add-on – but in both cases it often doesn’t fit in with the other tools that developers use today (e.g. ALM, refactoring, unit testing, etc.). Also, many of the MEAP vendors seem to be aiming their toolsets towards business analysts. When are we going to let this one go? Business analysts have an important role to play in teams, but they shouldn’t be developing UI, and they shouldn’t be writing code.

Debugging – Let’s say you create your application with a MEAP, and then it crashes 1 time in every 10 (i.e. one of those really nasty bugs to find). What are you going to do? a) Reach out to Apple? I suspect they won’t help you. b) Search the web for other people with the same issue? Could be difficult to find. c) Pay the MEAP vendor even more money to investigate your issue? Ah, that’s the one…

Data Abstraction – Many MEAPs offer connectors to databases, XML files, SAP, etc. Not only are these costly, but many are just pass-through connectors, so as a developer you don’t get any control over the connection. Want to implement synchronization? Want to change the formatting or query for better optimization? Probably not going to be possible.

Difficult to Extend – Many MEAPs don’t extend very easily. Found a new JavaScript library that you want to use in your application? How about a native control that you’d like to display? Could be tough. Some MEAPs do offer bridging to native code – but in which case, why not just write the whole thing in native code to start with?

Vendor Lock In – The sum of all the above leads to quite the definition of vendor lock in. Chances are by the time you deploy your first application you’ll be signed up with an expensive support and service agreement, with your developers working on code in a language that they’ll never be able to re-use, on a platform that won’t go anywhere.

I’ve extended this into a presentation that you can find below – which cover the above points in more detail, plus outline some general alternative approaches to creating applications without the dependency on a MEAP framework.

Based on other people’s experience with MEAPs, am I missing anything?

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Tips, Tricks, and Recommendations for HTML5/Mobile Web Development

Over the past few months I’ve been fortunate to have worked with several customers creating Mobile Web applications for different devices. These have included an iPad based Mobile Web app for a healthcare provider, a cross-platform Mobile Web app for a commercial real estate broker, and an Android tablet solution to allow scientists to research experiment details from the comfort of their lab.

From these projects, I’ve come up with a list of tips, tricks, and recommendations that I wanted to share if you are looking to develop your own Mobile Web applications. Hope you find them useful…

Understand the differences between Mobile Web and hybrid applications

It’s important to make an early decision on whether your application is going to be pure Mobile Web (the user accesses it through the browser on the device) or hybrid (the user launches an application with an embedded control to display web based content). The decision to use the mobile browser or to have a dedicated hybrid application will likely be determined by the functionality the application requires. For example, obtaining the GPS location from the device can be performed perfectly well inside the browser, but accessing the camera from a Web page needs a hybrid application to provide the functionality.

In my experience there are three common features that drive developers towards a hybrid application: 1. Access to the camera. 2. Access to local contacts on the device. 3. Deployment to the AppStore/Marketplace. The first two are to overcome limitations of what can and can’t be accessed through the mobile browser (and is something that Mozilla is trying to tackle through WebAPI). The latter one is probably the most important to understand however – as while a hybrid solution will enable the application to be published to the app stores, extreme care needs to be taken to ensure that the application will not be rejected. This is most common with applications destined for Apple’s AppStore (if Apple view your application as a single container for web content with no apparent native functionality, they will more than likely reject it).

If you do take the hybrid approach, you really have two options to build the application – you can either set out and build a native application, embed a WebView control and then hook different events to create your own bridge between the two. This can be very useful if you only have a small piece of Web functionality that you need to embed in your application. Alternatively, you can consider using a framework such as PhoneGap (now known as Apache Cordova). Using Cordova is not without it’s challenges (for example, with cross domain scripting and client side certificate authentication), but it can definitely give you a head start especially if the majority of your application is going to be based on mobile web content.

Setup a robust development and testing environment

Setting up a robust development environment might be viewed as obvious for most of us, but tools for developing Mobile Web applications are still relatively immature, so it’s an important area to get right before you start your first app. In the most basic setup, you are going to need three things to be successful:

The first is a great IDE for HTML development. You’ve probably got your favorite already, but a strong IDE with as much JavaScript code completion support as possible will be your friend. Personally, I switch between TextMate, Visual Studio 2010, and WebStorm depending on which platform I’m working with. It’s also interested to see where Adobe are headed with their toolset.

Secondly, you are going to need a browser capable of inspecting the DOM and doing JavaScript debugging. Personally, I use Safari for doing this, but Chrome and/or IE9 will equally provide you the tools that you need. The important thing here is not so much the choice of the browser, but the understanding of how to breakpoint JavaScript code and inspect elements both on and off the page.

Finally, you’ll need some kind of device, or device emulator. Switching the user agent on a desktop browser will only get you so far, and eventually you are going to need to test on something representative of the device that the user will be using. If you are developing an application that will be primarily used on iOS devices, I would certainly recommend a Mac (as the iOS simulator is very robust). If a Mac doesn’t float your boat as your development machine however you could consider a hosted solution such as MacinCloud or simply do all your debugging using an iPod touch. There are a few PC based utilities that claim to emulate mobile safari/iOS, but I’ve had a poor experience with all of them.

For Android, I tend to avoid the emulator whenever possible (it’s a resource hog) and instead have a selection of devices that I can use for debugging on the fly. I’ve found that the key for Android testing is to have a selection of devices with preferably different resolutions and running different versions of the OS (e.g. a separate device running 2.1, 2.2, 2.3, and 4.0 should cover most of the current market, unless you have a need to go back to 1.6 for some reason). If you don’t have access to physical handsets, you may want to consider one of the testing providers such as Perfecto Mobile. They have a variety of devices that you can rent, covering many different platforms.

Use client side JavaScript instead of server side scripting

If you’ve been developing Web applications for some time, especially enterprise facing applications, you’ll be used to having a lot of the presentation and application logic tied up in server side scripts, maybe running server-side ASP, ASP.NET, JSP, PHP, etc. When developing Mobile Web applications however, things need to change. While server-side scripting will of course still work for a mobile application (and might be very tempting as you start to write your first application), it quickly creates a tight coupling between your device and the server. In the old days where you were accessing the server from a desktop browser on the same network, this wasn’t a problem – but once you move the experience to a mobile device with a potentially patchy network connection, the last thing you want to be doing is relying on the server side for generation of pages and views. If your mobile web application needs to do a roundtrip to the server when you hit the “Next Page” button, you’re going to be heading for a world of hurt.

The answer is to move as much (if not all) of the application logic to client-side JavaScript. This might be a painful exercise as you translate the move from an MVC server side framework to handcrafting page navigation using client side JavaScript, but the pay off will be worth it. If you have all of the application logic locally, together with pre-fetching as many of the pages into the DOM when your application first loads, you effectively disconnect yourself from the server side which makes performance much better and also moving to offline much easier. Of course, you still want to communicate with the server side – who doesn’t? – but this should be done via a set of asynchronous REST/JSON calls to bring data into the application rather than relying on the server to generate HTML for your application.

Design for running offline

Related to the previous point, you should also start thinking about how your application could run offline, even if you have no plans to do so. This will put you on a good architectural path, and will also mean that your application will work if and when network connectivity is lost. There are plenty of articles explaining how to enable offline access in HTML5 applications, so I won’t plan to cover here – other than to say you’ll be creating a cache manifest for your application, specifying the files to go into your cache, enabling the scripts for checking the cache when your application starts, and handling control logic accordingly (e.g. when you hit that submit button, you’ll want to know whether there is network connectivity before making the call to the server!).

If there’s one piece of advice that I can offer here however (and we learned this the hard way) it is to design for offline first, but implement last. Do all of the right things to support offline in your application, but don’t enable it until you are close to the end of your development cycle. If you enable it too early, it can cause mayhem with the development team – as your developers could end up debugging against a version of the application that could be slightly older – or the cache doesn’t get refreshed in the way it should. This doesn’t application to local storage – this is fine to access during development – I would just recommend not enabling the cache manifest until you go into UAT.

Select the right UI framework for your needs

Almost every other day there seems to be a new HTML UI framework released, and mobile frameworks are no exception. At Neudesic we’ve had most experience and success using jQuery Mobile, but have equally done work using Sencha, Dojo and others. As all the frameworks offer slightly different combinations of controls, I’ve found one of the tricks for selecting a suitable framework is to first build out a list of the controls that you are likely to need. For example, in one project we developed a set of paper prototypes (side note – I really dig UI Stencils for this) and realized that we would be creating a multi-tabbed application, with many lists on each page. Knowing what controls we were likely to use ahead of time made selecting the framework easier, and also put into perspective what controls we would have to build from scratch.

The good news is that most of the frameworks have demo pages/sites available, so that you can check them out beforehand without having to download anything. This can be a great way of testing the controls across a different number of devices, as well as getting a feel for the performance. My rough order of magnitude is that HTML based mobile UI will feel around 85% of a native control – it will look similar, react similar, but you just know that there’s this 10 – 15% gap that doesn’t quite feel native.

Understand the caveats with implementing maps in Mobile Web applications

Related to the last point, many applications have a need to display maps and pinpoints, and this will likely remain true for many mobile web applications that you might be creating. Based on experience, there are a couple of caveats that need to be understood before you head down this path.

Firstly, performance on Mobile Web map controls is not to par with native controls. Using Google Maps in Safari on iOS seems sluggish when comparing it to using MapKit in a native iOS application. I’m not sure what optimizations have been done in MapKit to give it the performance it has, but the difference is quite noticeable. As a result, if your application has a fundamental need to do a lot of mapping (i.e. if this is it’s primary function) you may want to consider a hybrid approach where you navigate to native pages for the mapping as part of your application.

Secondly, the web control for Google Maps (and this probably applies to other mapping controls) likes to “own” the page – which can put it into conflict with UI frameworks such as jQuery Mobile. For example, when you change pages in jQuery Mobile, the DIV element of your current page is set to hidden, and the DIV element of the new page to block. If your map control is embedded on a page that gets set to hidden this can cause Google maps to have a hard time. We’ve experienced random behavior such as the map control not updating or repainting correctly when it is brought back into focus. This can be overcome by an event on the page load to refresh the map canvas (example below), but it’s one of those bugs that takes a lot longer to find than it does to fix.

$(‘#mappage’).live(‘pageshow’, function() { google.maps.event.trigger(map, ‘resize’); });

Think ahead for non-standard UI elements you are likely to need

While frameworks such as jQuery Mobile will provide standard controls such as buttons, lists, labels, and radio boxes, your application will likely have a need for elements and controls that are non-standard. These can include tables, grids, and image carousels to name a few. Many of these can be created using custom controls, but before going down that path, I always try and ask myself two questions:

Firstly, if the control does not exist, does that mean a better UI nuance is available for the device? For example, there are few mobile web controls for displaying datagrids on mobile devices. Rather than force-fitting a solution that might not work well on a 3.2″ screen, think about what alternative solutions could be used instead. For example, maybe a series of cascading list controls would actually provide for a better user experience over some custom hacked-together table control. When in doubt, try to look at how other mobile applications have used controls to represent a similar data set.

Secondly, if the control does seem to fit, but it’s just not included in the standard UI framework that you’ve chosen, think about searching for a third party solution before re-creating something new. This can apply to image carousels (PhotoSwipe is one of my favorite controls for doing this) as well as charting (there are several really good JS based charting controls out there).

Make your mobile web app look and feel like it belongs with native applications.

Why not go that extra step and have your mobile application look like it belongs with other native applications on the device? A couple of small recommendations for this one:

Firstly, never show the address bar in your mobile application. Simply use a <viewport…/> tag to have your application run in full screen mode. The user will still be able to get to the address bar, but it will be hidden from view by default. (side note – jQuery Mobile now performs this automatically without the need to do “scroll to” events in JavaScript).

Secondly, if you are targeting iOS devices, consider using Cubiq’s AddToHome JS library. This is an excellent add on that will display instructions for the user to add the application to the iOS home screen, enabling the application to have it’s own icon and run completely full screen when launched.

Don’t go creating your own username and password database

Have users sign on to your application can be very useful for security of the application and for storing preferences and other settings. Unless you have a very strong reason however, I recommend that you avoid creating your own username and password database for your application. Doing so can seem really easy at first, but as your application gets more popular you’ll be left with a nightmare situation of having to deal with registration issues, password resets, and all of the other administration that comes with owning your own identity provider.

If you are building a mobile web application for the enterprise, I suspect you’ll already be thinking about this – either hooking in to an existing Active Directory instance or other identity provider (although you’ll likely need to consider how this will work outside the firewall when your mobile users are accessing your application via a public connection).

If you are building a public-facing application however, an efficient solution can be to federate with an existing identity provider. Chances are your users already have a Google, Yahoo, or Facebook account. Why not take advantage of this and use this sign-in information to authenticate the user for your application? This can be done in a couple of different ways – either with a native SDK from one of the providers – or using a federated service such as Microsoft Azure’s Access Control Service. This is a simple service to setup, which will enable you to configure a list of providers and returns a bag of claims to your application which you can use to match up with a list of settings, preferences, etc. There are a few caveats with this approach, especially as some of the providers return the information via a post back (which can really upset your mobile application if you’ve pre-fetched all of the pages in to the DOM beforehand). This is something that I’ve written previously about in this post.

Make your Mobile Web application perform well

It might sound obvious, but if you want your Mobile Web application to come anywhere near to the performance of a native application, you’ll want to keep a keen eye on performance. Generally, I’ve found there are three main causes of bad performance in Mobile Web applications:

First is server-side generation of the UI and round tripping (as discussed in the point on client-side JavaScript earlier). If you are generating any of the UI on the server-side or making any synchronous server-side calls, you are more than likely to run in to trouble.

Second is too many CSS effects/transitions. Many of the UI frameworks, including jQuery Mobile, include several page transitions for when the user navigates between different pages. Unless you are exclusively targeting iOS devices, I would recommend turning all of these off. Many of the older Android devices don’t implement a version of Webkit that supports hardware acceleration – plus they are running on less capable hardware – so to avoid creating an application that stutters on Android devices, it’s best to disable any transitions and effects.

Finally, watch out for too many registered JavaScript events (especially on the class level). The JavaScript performance on mobile browsers can be much lower than desktop equivalents, and if you are not careful you can end up where the performance of the browser is being compromised by too many registered events. Often this will only add 100ms to various events, but combine this with specific events (such as a button tap) that must immediately navigate to another page, any delay over 100ms might be enough that your user thinks that the button wasn’t pressed correctly. They’ll press it again, and before you know it you have two JavaScript navigation events that you’ll need to handle.

Wrapping up

A bit of a lengthy post, but I hope that this is useful if you are heading down the path of developing Mobile Web applications. If you’d like more information on this, or maybe to share with colleagues, I’ve uploaded this presentation to SlideShare that goes through the above list in some detail.

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Authenticating with Google, Facebook, and others from your jQueryMobile Application

In my last post, I showed how to implement authentication using Google, Facebook, etc. for your iOS application – using the Windows Azure Toolkit for iOS.  This works well for iPhone applications written in Objective C, but what if you are developing a Web based mobile applications that span multiple platforms?  Given that everything is using Web pages, you would hope that it would be a little easier, but things can get tricky – especially if you are using jQueryMobile. 

Having implemented this a couple of times now, here is a rough guide of how to integrate AppFabric ACS (Access Control Service) authentication into a jQueryMobile application. (There is already a ton of documentation of both jQueryMobile and ACS, so I’m assuming that you understand the basics of how these both work).   

Step 1:  Create your own provider selection screen

When you first start playing around with using ACS on mobile web browsers, the first thing you’ll notice is that the default login page isn’t that nice. 

image

While the functionality of logging in will work, users have to pinch zoom to be able to read the buttons, which isn’t a great experience.  It also doesn’t fit in with any jQueryMobile theme that you may have created.  To overcome this, we can create our own provider screen. 

image

To build something similar to the above, I’ve used a jQueryMobile Dialog (which has an automatic border as well as a background effect).  The basic code for the screen looks like the following:

<!DOCTYPE html>
<html>
<head>
    <title>Select Login Provider</title>
</head>
<body>
    <div data-role="dialog">
        <div data-role="header">
            <h1>Select Login Provider</h1>
        </div>
        <div data-role="content">
            @{
                if (ViewBag.JSONProviders != null)
                    {
                    var providers = Json.Decode(ViewBag.JSONProviders);
                    foreach (var provider in providers)
                    {
                        <button type="button" onclick="javascript:window.location.href='@provider.LoginUrl'">@provider.Name</button>
                    }
                }
            }
        </div>
    </div>
</body>
</html>

As you can see from the above, the form is built by parsing a JSON object containing a list of identity providers and creating buttons for each provider – setting a name for a button and setting an on click action to the URL.  (The above code uses the Razor-based syntax for  ASP.NET MVC, but the same will work just by using JSON calls in regular Javascript). 

Two things to note here:

1.  It’s really important to use window.location.href instead of an <a> anchor when linking to the provider – otherwise you’ll break the AJAX model of your jQueryMobile app and a new browser window will be launched (which looks horrible, especially in full screen web applications).

2.  You are probably asking yourself where the JSON objects actually come from.  This brings us to our next point…

Step 2:  Make a call to the ACS JSON endpoint

The buttons in the form are based on identity providers, which you likely setup when you configured ACS.  These providers can be extracted as JSON objects using a JSON based endpoint that the ACS service providers. 

Here’s the URL of the JSON endpoint for ACS v2.

https://{0}.accesscontrol.windows.net/v2/metadata/IdentityProviders.js?protocol=wsfederation&realm={1}&reply_to={2}&context=&request_id=&version=1.0

{0} is the namespace of your ACS service

{1} is the realm within your ACS service

{2} is an optional URL (which must be HTML encoded) that specifies where to return the browser once authentication has been completed.  Remember, if you are using AJAX navigation, then you’ll want to pass in the correct #-prefixed syntax.  For example a return URL of the following:

http://localhost/MyWebApp#/MyWebApp/Accounts

Will instruct the ACS service to return to the Accounts page in your jQueryMobile app.

Again, you can make the call to the JSON endpoint using Javascript, or if you are using ASP.NET MVC like in Step 1 I would recommend creating a controller action called Providers which passes the return JSON object in a ViewBag. 

Step 3:  Launch the providers screen from your app

Finally, once you have your provider screen created, you’ll need to call it when authentication is required.  There are a couple of different ways of doing this – if you are using Javascript only, then create and maintain a variable called claims – which corresponds to the claims bag returned from the service (when the ACS service returns it does a post back to your application so that you can capture the claims).  Secondly, if you are using ASP.NET MVC then you can create a second action on the Account controller called claims with something similar to the following:

public JsonResult Claims()
{
    return Json(string.Join("n", ((IClaimsIdentity)this.User.Identity).Claims.Select(c => c.ClaimType + ": " + c.Value).ToArray()));
}

This will return the claims bag directly from the User.Identity property from the controller.

Well, just a short overview, but if you are thinking of implementing Google and Facebook authentication in your jQueryMobile application, hopefully this has been of some help.

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

TechEd 2011 Slides – DPR304

Thanks to everyone that came to my session at TechEd 2011 yesterday – it was a great crowd, and the presentation was a lot of fun to put together. My apologies for any confusion with the title (i.e. not making it explicit that it was a developer talk in the title) – this will definitely be something that we address next time.

You can find the slides from the talk below, and the source code of all demos can be found on GitHub. Hope you enjoy, and look forward to any feedback.

*** Update – corrected Session code in title ***


  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Using Apple Push Notifications from Windows Azure

In my MIX11 session last week I demonstrated how to create push notifications to iPhone and iPad devices from Wndows Azure.  I’ve put together this blog post to share more detail and the source code for how this works.

Firstly, if you haven’t already, you will need to register your iPhone/iPad application for push notifications.  To do this, log into the iOS developer center (you’ll need to be a registered Apple Developer) and in the provisioning portal setup a new App ID, enabling it for push notifications.  Here’s the App ID for my MIX demo:

image

With the development certificate that you downloaded during this process, create a new Azure worker role and import the certificate into a folder called “certs”:  In addition, you’ll need to configure the properties of the certificate file such that the build action is set to “Content”.

image

(I’ve deliberately skimmed over the previous points of creating and App ID and Azure Worker role as they are both well documented by Apple and Microsoft).

 

To start configuring the worker role for push notifications, first add a reference to the Windows Azure Storage Client (Microsoft.WindowsAzure.StorageClient) library.  In the OnRun section of the worker role, access the Azure queue that messages are going to be placed in. 

StorageCredentials creds = new StorageCredentialsAccountAndKey("YOUR ACCOUNT NAME", "YOUR ACCOUNT KEY");
  
CloudQueueClient cqc = new CloudQueueClient(""YOUR QUEUE URL”, creds);
var testQueue = cqc.ListQueues().First(q => q.Name.StartsWith("YOUR QUEUE NAME"));

Then, still within the OnRun method, create a routine that checks the queue for incoming messages and sets up the connection to the APN (Apple Push Notification) service.

while (true)
            {
                Thread.Sleep(10000);

                if (testQueue.RetrieveApproximateMessageCount() != 0)
                {

                    List messages = testQueue.GetMessages(testQueue.RetrieveApproximateMessageCount()).ToList();
                    foreach (CloudQueueMessage message in messages)
                    {
                        Trace.WriteLine("Retrieved message from Queue: " + message.AsString);
                        // open the APN connection
                        InitializeAPN();
                        // send message
                        string session = message.AsString.Substring(0, message.AsString.IndexOf(':'));
                        SendAPNMessage(message.AsString, session);
                        // tear down the APN connection
                        CloseAPN();

                        testQueue.DeleteMessage(message);
                    }
                }
            }

You’ll probably want to do something a little more elegant than “while (true)” but this works for the purposes of this post.  Also, as I mentioned in the talk, you may or may not want to setup and tear down the connection to the APN for each message that you send.  If you are planning to send a large volume of messages to a large number of devices, Apple may view this as a denial of service attack and refuse your connection.  A more prescriptive approach in this scenario would be to instead open the connection in the OnStart method and keep it alive during OnRun.

Within the worker role, setup the following declarations.  Most of these should be straightforward, and you’ll need to replace a number of them with your own details. 

private static string HOST = "gateway.sandbox.push.apple.com"; 
  
private static int PORT = 2195;
private static string CERT_PASSWORD = "YOUR PASSWORD";
private static X509Certificate2 CLIENT_CERT = new X509Certificate2(Environment.GetEnvironmentVariable("RoleRoot") + @"approotcertsmix11_dev_cert.p12", CERT_PASSWORD);

private static X509Certificate2Collection CLIENT_CERT_COLLECTION = new X509Certificate2Collection(CLIENT_CERT);
private static string DEVICE_TOKEN = "YOUR DEVICE TOKEN";  //Replace this with the Device token we obtain later on in this example

private TcpClient client;
private SslStream sslStream;

With these declarations in place, we can now start writing the APN code.  First, create an IntializeAPN method, responsible for setting up the connection to the APN.

private void InitializeAPN() 
  
{
    client = new TcpClient(HOST, PORT);
    sslStream = new SslStream(client.GetStream(), false);

    try
    {
        sslStream.AuthenticateAsClient(HOST, CLIENT_CERT_COLLECTION, SslProtocols.Tls, false);
    }
    catch (AuthenticationException ex)
    {
        Trace.WriteLine("Could not open APN connection: " + ex.ToString());
    }
    Trace.WriteLine("APN connection opened successfully.");
}

Then, create a method called SendAPNMessage which will construct and sent the push notification message in the correct format. 

private void SendAPNMessage(string message, string session) 
  
        {
            try
            {
                MemoryStream memoryStream = new MemoryStream();
                BinaryWriter binaryWriter = new BinaryWriter(memoryStream);

                // construct the message
                binaryWriter.Write((byte)0); 
                binaryWriter.Write((byte)0); 
                binaryWriter.Write((byte)32);

                // convert to hex and write
                byte[] deviceToken = new byte[DEVICE_TOKEN.Length / 2];
                for (int i = 0; i < deviceToken.Length; i++)
                    deviceToken[i] = byte.Parse(DEVICE_TOKEN.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
                binaryWriter.Write(deviceToken);

                // construct payload within JSON message framework
                String payload = "{"aps":{"alert":"" + message + "","session":""+session+"","badge":1}}";

                // write payload data
                binaryWriter.Write((byte)0);                 
                binaryWriter.Write((byte)payload.Length);    
                byte[] payloadBytes = System.Text.Encoding.UTF8.GetBytes(payload);
                binaryWriter.Write(payloadBytes);
                binaryWriter.Flush();

                // send across the wire
                byte[] array = memoryStream.ToArray();
                sslStream.Write(array);
                sslStream.Flush();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
            Trace.WriteLine("Message successfully sent.");
        }

You’ll notice that my SendAPNMessage method signature contains a “session” value.  For the purposes of the demo, I was sending across the session code that had changed as an explicit value in the notification message.  Feel free to change or remove this as you need.

Finally, the close method is called to close the connection.

private void CloseAPN() 
  
{
    client.Close();
}

At this point, you might be wondering how you obtain the DEVICE_TOKEN value for the above.  This is not the UDID of the device, but instead a separate token that is generated by the phone itself.  To get this token, and to handle incoming push notifications, let’s turn our attention to the XCode project.  For my demo I was receiving push notifications within a PhoneGap application, but this code will work equally in a regular native client application.

First, we need to instruct the application to register for APN messages.  This is done using the registerForRemoteNotificationTypes method.  You’ll need to call this method when the application first starts up (for PhoneGap projects, this can be in the init method of the AppDelegate).

NSLog(@"Registering for APN"); 
  
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];

This method has three callbacks that it can take advantage of.  One to indicate that registration was successful (we also get the Device ID from here), one to indicate that something went wrong (e.g. if we are running in the simulator, which doesn’t support push notifications), and one for when we actually receive a message).

The first two are easy to handle:

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
  
   
    NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
    NSLog(@"%@",str);
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
   
    NSString *str = [NSString stringWithFormat: @"Error: %@", err];
    NSLog(@"%@",str);   
}

Note how the first method (didRegisterForRemoteNotificationsWithDeviceToken) is where we actually extract the DEVICE_TOKEN string required in the worker role.  You’ll have to run this once, and copy and paste appropriately.  Of course, in a production environment, we would likely pass this value to the service via a separate call. 

The third callback gets called when the device actually receives a message.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { 
  
   
    for (id key in userInfo) {
        NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
        NSString *payload = [NSString stringWithFormat:@"%@",[userInfo objectForKey:key]];
       
        // work out the session code from the JSON payload
        NSRegularExpression* regex;
        NSTextCheckingResult* result;
        NSError* error = nil;
        NSString* regexStr = @"session = ([^']*);";
        NSString* value = nil;
        regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
        result = [regex firstMatchInString:payload options:0 range:NSMakeRange(0, payload.length)];
       
        if(result && [result numberOfRanges] == 2)
        {
            NSRange r = [result rangeAtIndex:1];
            value = [payload substringWithRange:r];
        }
        if(value)
        {
            NSLog(@"Found session value in payload: %@",value);
            NSString* jsString = [NSString stringWithFormat:@"handleOpenURL("http://URLHERE.cloudapp.net/Session/Lookup?session=%@");",value];
            [webView stringByEvaluatingJavaScriptFromString:jsString];
        }
    }       
}

 

As you can see above, this method parses the payload of the message, tries to work out the session code, and if one is found, creates a new javascript call to a method called handleOpenURL which instructs PhoneGap to call the method of the same name.  Of course, you are going to want to configure this for your own scenario, but hopefully this gives you a sense of how to pass a value as part of the message, and then take an action on that accordingly. 

Well, that wraps up this post.  I hope you enjoyed the talk at MIX, and that this code is useful if you have services in Windows Azure that have a need to push notification messages to iPhone and iPad devices.




  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Meet me for lunch!

I’m on the road for the next few weeks, visiting locations across the US, holding a series of “Mobility lunches”.  These lunches are a great way to get up to speed with what mobility means for your organization – from the current state of the mobile market, handsets, tablets, through to building applications and solutions for your own employees and customers.

Each event is held over lunch, and it’s a great opportunity to network with peers in your region as well as folks from the local Neudesic office.  Here is the schedule – it’s free to attend, although you do have to register!  Look forward to seeing you there!

April 19 – San Diego

April 20 – Los Angeles

April 26 – Denver

April 27 – Las Vegas

April 28 – Phoenix

May 5 – Orange County

May 10 – Chicago

May 11 – New York

May 12 – Philadelphia

May 31 – San Francisco

June 1 – Seattle

June 7 – Dallas

June 8 – Houston

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Developing iPhone and iPad apps that leverage Windows Azure

Thanks to all that came to my session at MIX11 last week – it was a lot of fun to put together despite a couple of demo glitches!  You can now view the recording of this online, as well as browse and download the slides below. 

I’ll be sharing the source code for the demos in the next couple of posts.

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

iPhone and iPad Security

Thanks to everyone that attended my April WebCast on iPhone and iPad Security. 

“Your organization is starting to rely on iPhone and iPad devices to do business.  But how secure are these devices, especially in an enterprise setting?  How do you apply policy to the device?  What security considerations should you be thinking about in your own applications?  And what happens when people in your organization "jailbreak" a device?”

This was a fun presentation to put together, covering many aspects of security from policy, data protection, network, and application security.

You can view the recording here, or browse through the slides on slideshare below. 

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS