Getting Started with Metro–Repository and Display (p2)

First an update to the previous entry.  Special thanks to David Kean, of Microsoft for pointing out that the HttpClient class exists for the sole purpose to handle web requests, the way I was doing it was outdated.  I actually knew of this class, but mistakenly thought it was WebClient.

Since the last coding adventure I decided to move some code around and work with a more established pattern for accessing my data.  I defined this interface for my repository (just a start).

public interface ITrendRepository
{
     Task<IList> GetTrendLocationsAsync();
     Task<IList> GetAvailableTrendsAsync(IList locs);
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Both of these methods will, potentially, be marked async in their implementations, but you are not allowed to specify it here. It makes sense, because the underlying implementation may not require async capability, Ill explain more in a moment.

I am creating a very simple repository layer here, within which I have two repositories: MockTrendRepository and ActualTrendRepository.  In the Mock version, I am returning hard coded data (I have hit Twitter’s rate limit too much to keep using actual).  In the Actual version, I am hitting Twitter directly.

Coding MockTrendRepository was interesting. I don’t want to show a ton of code, so this is one of the methods:

public async Task<IList> GetTrendLocationsAsync()
{
    return new List
        {
            new TrendLocation
            {
                LocationIds = new int[] {},
                LocationName = "United States"
            },
            new TrendLocation
            {
                LocationIds = new int[] {},
                LocationName = "United Kingdom"
            },
            new TrendLocation
            {
                LocationIds = new int[] {},
                LocationName = "Mexico"
            },
            new TrendLocation
            {
                LocationIds = new int[] {},
                LocationName = "Russia"
            },
        };
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Remember, when you mark a method as async it must return Task, Task, or void.  However, if you look at this method, you can early see I follow that rule with method definition, but the method actually returns a straight List, which is T in the Task declaration.

My explanation for this is, because there is no await method being used, the code is deemed to run synchronously, thus the compiler will understand that it wont need to wrap the method body with Task, so its superfluous in this case. (notice, VS11 Beta, does underline the method in green to indicate you are missing await in the method body; this is not an error.

Making it Metro

So, now we have all of our data, we need to present it to the user.  At the moment this part is still unfinished.  I am currently at the point where my data displays but is not following Metro guidelines, but I figured its good to get starting talking about the GridView control.

If you have seen Metro applications before, you are familiar with seeing a GridView, or a control similar to it.  It allows for Groups which are arranged horizontally under the main title and then rectangular boxes around the individual items in the datasource, this what I am currently looking at now:

MetroScreen

I swear, from all the Microsoft talks, that there is a way to get the appropriate Metro boxes around these items without specifying the template explicitly.

GridView requires a CollectionViewSource as its datasource.  Since we are grouping these items, we set the IsSourceGrouped property true, here is my XAML:

DatasourceDeclare

Understand that CollectionViewSource is a standard .NET class, it is sealed so it cannot be inherited.  In order to bind to this properly, use a standard LINQ statement to group your data by the appropriate key and simple assign it to the resource, the cvs member variable.

var bindingData = from at in availableTrends
                  group at by at.Country into g
                  orderby g.Key
                  select g;

cvs.Source = bindingData;

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This is different from the previous version of VS11, where you used IGroupInfo interface, this has now been removed as a means to simplify this process.

Setting the GridView Parts

The GridView control has several parts that we care about: ItemsPanel, ItemTemplate, GroupStyle.HeaderTemplate, and GroupStyle.Panel.

ItemsPanel defines what the general layout panel for the control is.  GridView will display groups in a certain way.  Typically, you’ll want a horizontal StackPanel, so the group items are laid out left to right.  This will leverage horizontal scrolling.

     
          <StackPanel Orientation="Horizontal" />
     

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The ItemTemplate is our old standby, from WPF, for laying out the individual items in the ItemsSource.  This template controls how the individual items look as it they are laid out within the master ItemsPanel.  In this case, it’s a Grid (background LimeGreen) with a TextBlock showing the trend.

<GridView.ItemTemplate>
     <DataTemplate>
          <Grid Height="150" Width="150" Background="LimeGreen">
               <TextBlock Text="{Binding Display}" FontSize="14.667"
                                  FontFamily="Segoe UI" VerticalAlignment="Center"
                                  HorizontalAlignment="Center" />
          </Grid>
     </DataTemplate>
</GridView.ItemTemplate>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The GroupStyle.HeaderTemplate, as you might expect, defines the template that will render the groups keys.  Make sure you bind whatever the display element is appropriately.  Because I am using IGrouping which defines the property Key of type TKey. Thus, the property that I use for display is Key.

<GroupStyle.HeaderTemplate>
     <DataTemplate>
          <StackPanel Orientation="Vertical">
               <TextBlock Text="{Binding Key}" FontSize="26.667"
                      FontFamily="Segoe UI" />
          </StackPanel>
     </DataTemplate>
</GroupStyle.HeaderTemplate>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The final template we define is the GroupStyle.Panel which defines the panel used to layout the items in the ItemsSource, recall the ItemTemplate defines what goes on inside this panel, so this will be a single panel definition.

<GroupStyle.Panel>
     <ItemsPanelTemplate>
          <VariableSizedWrapGrid Orientation="Vertical" />
     </ItemsPanelTemplate>
</GroupStyle.Panel>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

One of the additional guidelines for Metro’s approaching to differentiating items in terms of importance is font sizing.

  • Header – Segoe UI – 42pt
  • Sub Header – Segoe UI – 20pt
  • Support – Segoe UI – 11pt
  • Tertiary Text – Segoe UI – 9pt

Typically, either Segoe UI or Helvetica is used as font types in Metro style apps.

Next Steps

So at this point, I have gotten the basics down, but I have bad spacing between the groups.  Plus I am convinced that there is an easier way to create the Metro UI boxes for the items.  I am still researching that aspect.  I also need to create the drill down for the next level.  I am considering a change, so that I show the locations with trends instead of the all the trends.

Getting Started with Metro – A Twitter Trend Reader (p1)

Its not only because I went to the Windows 8 Developer Event yesterday, I have honestly been meaning to dive into the new features in Windows 8 and take a crack at designing apps with Metro in mind.  With that I elected to spend the majority of today working with Windows 8 and attempting to create a simple app I came up with.

Twitter tracks trends and the trends are tracked for a few select cities around the world.  I wanted to create an application that would allow users to see the full list of countries with cities in which a particular trend is being tracked.  Group these “trends” by the country and allow users to dive further in and see the relevant tweets for the particular trend.  Very simple.

Obviously the starting point for this endeavor was getting the software.  I actually installed Windows 8 on an old Tablet that I bought back before my study abroad in Japan in 2006.  I wondered if I could interact with it using the pen.  I havent used the machine for anything serious in many years.  As you might expect, the pen didn’t work and I really came to find that Windows 8 really doesn’t belong on this system, but I didn’t want to take time to install it side by side on my IBM personal laptop.

First thoughts

Ok, I will say it, the Microsoft guys really make this stuff seem easier in demos then it actually is.  First, using async and await keywords.  I have been to many talks on this new language feature but actually doing it does take more thought then I initially thought.

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
     var locations = await GetLocations();
     var data = await GetAvailableTrends(locations);
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The async keyword essentially indicates that a method should not block the UI thread.  Once the method features this keyword, you can use the await keyword.  How this has been explained to me is that await indicates the result may not be readily available, but it promises that it will be.  Thus any code that needs this result should wait.  In essence, the compiler will rewrite this code to use the TPL.  Code that is dependent on the result will in essence be place in a “continuation”.  Since both of these methods will make a web request, it is important that they both “await” the return.

Honestly, this can be confusing, as you will see, understanding how to use async and await will be critical moving forward.  It really does make things easy, but you do have to make sure you don’t rely too much on the “await”.  I found it useful to break things up into methods and mark those with await.  Remember, you can only “await” an “async” method.

Making Requests

To actually get the data, we need to make some requests, and we can use the brand new (I think) JSON handling objects in Windows.Data.

 

   1:  private async Task<List> GetLocations()
   2:  {
   3:      var request = WebRequest.CreateHttp(
   4:          "https://api.twitter.com/1/trends/available.json");
   5:      var response = await request.GetResponseAsync();
   6:   
   7:      using (var stream = response.GetResponseStream())
   8:      {
   9:          var content = new StreamReader(stream).ReadToEnd();
  10:          var locations = from jo in JsonArray.Parse(content)
  11:                                          .Select(jo => jo.GetObject())
  12:                          select new
  13:                          {
  14:                              WoeId = int.Parse(jo["woeid"].Stringify()),
  15:                              Country = jo["country"].Stringify()
  16:                          };
  17:   
  18:          var groupings = (from location in locations
  19:                           where location.Country.Length > 3
  20:                           group location by location.Country into g
  21:                           orderby g.Key
  22:                           select new TrendLocation
  23:                           {
  24:                               LocationName = g.Key,
  25:                               LocationIds = g.Where(t => t.WoeId > 1)
  26:                                              .Select(t => t.WoeId).ToList()
  27:                           }).ToList();
  28:   
  29:          return groupings;
  30:      }
  31:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Sorry, that is a lot of code.  What I really want to draw attention to is line #10, the rest of this is fairly select explanatory. Since we know what is coming back from Twitter is a JSON array (even if it might only have one result), thus we parse it as such.

Working with these new library is, quite frankly, a royal pain in the ass. First understand that each entry in the JsonArray is actually a JsonObject, but you cant run Cast, so you need to do a Select.  Next, once you have the object, you can use [] notation to reference the key you want.  This comes back as an IJsonValue. Depending on what is actually at the location you must call the appropriate method.  Above, I am calling Stringify which makes no sense to me, but I could never get GetString to work.

Its not that the library is necessarily bad or broken, it just feels weird.  I don’t like all the casting and the knowledge my code must have about what is coming back.  This part took me the longest to decipher.

Where Am I now?

At present I am nearly to the point where I have all of the data for display.  However, I am running into problems, I believe, with rate limiting on Twitter, because I am making so many requests so frequently.  I will need to find a way to cut down on the amount of traffic I am producing.  I am hoping,in a future entry, to talk about using the GridView to actually create the UI, which is, in my mind, the most alluring part of Windows 8.

Windows 8 Developer Event

For the past few months I have been reading and looking at Windows 8, the next version of Microsoft Windows featuring the Metro theme applied to their desktop systems.  Today, I went for a learning event at Navy Pier in Chicago.

I really like the Metro theme and I think that if Microsoft can get its act together and deliver a consistent message to its developers and clients, it has the potential to challenge Apple.  But Microsoft still lacks in one major area compared to Apple: marketing.  But I see improvements in this area and, in the end, consumers can only benefit from additional competition in the market.

At the core of Metro is this idea of a chrome-less design, the idea that content is first and  foremost. Mostly this applies to the apps but Sara Summers was kind enough to talk about how it can be applied to the web as well.  These apps are, quite simply, gorgeous and, in my opinion, completely outdo anything I have seen on the Apple or Android.

I really feel like the designs most designers tend to create today are born out of many older design principles, principles that may be starting to grow stale given the greater levels of interactivity we are able to attain with modern devices.  Metro just feels so much more vibrant and alive versus other UI themes.  I really think that once people start to play with this new generation of applications the difference will become obvious.

A recurring theme in many of these events is the question regarding XAML and HTML5, which one will it be.  When this question was brought up today it was answered that both will stay because both target very different things.  For developers, it really is about options.  You would rather have too many options then not enough, though too many options can also cause design paralysis.  Microsoft regards HTML5 and XAML as addressing two different areas, each of which are capable of solving different problems, thus both are supported by Windows 8.

What I am most impressed with is how much help Microsoft is giving developers in terms of templates and pre-baked controls.  I will attempt to build a very simple Twitter Reader over the course of the next couple dates.

Some things I didn’t like, I am still not sold on Windows 8 as a client desktop OS.  As a tablet and phone OS I think it is gorgeous and incredibly usable.  But put it on a machine without a touch interface and I am not certain it works very well.  While its true that touch is becoming extremely pervasive in our industry, I don’t know if we have quite reached a point where people believe their normal workstations should be touch enabled.  But this is the exactly the thinking that put Microsoft, and a slew of other companies, behind Apple, who did believe people were ready.  So maybe this is the catalyst to put Microsoft back on the map.  Only time will tell.

Bottom line though, it is a great time to be a Microsoft developer.

iOS Programming – Working with the Network

Modern applications need to connect to the network to read data from web services.  This is one of the strengths of mobile development because it use capable of delivering information specific to the end user.  iOS applications are quite capable of connecting to the network and reading data.  The following example shows my Twitter Profile application.  If you remember in part 1 we created the application but hard coded the values coming back.

Get Data Back from the Service

Generally when you return data from a service its either going to be in JSON (JavaScript Object Notation) or XML format.  My preference for services tends to be JSON because its much lighter on the way down than XML.  The following code shows how to setup a URL and query the Twitter API to get information about a user (in this case its me).

NSString *urlString = [NSString stringWithFormat:@”http://api.twitter.com/1/users/lookup.json?

screen_name=%@&include_entties=true”, twitterHandle];

NSURL *url = [NSURL URLWithString:urlString];

 

NSData *data = [NSData dataWithContentsOfURL:url];

Easy.  Just create a string (or you can do it on one line if you like, but Objective-C gets ugly fast).  Call URLWithString to create an instance of NSURL which we will be using to call our service.  The data for this is collected into an instance of NSData which uses the url object to build the data object as it comes back from the request.

Using the data in your program

So you have the data, now we have to use it.  In iOS5 there is a new class, the NSJSONSerialization class, which can read an instance of NSData and wrap it so the JSON can be read very easily.

NSArray *returnResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

NSDictionary *profileInfo = [returnResult objectAtIndex:0];

Since Twitter returns to us an array of JSON objects (though it will only ever contain one item) we set our processed JSON to a variable of type NSArray.  As mentioned, we need the very first (and only item) in this array.  This will be a key=>value dictionary which represents the contents of the JSON response.  I have decided, for sake of clarity, to break this read up.  Here is how I got the data out of the NSDictionary (which is one of the weirdest Hashtable types I have ever worked with).

NSNumber *follower_count = [profileInfo objectForKey:@”followers_count”];

NSNumber *tweet_count = [profileInfo objectForKey:@”statuses_count”];

NSNumber *friend_count = [profileInfo objectForKey:@”friends_count”];

NSDictionary *status = [profileInfo objectForKey:@”status”];

NSNumber is effectively a wrapper for int, which we need here because objectForKey returns an object and thus we can’t do a straight assignment.  Also,objectForKey is defined to return id which is a variable type.  I don’t want to say Variant ala VB, but that is what it kind of feels like, though I am told it is closer to dynamic in C#.

Notice that we did return an instance of NSDictionary for the key status, which in the Twitter API is a block of JSON to show the current status for that user.

Assign these to the properties of our TwitterProfile object (below).

TwitterProfile *profile = [[TwitterProfile alloc] init];

profile.followersCount = [follower_count intValue];

profile.friendsCount = [friend_count intValue];

profile.tweetCount = [tweet_count intValue];

profile.currentStatus = [status objectForKey:@”text”];

Return this and we are good to go.

Conclusion

Accessing data from iOS is easy and the effect is immense.  Data downloaded from the web, especially data pertaining to the end user can make your app more lively and more personable and thus, hopefully more popular.  Thanks

Beginning iOS Programming

I recently decided to put aside my differences with Apple and learn the platform.  I figure knowing Android, Windows Phone 7, and iOS is a very marketable set of skills.  For a long time I have made attempts to get into iOS but I always stumbled when I hit Objective-C.  I tried going the MonoTouch route, but I don’t really feel you can fully understand MonoTouch without understanding iOS and, by extension, Objective-C.  So with Pluralsight license in hand I decided to make a concerted effort to learn Objective-C and begin to grasp the principle of iOS programming.

After a full day of watching the Pluralsight “Introduction to iOS – Part 1” video I am amazed at how far I am come.  I decided to work up a quick Twitter Profile app.  While I am still hung up on the network communication aspect of iOS, I think I have grasped, quite well, the understanding of how to interact with UI components through Outlets and Delegates.

Understand how it works

The best way I can relate how iOS works to myself is to compare it to the MVP model of ASP .NET, with the code behind.  iOS claims to feature the MVC pattern, however, this really does seem to a big misnomer, the xib files are hardly passive and seem to be linked to a single controller (ala presenter).  Within iOS, the responsibility of responding to and communicating with the View (xib files) lies with a “view controller” which is the Presenter (not a controller).  This line of code, from the didFinishLaunchingWithOptions in the AppDelegate.m file, appears to specify this relationship:

self.viewController = [[[ViewController alloc] initWithNibName:@”ViewController” bundle:nil] autorelease];

Notice that the file extension for my xib file (ViewController.xib) is not specified.  autorelease is new in iOS as a way to handle garbage collection.

Wireup the UI controls

Placing the UI controls using Interface Builder is simple.  For my application, I am using 8 labels, a header bear, and a search bar.  This is the UI as it appears in Interface Builder:

NewImage

There are actually labels here to hold the content as it comes back.  To wire these controls up, we need to add them as properties to the ViewController.  This is similar to what happens in the code behind for .NET applications, it just happens automatically.  Here are my definitions for the controls:

@property (retain, nonatomic) IBOutlet UILabel *lblTwitterUser;

@property (retain, nonatomic) IBOutlet UILabel *lblFollowersCount;

@property (retain, nonatomic) IBOutlet UILabel *lblFriendsCount;

@property (retain, nonatomic) IBOutlet UILabel *lblTweetCount;

@property (retain, nonatomic) IBOutlet UILabel *lblCurrentStatus;

IBOutlet “marks” properties as being available to controls in the UI (View).  The @property modifier indicates that this variable will be exposed as a property.  These are similar to the C# variety, but we just don’t explicitly implement getter and setters, these are created using the @synthesize modifier. Once you have made these definitions you can perform the wire up; it must be done physically.

Implementing Search

You may have noticed that we have not talked much about the search bar, nor have we defined an IBOutlet for it.  This is because search is handled using a delegate.  A delegate (also called a protocol) indicates a method that will handle an “event”.  Think of this as an interface call.  When the “event” happens, it looks to see if the controller implements the delegate (though implementation is optional).  In this case we will implement the UISearchBarDelegate, this is defined for usage in the .h file as such:

@interface ViewController : UIViewController<UISearchBarDelegate> {

 

}

The method we want to implement in the .m file is searchBarSearchButtonClicked.  I have implemented as such:

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {

// get the provided user name

NSString *handleName = searchBar.text;

TwitterProfile *profile = [TwitterProfile performLookup:handleName];

 

// assign the values

lblCurrentStatus.text = profile.currentStatus;

lblTwitterUser.text = handleName; //profile.username;

lblTweetCount.text = [NSString stringWithFormat:@”%d”, profile.tweetCount];

lblFollowersCount.text = [NSString stringWithFormat:@”%d”, profile.followersCount];

lblFriendsCount.text = [NSString stringWithFormat:@”%d”, profile.friendsCount];

 

[searchBar resignFirstResponder];

}

Now, don’t make the same mistake that I did here.  There is another step to making this work.  Open the Interface Builder application and set the delegate to the “File’s Owner (the ViewController in this case)”.  Below you see the end result:

NewImage

If you forget to do this, the event will not be caught by the Controller.

Closing Thoughts

Objective-C is certainly different from any of the languages I have worked with in the past, but I can see its draw.  It has kind of a C++ type feel to it and you really can leverage a lot of power.  Once you get passed the “message passing” idiom its just like any other language.  I am actually, now, looking forward to learning more about the offerings of iOS.  Who knows, I might even submit a personal app one day :0

Up next, I need to figure out how network communication is done in Objective-C so I can actually make this application read from the Twitter REST API instead of simply hardcoding the result.

Why Mobile will go to the Web

I can vividly remember the early days of web development and my first encounter with JavaScript.  It seemed so foreign and obtuse to me, like it didn’t belong.  But being the age of Dynamic HTML one had to become familiar with JavaScript to make websites more memorable and increase their traffic.  Sure we all hated JavaScript but we forced ourselves to use it cause there was nothing else.

In the present day now, most people cant imagine NOT having JavaScript and it has steadily found its way into so many other aspects of computing outside the web, such as the NoSQL movement.  JSON has become one of the most common data transport mechanisms in modern Ajax applications.  Much this enhancement to its popularity come thanks to the variety of wrappers that have been developed over the years which have abstracted away the many headaches developers faced when working with JavaScript.  Notable among these many frameworks is jQuery, which single handily changed the game and the way we view JavaScript.

Most people who know know that my thoughts on mobile are that native app development is a dead end.  While you cant ignore the various idioms the various OS’ provide, the driving force in our industry has always been businesses and how much they are willing to pay to allow to develop and thus continue to refine our craft.  As the popularity of the smartphone continues to skyrocket companies are, more and more, looking at mobile and the next frontier.  Whereas before it seemed inconceivable for a business not to have a website (in fact some business had ONLY a website), soon it will be inconceivable for a company NOT to have a mobile presence.

There are so many similarities between the early web transition and what we are seeing now, but there are also some very distinct differences.  Before the Internet companies would develop applications and deploy them on the client side only.  This was a headache due to the maintenance of the application as well as the incompatibilities that cropped up when a system wasn’t setup exactly like another.  The explosion of popularity that marked the birth of the modern World Wide Web ushered in an era where companies could now deploy web application to a single web server (or a farm) and allow employees to use these application without fear of incompatibilities and decreased maintenance cost.

But all was not well, this popularity caused the onset of the First Browser Wars, chiefly between Microsoft and Netscape.  The war came to an end with Microsoft using its tremendous advantage in market share to defeat Netscape.  Thing stayed pretty much the same on the web until 2007 when the Apple iPhone hit the scene and brought about the notion of a smartphone as a consumer device.  One of the biggest changes in the smartphone paradigm was the notion of customization, mainly through “apps”.  The iPhone literally caused an explosion and before anyone knew it we were ushered into the era of the smartphone and the “mobile web”.

In the early years, the iPhone was unchallenged and because of this its market shared swelled tremendously.  This continued until the release of Android by Google.  Google operating from a different mindset than Apple used the openness and availability of its platform to gain huge market share from other competitors eventually surpassing Apple in global market share in 2011.  Along the way other companies have put out new versions of their mobile OSes in attempt to gain back lost market share, chiefly among them: Palm, Microsoft, and RIM (Blackberry).

I believe we are on the precipice of a Second Browser War, this time a battle for the mobile web.  The former champion, Microsoft, has lost a tremendous amount of browser share due to a long period of stagnation.  New competitors like Apple (Safari) and Google (Chrome) and a resurrected Netscape (Mozilla Firefox) have certainly caused Internet Explorer to lose significant ground.  Furthermore, Microsoft can, at this point, hardly claim to even be a legitimate competitor in the battle for smartphone market share, that is largely between Apple and Google.

In addition, for the same reason companies moved their application off client machines and out onto the web, so will it be that they will forgo native app development in favor of mobile web applications for the majority of business applications.  This does not mean native application development will be dead on mobile devices, but it will be relegated to games and other apps that MUST take advantage of the hardware.

One of the counter arguments that I have heard to this point is that more and more apps are relying on the camera or other common pieces of hardware on a cellular device.  At this point, ONLY native apps can truly take advantage of these elements.  While this is true NOW, I do not believe it will be true in the long term.  HTML5 has not yet been standardized and I don’t doubt that talks are underway to establish a standard way for client side mobile web code to interact with a camera and other hardware.  For example, the FCC has already made it mandatory that all smartphone support GPS, mostly for emergency purposes and just about every smartphone in existence has a camera, I think it would be foolish to assume there will NEVER be a way to interact with those elements using a language like JavaScript.

Another counter argument I have heard is mobile web breaks the usability paradigm established by the OS developers (4 buttons on Android, 3 buttons on Windows Phone 7/8).  In reality, only Apple’s one button paradigm seems that it would be agnostic to a reliance on the mobile web, though this is not to say these buttons couldn’t be supported via a mobile interface, though that would complicate things for developers.

In the end, the majority of decision in computing are driven by the businesses which engage with computer professionals to have a service fulfilled.  In the very near future, companies will begin loudly asking why the same application must be developed for each of the popular platforms.  This need is driven by the users who want to use the applications.  Businesses must fulfill these needs, but developing the same app over and over just to fulfill a different usage paradigm is stupid and costly.  Business will start asking, “why cant we develop the application one time and have everyone use it?”.  This will be the central question consultants must answer as the future comes.  We have already started seeing this answer manifest itself in tools like PhoneGap and Titanium.  HTML5 is being readied with a variety of features to support mobile application development.  The question really is, are you ready to be a mobile web developer?

Next article – Introduction to jQuery Mobile.

Experimenting with the MVC4 Mobile Templates

Lets face it guys, the mobile web WILL be the future battleground for applications (replacing the native apps we see today).  In simply does not make any sense, outside of games, for developers to continue to create essentially 4 versions of the same program.  Prior to the advent of the web the SAME problem was had.  What happened there?  The explosion of the web and the first browser wars brought most, if not all, corporate/business applications to the web, this to avoid the hassle of deploying client side applications.

We know face a similar problem with mobile web.  This time, there is not one dominant browser which can use its market share to subvert the standards.  That being said, both Apple (Safari) and Android (Chrome) use WebKit, so while it may not be one browser which dominants the mobile browser space, it is WebKit which is the leading engine for rendering web pages.  Trust me, the age of writing an app for iPhone, Blackberry, Windows Phone 7/8, and Android are drawing to an end. The most important thing right now is the mobile web application development experience.

Many would say that this wont happen because so much is vested in the device hardware and usage idioms (the four buttons of Android, the single button for iPhone, etc). These are are all minor issues and are things that smarter people than I will find answers to.  The future is the mobile web and all development groups would be wise to begin educating their developers to create mobile web apps, lest they be left behind.  And so that bring us to the true focus of this entry, the mobile templates in MVC4.

Overall, there wasn’t any major new introductions in the platform, but to me the mobile templates where a huge deal.  They default to using jQuery Mobile which gives the applications, out of the box, an iOS like feel.  Most of the navigation for these apps would be on the screen (this is also why Apple is in the best position moving forward, and I dislike Apple. Their usage paradigm is least dependent on device interaction, rather they leave the navigation within the app to the user).  Here is a screen shot of an app that I created to demonstrate MVC4 Mobile Templates:

2012-04-03_2240

Just a simple application which lists out the various teams in the National Hockey League (NHL).  Clicking on any of these links will take you the next level of granularity.  This is all organized using the previous bits from the Microsoft MVC Framework + Razor templating engine.  The code to load one of these lists uses LINQ to XML:

   1: public ActionResult View(int id)

   2: {

   3:     var document = XDocument.Load(Server.MapPath("/App_Data/NHLTeams.xml"));

   4:     var divisons = document.Root.Descendants("Conference")

   5:         .First(c => c.Attribute("Value").Value == id.ToString())

   6:         .Elements().Select(elem => new Division()

   7:                                        {

   8:                                            Name = elem.Attribute("Name").Value,

   9:                                            Value = elem.Attribute("Value").Value

  10:                                        }).OrderBy(d => d.Name).ToList();

  11:  

  12:     var divisonViewModel = new ConferenceViewModel()

  13:                                {

  14:                                    ConferenceName = document.Root.Descendants("Conference").First(

  15:                                      c => c.Attribute("Value").Value == id.ToString()).Attribute("Name").Value,

  16:                                     Divisions = divisons

  17:                                };

  18:     return View(divisonViewModel);

  19: }

Pretty straightforward.  Under the hood this is all XPath and XQuery at work.  This is the same code you would create (thought this code would probably be better off in the data layer and being fed the XML file path to load) with the same organization that MVC is known for.

What do you think of the possibility (or certain future from my standpoint) of everything going to the mobile web?

Do you think businesses will see the value in using the web for the same reason they moved all of their original client apps to the web?

As a consultant how can we continue to make companies understand and help them stay relevant in a world that is changing so quickly?

Experimenting with MEF

No, I am not becoming a druggie, but I am becoming more extensible.  MEF stands for the Microsoft Extensibility Framework.  It is a new Framework born out of the PRISIM project.  The goal of this project is to create new patterns and practices to be used within the .NET Framework to create more modular and maintainable code.

MEF drives at the notion of “composing” applications, as opposed to building them.  If you think of an application as logically divided amongst various modules this notion of composing the pieces together makes sense.  Add on top of that the ability to allow for solid decoupling of the layers through a Dependency Injection centric model and you are able to A) create application that can change without changing (follows the “O” principle from SOLID) and B) enforces the ideals of the “design by contract” idealology.

This notion of “composition” is not new, in fact it’s a core concept in many modern paradigms focused on OO languages.  MEF, however, takes it a bit further.  Consider the example:

The application is divided into two projects.  The Program class creates an instance of the Application class and calls Execute.

The Application class is more interesting and shows the first signs of MEF being used in our program:

   1: public class Application

   2: {

   3:     [ImportMany] private IEnumerable<Lazy> operations;

   4:     private CompositionContainer _container;

   5:  

   6:     public Application()

   7:     {

   8:         // create the catelog

   9:         var catelog = new AggregateCatalog();

  10:  

  11:         // add our universal directory to the cateloyt

  12:         catelog.Catalogs.Add(new DirectoryCatalog(@"C:\HelloAssemblies"));

  13:  

  14:         // create the container from the catelog listing

  15:         _container = new CompositionContainer(catelog);

  16:         _container.ComposeParts(this);

  17:     }

  18:  

  19:     public void Execute()

  20:     {

  21:         Console.WriteLine("Beginning Execution");

  22:         foreach (var op in operations)

  23:         {

  24:             Console.WriteLine("Executing");

  25:             Console.WriteLine("{0} - {1}", op.Value.SayHello(), op.Metadata.Language);

  26:         }

  27:         Console.WriteLine("Execution Complete");

  28:     }

  29: }

If you are familiar with Dependency Injection (DI) then the concept of a “Container” is not foreign to you.  Containers are useful in that they allow us to specify configuration information and based on that information that will A) resolve interfaces to concrete classes and B) allow for automated maintenance of an objects life.  MEF operates in a very similar fashion.

