CodeStock 2011

I got a chance this weekend to attend CodeStock in Knoxville, TN for the first time.  Special thanks to everyone involved in organizing the conference.  I got the chance to learn a lot by attending some great sessions, including those dealing with the fall out of the layoff of the Mono team following the purchase of Novell by Attachmate.

I also had the chance to present a couple sessions on native Android development, both my Intro talk as well as my more advanced Upgrading Android Apps session.  Both of the talks were well received and I appreciate everyone coming by to listen to me talk.  Getting the chance to converse with people about these topics, as well as many others, is part of what makes speaking and attending these conferences so much fun.

As promised to those who attended, I am providing the slide deck and code for both talks, slightly modified to remove any sensitive data that is contained within the application.  Please feel free to contact me on Twitter (@jfarrell) or via email (imjason@gmail.com) if you have any questions.  As always, thank you for attending CodeStock giving me the chance to meet you.
http://cid-630ed6f198ebc3a4.office.live.com/embedicon.aspx/Source/AndroidIntroDemos_codestock2011.zip http://cid-630ed6f198ebc3a4.office.live.com/embedicon.aspx/Source/UpgradingAppDemos_codestock2011.zip

Code First Entity Framework

Recently we had Chris Sutton stop by the West Michigan .NET User Group to talk about Code First Entity Framework, one of the hotter topic in the Microsoft space.  The Code First Entity Framework represents an interesting step for Microsoft with giving control back to the developer over their model, similar to how NHibernate handles things.

The CF EF model allows developers to use POCOs exclusively with a defined Context class to persist data to the layers of their database, this allows it to work well with DI which is a growing trend in development.  Using standard mapping conventions developers can keep their models clean and avoid the litany of craziness that is often associated with generated models.

Taking many of the conventions from NHIbernate and other clean model driven ORM platforms CF EF takes the best of Microsoft’s powerful EF framework and combines it with these principles to provide for an exceptional development experience.

Chris Suttons presentation materials will be made available on the West Michigan .NET User Group website: http://www.wmdotnet.org, visit for more details

Upgrading Android Applications

This weekend at the Chicago Code Camp I will be debuting a new presentation focusing on advancing the quality of Android applications.  Mostly we will focus on various aspects that, when leveraged correctly, can improve the usability of your application and the likelihood that it will continue to be used by users.

The principle point of the talk was to build on the concepts from the Intro talk and understand the extensibility points within Android.  Mobile users are a special breed of users that are mobile and require apps that fit their lifestyle.  Making users wait is not acceptable and may result in someone getting hit by a car.

Focus Points:

  • Styles
  • Themes
  • Notifications
  • Dialogs
  • Indicators
  • Camera usage
  • Search

Understanding how to achieve these goals through leveraging what Android gives you is essential to meeting the usability needs of your end users.  We talked about hiding “jankiness” using dialogs and indicators to manage user expectations, and doing these operations in AsyncTask.

In response to the feedback I received, I am making available all assets for the presentation available here.  Please note that I intend to make changes ahead of CodeStock where this talk will be presented next.

http://cid-630ed6f198ebc3a4.office.live.com/embedicon.aspx/Source/UpgradingAppDemos%20-%20Release.zip

Please feel to leave any comments on topics that I didn’t cover and that you would like to see or topics that I did cover that you didn’t like.

Advanced Android Presentation

In preparation for my speaking engagements at CodeStock and the Chicago Code Camp, I am preparing a new presentation which supplements my existing, and soon to be retired, presentation “Introduction to Android”.  The title of this new presentation is, tentatively and uncreatively, “Advanced Android”.

This is the first time I have tried such a presentation where the goal is to simply show and discuss concepts in Android that many developers will use to simplify their development of Android apps.  However, there are a bevy of topics I could cover.  With that in mind, below is a tentative outline of presentation, please comment on anything I have missed or what topics you find most interesting.  Thanks

  • Introduction
    • Android growth and popularity
    • App expectations
  • Strategies
    • Dependency Injection (Guice)
      • View finding
      • Data Layer management
  • UI
    • Menu
      • Interaction
      • Rules
      • Customizing
    • ListView
      • Adapters
      • Custom list item templates
    • Dialogs
      • Alert
      • Custom
    • Notifications
      • Raising
      • Using Receivers
  • Using External Resources
    • Intents – provide advanced understanding and options
      • Camera
      • Contact List

Please take a look at this list and let me know if there is something I missed or what topics on here are really not interesting, if any Smile.  I will work through the list and start putting things together over the course of the next week, gotta hurry though, Chicago Code Camp is May 14.