Using MEF you can specify a catalog which houses the ways in which MEF will seek to fulfill composable parts.  In my example, I am specifying a directory in which I can drop assemblies that will be automatically included as part of the application by MEF.  Those DLLs are then searched for any classes which specify the ExportAttribute.

In the example, you notice I use the ImportsManyAttribute with an IEnumerable containing “lazy” types.  Lazy is a special new type in .NET4 that denotes something which will be determined later.  In this case, Lazy will load objects which implement the interface ISayHello and provide metadata via the interface ISayHelloData.  Metadata is extremely useful in MEF and allows the specification of important pieces of data to the object.  Consider the following implementation of ISayHello where the class will say “hello” in Japanese:

   1: [Export(typeof(ISayHello))]

   2: [ExportMetadata("Language", "Japanese")]

   3: public class JapanSayHello : ISayHello

   4: {

   5:     #region Implementation of ISayHello

   6:  

   7:     public string SayHello()

   8:     {

   9:         return "Domo";

  10:     }

  11:  

  12:     #endregion

  13: }

Use the ExportAttribute to specify the composable type (interface) you want to associate the class with.  In this case, since JapanSayHello implements ISayHello, we will export it as such.  ExportMetadataAttribute specifies the bits of metadata desired for this class.  In my case, I have a very simple metadata defintion:

   1: public interface ISayHelloData

   2: {

   3:     string Language { get; }

   4: }

You can clearly see the correlation between the properties in this interface and the metadata as specified above.

In addition to JapanSayHello, I also created the classes GermanSayHello and AmericaSayHello.  The idea was to reach a place where I could add/remove DLLs from a directory and thus change the way the application runs, without changing code.  Here is how I did that:

Putting it all together

One of the things I am coming to find with MEF is, everything is about how you organize.  A MEF based architecture isnt something you just throw together, nor is it something that you use for EVERYTHING in your application.  It, like most tools/paradigms, has a very specific calling and can really help an application if applied right. Its very much like DI in that respect.  For example:

On a project we are working on I was asked to create a Queue service to allow end users to move the process of a long running task off of their personal machines an onto a more stable application server environment.  Due to time constraints I was forced to use a Factory pattern to perform command –> class resolution, however, I still feel that MEF would’ve been a great tool to use here.  Here is why: as new Queue Commands are created, the Factory class must be updated to allow the Queue to know what a number representing.

As time went on, this became more cumbersome, partly because the number of commands needed ended up being higher then expected.  I analyzed MEF as a way to simple drop new command DLLs into a directory and automatically pick them up so they could be run.  Unfortunately, since the commands called into a shared architecture and the system wasn’t really organized to support this implementation the proposal was rejected due to time constraints.  However, if I could do things over again, I would certainly consider MEF as a way to make adding functionality to a process without changing the central process.