Switching to IntelliJ

Developing in Android is an activity that is done in Eclipse the majority of time, after all Google supports the Android Developer Tool (ADT) for the platform which makes development a breeze with one exception: you are still using Eclipse.

Now don’t get me wrong, I don’t mind Eclipse, in fact when it comes to trying out a new language I can almost always be assured that a plugin exists and I get to play in an IDE that I am familiar.  But, I have always found then when I start getting into serious development and heavy coding Eclipse falls short, especially with respect to performance.  I think it tries to be “a jack of all trades, master of none.”, perhaps the most frustrating aspect is the intelli-sense support; I come from .NET where Visual Studio is bar none the best IDE one can work in, perhaps my standards are just too high.

Luckily JetBrains, the same company which produces my favorite refactoring tool ReSharper, saw this shortcoming as well and created IntelliJ and, as luck would have it, due to the popularity of Android they began integrating Android supporting into their IDE, which is available for free via the Community Edition, though I am considering buying the full, if only to support the development, might serve as my official non Mono/.NET development IDE.

When I first started exploring this, the integration was still not all there, it is now.  The only thing really missing that Eclipse has is the management of external resources (SDKs, Emulator) through AVD built right into the IDE, IntelliJ does not.  However, managing this content can easily be accomplished by running the android.bat file in your tools directory where you store your SDK libraries on your machine (below)androidbat

This aside you can do everything in IntelliJ, and the performance of the development aid tools are just so much better.  If you are starting with a fresh install on a system devoid of Android, hit up http://developer.android.com/sdk/installing.html and skip step 1 and 3 (and any others referring to Eclipse or ADT).

The Android plugin will still come bundled with the Community Edition, which you can download here.  It will automatically read your system for Android SDKs installed, so be prepared to point to these SDKs (in other words, know where you installed them).

One of the early complaints that I had was the inability to switch which SDK I was using on the fly.  Its not at all common for this to happen due to the rapid proliferation of Android and the decision of what features you want your apps to use.

Simply right click your project and select Module Settings.  Select the Dependencies tab and press “Add”, you will see the following:ModuleSettings

In my case, I have all version of Android since 1.6 installed, excluding 3.0.  1.6 is NOT in the list cause the project is currently using it.  From this dialog you can easily Add/Remove the SDKs your project is using.

Selecting the Emulator is equally as easy, you simply need to add configurations:EditConfigurations

Notice, when you first enter this mode the dropdown shown above will be empty, so you will only have “Edit Configurations”.  The screen is pretty self explanatory, hit the indicated plus button to add configurations.Configurations

The square indicates the button to add to add a new launch configuration.  I tend to create a new launch configuration for each project which allows me to easily control different version requirements for my apps.  You can of course share the configuration across multiple apps.

Also on the screen, indicated by the arrow, you can select the emulator profile you wish to use.  These are created using the AVD Manager which we launched using the android.bat file above.  The above is my naming convention describing the emulators OS version and resolution.

All in all, I have really enjoyed using IntelliJ for my Android editing.  The only real obstacle I ran into was the way to support a two project solution from Eclipse; the answers is multiple modules, though getting everything in IntelliJ is a bit tricky.  But despite the minor friction points because you have to do a bit more to get things working then Eclipse, development is an absolute dream, especially the intelli-sense aspect.

I do not plan to cease recommending Eclipse for beginners, but my Advanced Android talk that I will be debuting at the Chicago Code Camp on May 14, 2011 will feature IntelliJ as my IDE of choice.

Great Lakes Software Excellence Conference

 