The following video shows the effect of the code above:

2012-03-18_1519

(click to see video)

I really like the idea of composing applications.  It just makes more sense then trying to view application, especially complex ones, as a single monolithic unit.  By breaking the application into smaller units, testing becomes easier, maintenance becomes easier, and code becomes cleaner.  In addition, you could play with the idea of not just using the same business logic in multiple applications but the same composable part.

Moving to Centare and Chicago

I am pleased to announce that, as of March 5, 2012, I have accepted the offer from Centare Group to work for them as a consultant out of their Downtown Chicago office. My start date will be April 9, 2012. Due to my responsibilities and knowledge with the current project at Meijer I am remaining on staff with Meijer until March 30, 2012.

I am extremely excited about this opportunity and look forward to the new and exciting challenges as a consultant in Chicago.

The Next Step: Command Binding

One of my biggest goals with this application is achieving a complete understanding of how the MVVM pattern can be applied and how to achieve strong code coverage through unit tests.  Thus far the first portion of the goal is proceeding nicely, regrettably I am having difficultly with the second piece.

One of the nice thing I am finding is by using an Dependency Injection model for class type resolution I can greatly cut down on the amount of code on my code behinds.  I was already familiar with this aspect with respect to properties and using INotifyPropertyChanged but now I am finally getting a chance to apply it to commands.  For example, I defined the following interface to define the contract which a view model must follow for the Venue management screen:

   1: public interface IVenuePageViewModel

   2: {

   3:      /// 

   4:      /// The list of stored venues from the repository

   5:      /// 

   6:      ObservableCollection Venues { get; }

   7:  

   8:      /// 

   9:      /// The ICommand instance which will handle the Saving operation

  10:      /// 

  11:      ICommand SaveCommand { get; }

  12:  

  13:      /// 

  14:      /// The ICommand instance which will handle the Add operation. Prepares the Venue instance appropriately

  15:      /// 

  16:      ICommand AddNewCommand { get; }

  17:  

  18:      /// 

  19:      /// The ICommand instance which will handle the Cancel Operation for active Save state

  20:      /// 

  21:      ICommand CancelCommand { get; }

  22:  

  23:      /// 

  24:      /// Select a Venue to be the active Venue

  25:      /// 

  26:      /// 

  27:      void SelectVenue(Venue venue);

  28:  

  29:      /// 

  30:      /// Indicates the current active venue

  31:      /// 

  32:      Venue Venue { get; }

  33:  

  34:      /// 

  35:      /// Return a list of States that can be displayed to the user

  36:      /// 

  37:      IList States { get; }

  38:  }

What this gives me is a way to implement multiple view models and allow them to operate on the same or different views.  This achieves a very nice, clean separation between the view model code and the view itself.

ICommand

One of the neat things that WPF can allow you to do is to bind to commands.  This removes the need for the view to specify an event handler and allows the event to be directly routed to the view model where it can be handled.  I created two classes which implement this interface: EventCommand and ActivatedEventCommand.  This is how I perform the binding in code and XAML:

   1: /// 

   2: /// The ICommand instance which will handle the Saving operation

   3: /// 

   4: public ICommand SaveCommand

   5: {

   6:     get

   7:     {

   8:         return new ActivatedEventCommand(() => _canSave, SaveVenue);

   9:     }

  10: }

  11:  

  12: /// 

  13: /// The ICommand instance which will handle the Add operation. Prepares the Venue instance appropriately

  14: /// 

  15: public ICommand AddNewCommand

  16: {

  17:     get

  18:     {

  19:         return new EventCommand(CreateNewVenue);

  20:     }

  21: }

   1: <Button Style="{StaticResource CommandButton}" x:Name="btnAdd" HorizontalAlignment="Left" Margin="10,5,0,0"

   2:         Command="{Binding Path=AddNewCommand}" Grid.Column="0" Grid.Row="2" />

   3:  

   4: <Button Style="{StaticResource CommandButton}" x:Name="btnSave" HorizontalAlignment="Left" Margin="0,0,7,0"

   5:         Command="{Binding Path=SaveCommand}" />