Today, I had the chance to once again give my “Introduction to Android” talk, this time at the Great Lakes Software Excellence Conference (http://www.glsec.org).  This was my first time attending the conference, though it was the fifth time the conference had been held.  This is also the second to last time I intend to give this talk, it will be retired after I give it at CodeStock 2011 in June.  I really looked forward to this conference as it is planned by SoftwareGR (http://www.softwaregr.org) which is not the .NET crowd that I am accustomed to running with, this means new people and new ideas, both of which help inspire me in development moving forward.

In addition, despite having given this presentation a large number of times before I am lucky that the topic continually changes and the landscape of mobile development is continuously evolving.  This has allowed me to expand and change the presentation to take into account new happening, such as the situation with the Symbian operating system from Nokia and continue to provide new stuff each time I give it.

Below are the materials for my presentation.
http://cid-630ed6f198ebc3a4.office.live.com/embedicon.aspx/Source/GlsecAndroid.JasonFarrell.zip

Query for JSON in Android

One of the most common uses for a mobile device is consumption of feeds from online services such as Facebook and Twitter.  Commonly the data from these services is transmitted using either JSON or XML.  JSON is a very common path taken my developers, due to the simplified structure and reduced overhead.  In this post, I will show you how to access a public Twitter API call and read it to a common domain object.

The first step is executing the web request.  To do this we need to define a request object which effectively defines what our transmission will look like.  This request is processed by an HttpClient which handles the various points of interest in the request lifecycle.  The code below illustrates:

   1: public static TwitterResult performLookup(String handle) {

   2:     String lookupUrl = String.format(

   3:         "http://api.twitter.com/1/users/show.json?screen_name=%s",

   4:         handle);

   5:     

   6:     HttpClient client = new DefaultHttpClient();

   7:     HttpGet getRequest = new HttpGet(lookupUrl);

   8:  

   9:     HttpResponse response = client.execute(getRequest);

  10:     ResponseHandler handler = new BasicResponseHandler();

  11:     String json = handler.handleResponse(response);

  12:         

  13:     return new TwitterResult(json);

  14: }

Notice how we use the HttpResponse and ResponseHandler to handle the call coming back.  In this case we are getting the response back as a string, which is actually a JSON string, due to the way the call was made.

We pass the string to the constructor of TwitterResult the parsing of this object is handled by Android using the JSONObject type, see below:

   1: public TwitterResult(String json) {

   2:     JSONObject object = new JSONObject(json);

   3:     setTwitterHandle(object.getString("screen_name"));

   4:     setLocation(object.getString("location"));

   5:     setDescription(object.getString("description"));

   6:     setFriendCount(Integer.parseInt(

   7:         object.getString("friends_count")));

   8:     setFollowerCount(Integer.parseInt(

   9:         object.getString("followers_count")));

  10:         

  11:     object = object.getJSONObject("status");

  12:     setMostRecentStatus(object.getString("text"));

  13: }

As you can see, using JSONObject the parsing becomes significantly easier.  Note that I just realized that this is making needless calls to parseInt as JSONObject supports a getInt call which will work in its place.

Twitter Authentication on WP7

One of my current areas of interest is Twitter and how it can be integrated into applications to support more socially aware applications.  Twitter uses oAuth to authenticate its services, thus along with my interest in Twitter I have also developed an interest in oAuth.  This blog entry will describe the method I used with a Twitter app I wrote as an experiment for Windows Phone 7.  To assist me in access the REST APIs of Twitter, I used the Hammock REST Client Library.

To begin, any attempt to authenticate requires a Request Token from the Twitter service to ensure you have the rights to request authentication.  This is done with the following code.

   1: public void RequestToken(string consumerKey, string consumerSecret)

   2: {

   3:     var oauth = GetBaseWorkflow(consumerKey, consumerSecret);

   4:     oauth.RequestTokenUrl = Constants.REQUEST_TOKEN_URL;

   5:     oauth.CallbackUrl = Constants.CALLBACK_URL;

   6:  

   7:     var info = oauth.BuildRequestTokenInfo(WebMethod.Get);

   8:     var oAuthQuery = CreateRequestForQueryInfo(info);

   9:  

  10:     oAuthQuery.QueryResponse += (ob, ev) =>

  11:     {

  12:         var parameters = ev.Response.GetQueryStringParameters();

  13:         onTokenRequestComplete(parameters["oauth_token"]);

  14:     };

  15:  

  16:     oAuthQuery.RequestAsync(Constants.REQUEST_TOKEN_URL, null);

  17: }

The parameters to this function are the consumer key and consumer secret values which are provided by Twitter which identify the application.

The thing to note in this code block is the callback URL.  This value will play a significant role in the future code.

What this code block returns is an AuthorizeURL that will allow a user to authorize the application to access their Twitter account.  If you notice the QueryResponse portion, this is an event that fires an event which is listened to by the outside code base.  The event passes us the URL and we use a WebBrowser control to display the Authorize page.

The updated screen with the URL is shown below within a WebBrowser control.screen1

This way the authentication information can be inputted by the user.  As a rule with oAuth we never store passwords, but instead we store a access token and its secret token to authenticate our requests.

At this point, Twitter handles the processing and noting that our application has the rights to access your Twitter account.  Once Twitter, completes this process, it will send us to our callback URL, which will be intercepted by our WebBrowser control as shown below:

   1: private void webBrowser_Navigated(object sender,

   2:                           NavigationEventArgs e)

   3: {

   4:     progressBar.Visibility = Visibility.Collapsed;

   5:     if (e.Uri.ToString().Contains(Constants.CALLBACK_URL))

   6:     {

   7:         var parameters = e.Uri.Query

   8:             .GetQueryStringParameters();

   9:         AuthorizeToken(parameters["oauth_token"],

  10:             parameters["oauth_verifier"]);

  11:         webBrowser.Visibility = Visibility.Collapsed;

  12:         progressBar.Visibility = Visibility.Collapsed;

  13:     }

  14: }

Basically, if we see the callback URL being used we understand the process to be complete and we can move to the next stage.  When this is seen we access our Query String and pass the access token (represented by oauth_token) and the verifier (represented b oath_verifier) to our AuthorizeToken function, shown below:

   1: private void AuthorizeToken(string accessToken, string verifier)

   2: {

   3:     _authorizationWrapper.ValidateAccessTokenComplete += ev =>

   4:         Dispatcher.BeginInvoke(() =>

   5:         {

   6:             ((App)Application.Current).Context =

   7:                 new AuthorizationResult

   8:                 {

   9:                     AccessToken = ev.Token,

  10:                     AccessTokenSecret = ev.TokenSecret,

  11:                     ScreenName = ev.ScreenName

  12:                 };

  13:  

  14:             NavigationService.Navigate(

  15:                 new Uri("/ConfirmAccount.xaml",

  16:                     UriKind.RelativeOrAbsolute));

  17:         });

  18:     

  19:         _authorizationWrapper.ValidateAccessToken(

  20:             Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET,

  21:             accessToken, verifier);

  22: }

As you can see, we are actually receiving the username from Twitter and not from any input from the user to our application.  This ensures that we are upholding the principal points of oAuth which is we never store passwords or personal login information, we are leveraging a third party to handle the authentication.

Once this process is complete, we return to the process of the application itself, through a redirect to ConfirmAccount.xaml.  One of the things I am working on is a pattern for easily storing data, either permanently or temporarily, in a place that can be accessed from request to request.  In this case we are calling it context and storing the result of authorization.  This accessed on the confirmation page by the following code, which saves the data to Isolated Storage through my custom ORM framework:

   1: protected override void OnNavigatedTo(NavigationEventArgs e)

   2: {

   3:     var result = GetContext();

   4:     viewModel.ScreenName = result.ScreenName;

   5:     viewModel.AccessToken = result.ScreenName;

   6:     viewModel.AccessTokenSecret = result.AccessTokenSecret;

   7: }

   8:  

   9: private void btnConfirm_Click(object sender, RoutedEventArgs e)

  10: {

  11:     viewModel.SaveAccount();

  12:     NavigationService.Navigate(new Uri("/Accounts.xaml",

  13:         UriKind.RelativeOrAbsolute));

  14: }

This completes the save process and gives us the ability to use oAuth to authenticate requests to the service.  While the matter of using my own XAML page to handle authorization is a nice to have, in some ways, directing user to Twitter allows them to feel more at ease when entering this sensitive information.  Also, with the way this is designed, I can assure myself that I am not storing any of this sensitive information, which is the benefit of using a third party authorization technique like oAuth.

West Michigan .Net User Group: JQuery

Tonight we got the chance to listen to Karl Swedberg talk about JQuery.  Karl is a member of the JQuery development team and has some great insight on the development challenges facing developers when using JQuery.  This in mind, I requested that he create a more advanced presentation that was beyond the basics of JQuery.

What we got was awesome!! I learned so much about JavaScript and JQuery including quirks and many of the tricks the experts use to squeeze every ounce of performance out of my scripts.  It was exactly what I was looking for for the User Group, a different and more advanced take on JQuery.

Really gotta thank Karl for coming out and sharing many of the finer points of JQuery.

To Meijer

Over the past few months I have not been satisfied with the direction RCM continues to drift.  Thus, I decided it was time for a change of scenery and in late November, I began searching for a new position.

I am please to announce that that search finally came to an end last Friday with my acceptance of an offer to work at Meijer Inc.  For those of you who do not know, Meijer is a huge retail company based out of West Michigan.  I will be heading to help support their Labor Management applications, for me it is a bit of nostalgia as I spent 10yrs in my youth as a cashier for Meijer and to return to them in such a role is quite gratifying.

It should be quite interesting, getting a chance to explore the corporate computing world as well get first hand lessons in scalability, an area that I admit I am relatively weak with respect to other areas of development.  I also get to join some former RCM guys and reunite at our new company.

My last day will be 4/1 at RCM and my first day at Meijer is 4/4.  Really looking forward to this change of scenery.