The only real difference between EventCommand and ActivatedCommand is that the activated variant will update its Enabled status based on the return value of the provided lambda.  This is curcial because once the binding here it functions like any other property, with one slight twist.  Whenever the property changes ICommand.CanExecute is polled.  If the method returns false, then the command will be disabled.

What this means is whenever I notify that SaveCommand has changed WPF will set IsEnabled to the boolean return value of ICommand.CanExecute.  This allows the interface to update the enabled state of components automatically based on the internal state of the view model.  A very powerful concept, especially when you then combine it with ElementBinding.

   1: <TextBox x:Name="txtVenueName" Width="200" MaxLength="70" HorizontalAlignment="Left" Text="{Binding Venue.Name, Mode=TwoWay}"

   2:          IsEnabled="{Binding ElementName=btnSave, Path=IsEnabled}" />

Now, not only does the Save button automatically disable itself when saving is not allowed, it is being watched by other elements within the form who will set their IsEnabled state based on whether the Save button is enabled.  Through adding almost no code, I am quickly able to provide a clean intuitive interface which switches state intelligently.  This is the code is my code behind:

 

   1: public partial class ManageVenue : UserControlBase

   2: {

   3:     public ManageVenue()

   4:     {

   5:         InitializeComponent();

   6:     }

   7:  

   8:     private void Venue_Loaded(object sender, System.Windows.RoutedEventArgs e)

   9:     {

  10:         LayoutRoot.DataContext = InjectionContainer.Get();

  11:     }

  12:  

  13:     private void dgVenue_SelectionChanged(object sender, SelectionChangedEventArgs e)

  14:     {

  15:         if (e.AddedItems.Count > 0)

  16:             InjectionContainer.Get().SelectVenue((Venue)e.AddedItems[0]);

  17:     }

  18: }

Since we define each ViewModel as a Singleton, thereby allowing only one instance to event exist we don’t even need to worry about casting or accessing the LayoutRoot property here.  However, I wonder what will happen if I hit my “Back” button and do not reset the internal state of the view model. Could be kind of weird when I come back to this page later on.  But Ill check that out later.

Conclusion

The MVVM pattern is a very powerful pattern and requires much discipline and understanding to fully implement.  This is why it is common for programmers to rely on a framework like Caliburn.Micro to do this for them.  That said, I have often found that understanding what you are doing makes using a framework much easier.  I can already see some of the concepts I didn’t quite grasp in Caliburn making more and more sense to me.  With any luck when I do finally decide to transition this application to use Caliburn the switch will be very easy.

Command Binding is quickly becoming one of my new favorite aspects in WPF, though it does seem you can command bind everything, case in point the SelectionChanged event on the DataGrid.  But, it does make things significantly cleaner.  I am also certain that when I focus more on the testing aspect of this it will be easier to test with all the view logic in the View Model instead of the code behind.