Front-end JavaScript Logging and Crash Reporting

One of the biggest things I miss about mobile development is remote crash reporting. It was absolutely essential. It was funny at the time because it seemed like such a revolutionary concept but then I realized that I should have been doing this for both languages on the server and in the browser. Now that I’m not doing as much mobile development I started looking for a similar exception aggregation system. I was pleased to find a language agnostic system called Sentry.

Great, so I found my crash reporting system but the next step was how I was going to implement it on a large scale.  I quickly turned to the patterns that the most logging frameworks use in Java and Python. Native JavaScript’s console.log() was great, but didn’t offer the flexibility I’d want for a large scale app. I wanted the ability to have different log levels and display logs in the browser console when I was debugging things, but at the same time I wanted to report a crash if I ever invoked logger.fatal().

I did some searching for JavaScript logging frameworks and I found a port of Java’s log4j, log4javascript. I found this to be pretty awesome but I was skeptical of using it right away as I didn’t want something bloated that had a full kitchen sink. It does offer a lot, but there were a lot of features I was looking for, specifically the ability to create different logging adapters that would allow me to log to Sentry. One thing you have to be careful is that if you log too many fatal errors you could overload your Sentry server so you’ll have to load test and scale accordingly. Sentry does have configuration options for Redis queues etc. to handle large volumes of logs.

In order for JavaScript to log to Sentry, I’d have to use one of their clients, Raven-JS. Once I got that working standalone, I wrote an adapter for log4javascript that would allow me to log all fatal() and error() logs to Sentry.

If you’d like to take it a step further, you can create a wrapper that instantiates the logger and configures it for you.

com.restlessThinker.Logger = {
    getLogger: function (name) {
        var loggerName = name || null;
        var logger = log4javascript.getLogger(loggerName);
        var consoleAppender = new log4javascript.BrowserConsoleAppender();
        var globalLoggingLayout = new log4javascript.PatternLayout('[%-5p] [%d{HH:mm:ss}] [%c] ::: %m%n');
 
        var subHostName = com.restlessThinker.Util.subHostName();
        consoleAppender.setThreshold((subHostName === 'prod') ? log4javascript.Level.ERROR : log4javascript.Level.DEBUG);
        consoleAppender.setLayout(globalLoggingLayout);
        logger.addAppender(consoleAppender);
        // this can be modified to fit dev/staging/prod
        if (subHostName !== 'prod') {
            var ravenAppender = new log4javascript.RavenAppender('somedevkey', 'mysentryurl.com/2');
            ravenAppender.setThreshold(log4javascript.Level.ERROR);
            logger.addAppender(ravenAppender);
        }
        return logger;
    }
};

You can generate multiple loggers in different classes/files.

var logger = com.restlessThinker.Logger.getLogger('newLogger');
logger.fatal('log this to sentry');

I hope this helps!

JavaScript Interfaces

In my personal quest for the “History of Javascript“, one of the first things I wanted to analyze was code maintainability. I tend to favor code maintainability and testability when making architectural decisions in any language. Naturally this lead me to wanting to see if there were any design patterns or anti-patterns in JavaScript. My first choice was  Pro JavaScript Design Patterns: The Essentials of Object-Oriented JavaScript Programming. I must admit when I was browsing through the book I was very skeptical of it when I saw a section on Interfaces in JavaScript. I know that it can be very risky trying to implement non-native functionality into one language from another. It’s even worse when you try to shoe-horn a pattern into a different language where it’s clearly not needed. I also strongly believe that languages evolve to help eliminate the need for developers to implement design patterns and that the languages themselves can have the patterns built in.

My favorite languages are both strongly typed and dynamic so it was a little hard for me to fully let go of types when jumping into JavaScript. When picking out this book, my main mission was “How can you create a large scale JavaScript application while still having it be very maintainable”? Any language can get unwieldly and design patterns aren’t a silver bullet, but I was curious to see enterprise methodologies applied on a free-spirited, hipster language. ;)

After reading it, it’s easy to see their perspective on when it’s necessary and that their implementation was very simple. We simply need to check if an object contains the specific methods defined in an interface. It uses duck typing to determine if the method exists, it doesn’t care about the parameters but just so you don’t get undefined is not a function. We obviously don’t want this everywhere but I find it works in a few scenarios. First, if we need to group classes. Second, if we must implement some design pattern that requires an interface. Third, if we have to invoke methods on a dependency injected object that we want to throw errors if a method does not exist and give other developers working on the same code feedback.

If you’re curious, buy the book or check out my example on GitHub.

 

JavaScript the Good Parts

Every front-end, full-stack, UI developer/engineer should have a copy of this book. Every dev team should have a copy of this book. Ironically the book is very thin, but it’s also great for a refresher every few months. It’s helped me enjoy JavaScript by simply avoiding the bad parts and pitfalls while telling me “why”.

Rekindling a relationship with Javascript

Javascript was my first language. At the time, I had no idea what were good and bad qualities of a language. I had no idea what I was doing. I left Javascript for Flex and then traded in Flex for iOS and now I’ve come full circle back to Javascript. It’s been 8 years since I’ve written a line of meaningful Javascript.

I’m going to try to remember where I left off at. I’m going to see what I missed. I’m going to see if Javascript has evolved and matured over the years. My very own “History of Javascript”.

My thoughts on Reactive Programming in iOS

I’ve been seeing a lot this topic lately and I thought I’d share my opinion on it. The first thing I’d like to say is that binding is easily the #1 feature request that I want brought over to iOS from Cocoa on OS X. As a long time Flex developer I’ve had the enjoyment of binding data to UI controls. For front-end development, it saves so much time and you start wondering how you’ve ever developed front-ends without it.

Even though it’s been a complete dream of mine to have reactive programming on iOS, here are the key reasons for me on why I’m waiting:

Memory and Performance

Binding is expensive. On iOS, we don’t have the luxury of speed of a desktop or laptop computer. Over time this will change but there is still a large number of devices that are iPhone 4, 4S and older generation iPads. To me this makes sense as the #1 reason that Apple hasn’t included binding in iOS. Reactive Cocoa, the popular framework for iOS is seeing a little bit of the performance issues that binding presents. I strongly believe in Larry Pages quote about speed:

“Speed is product feature number one”

I’m not talking about premature optimization here but if your software performs faster your users will have a better user experience, and that is what matters the most.  A lot of the early versions of libraries will have performance issues.

Maintainability

Reactive Cocoa is a great library for achieving binding on iOS, but what are you going to do when Apple finally includes binding natively on iOS?  Will you update all of your apps? One example I have is NSJSONSerialization. There were a few libraries out there that touted ease of use and performance benefits and you had to do your own analysis on each library and decide.  When it released, it was the fastest JSON serializer available on iOS and it shipped with Cocoa so you don’t have to worry about updating the library. It’s very easy for developers to ignore changes that should be made internally to an app that will be better long term.

Know when to use a hammer and when to use an axe

It’s very easy to complicate application architecture with such a powerful tool. In my Flex days, there were developers using binding at an entire class level versus property level and they kept all of the models in the entire application in one class to seem “tidy” but was suffering huge performance issues over time because the binding had to react to every single property in that class whenever binding fired.  This would be an absolute nightmare on a mobile device with smaller resources.

There are some benefits to using reactive cocoa or other binding frameworks on iOS, just use it wisely and program on purpose.

It takes a lot of discipline to go against the popular trend right now but with these trade-offs, I think I’ll wait a little longer. I’m confident that reactive programming on iOS will be as common as IBOutlet.

Objective-C OAuth2 with Google

It’s almost a necessity for any application these days to connect to a third party system for an external service. The authentication method of choice used by many of these third party companies is oAuth2.  The Google API in some cases requires you to use OAuth2 so a user can authenticate with Google and return your application an authorized token which you can make requests to Google on behalf on that authenticated user.

For Objective-C, Google has an official library (although version 0.0.2 at the time of this post) but it’s pretty outdated. Lets go into what makes it great:

  • Contains a view controller with a UIWebView with browser back and forward buttons built in
  • Has the ability to check if the token is still valid
  • Saves the access token to NSUserDefaults
  • Allows you to clear out the oauth token

Here’s what could be improved:

  • The browser back and forward buttons no longer work in iOS7
  • Default back button in view controller is hidden in iOS7
  • Uses a third party library called SBJSON for JSON serialization. iOS now has native serialization with NSJSONSerialization and we don’t need this third party dependency.  NSJSONSerialization has also been benchmarked to be the fasted serializer.

The first two are unfortunately deal breakers as it provides a frustrating experience for the user.  Lets look at how we would create our own alternative.

Google Console

You’ll need to get a client id and client secret from the Google API console. For this example we’ll be using the  Google Contacts CardDAV API. Under registered apps, create one for iOS to obtain the client id and client secret along with setting the redirect URI to localhost.

Creating the view controller

Create a view controller with a xib that will have a UIWebView. Don’t forget to set the vc as the delegate to the UIWebView. You’ll then need to create a delegate:

@class GNGoogleContactsOAuth2ViewController;
 
@protocol GNGoogleContactsOAuth2Delegate 
 
- (void)googleOAuth2:(__weak GNGoogleContactsOAuth2ViewController *)googleOAuth2 didRetrieveAccessToken:(NSString *)accessToken andRefreshToken:(NSString *)refreshToken;
 
@end
 
@interface GNGoogleContactsOAuth2ViewController : UIViewController
 
@property (weak) id delegate;
 
@end

Then in viewDidLoad:

- (void)viewDidLoad
{
    [super viewDidLoad];
 
    _redirectURI = @"urn:ietf:wg:oauth:2.0:oob";
    [_myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://accounts.google.com/o/oauth2/auth?state=/profile&redirect_uri=%@&response_type=code&client_id=%@&approval_prompt=force&access_type=offline&scope=https://www.google.com/m8/feeds", _redirectURI, GNGoogleCalendarClientID]]]];
}

*for some reason wordpress is html parsing the & in the url to & so please be aware if you are copying and pasting.

The redirect URI looks odd but it’s telling the oauth system that it’s a local application and not a web redirect after authentication. You should see this address in the Google console.

Now when you display this view controller, the UIWebView will load up Google’s account authentication screen.

Handling the UIWebViewDelegate

The next step is to handle the user authenticating properly to Google and extracting the oauth code. The code is in the documents title so we check the title for a success string and extract the code accordingly. Once we get the code, we have to make another request to Google, this time at their oauth2 endpoint to request an access token. This is where the user can grant permissions to your application.
 

#pragma mark -
#pragma mark UIWebViewDelegate
 
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	return YES;
}
 
- (void)webViewDidFinishLoad:(UIWebView *)webView{
	[self dismissHUD];
    NSString *theTitle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
	if( [theTitle rangeOfString:@"Success"].location != NSNotFound ) {
 
		NSArray *strings = [theTitle componentsSeparatedByString:@"&"];
		if( [strings count] > 0 ) {
			[self showBusyWithAllowedInteraction];
			NSString *code = [[strings objectAtIndex:[strings count]-1] substringFromIndex:5];
 
			__weak GNGoogleContactsOAuth2ViewController *weakSelf = self;
			NSURL *url = [NSURL URLWithString:@"https://accounts.google.com"];
			AFOAuth2Client *oauthClient = [AFOAuth2Client clientWithBaseURL:url clientID:GNGoogleCalendarClientID secret:GNGoogleCalendarClientSecret];
			[oauthClient authenticateUsingOAuthWithPath:@"/o/oauth2/token"
							       code:code
							redirectURI:_redirectURI
							    success:^(AFOAuthCredential *credential) {
 
								[_delegate googleOAuth2:weakSelf didRetrieveAccessToken:credential.accessToken andRefreshToken:credential.refreshToken];
								[_myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://mail.google.com/mail/u/0/?logout&hl=en"]]];
 
							} failure:^(NSError *error) {
								[weakSelf dismissViewControllerAnimated:YES completion:nil];
							}];
			[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
		}
	}
}

 

For authenticating I’m using the AFOAuth2 library since I’m already using AFNetworking. In the success block we pass the accessToken to the delegate but I want to point out that we make another URL request to Google. This is a hack that actually logs the user out of Google services.
 
That’s it! It’s a simple alternative but it’s still missing some features like keeping the access token in NSUserDefaults. Hopefully in a future post I’ll get this in a lib and put it on GitHub.

 

 

 

Unit testing UITableViewCell

It might not seem obvious but unit testing data that exists or that is formatted in your UITableViewCells is important.  One example would be if you’re loading data from JSON via a dictionary, null objects serialize as [NSNull class] and if you’re displaying it as text – would use [NSNull description] which would show up as “<null>” in one of your strings. Worse, you could be trying to perform some action on the NSNull object like expecting an array and could be trying to execute [NSNull length] and your app would crash. There are other reasons but I won’t go into that discussion as this post is about my findings on how to properly setup testing for UITableViewCells. Lets take a look at the UITableViewCell implementation before we look at how we can test it.

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  TweetObj *tweet = [_tweets objectAtIndex:indexPath.row];
  if( tweet.type == TweetTypeImage ) {
    TweetImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TweetImageTableViewCellIdentifier];
    [self configureCell:cell forIndexPath:indexPath];
    return cell;
  } else if( tweet.type == TweetTypeNormal ) {
    // do another cell
  } else {
    // another cell
  }
}
 
- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
  if( [cell isKindOfClass:[TweetImageTableViewCell class]] ) {
    TweetObj *tweet = [_tweets objectAtIndex:indexPath.row];
    NSString *firstName = [tweet.data objectForKey:@"first_name"];
    NSString *lastName = [tweet.data objectForKey:@"last_name"];
    NSString *name = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
    [((TweetImageTableViewCell *)cell).nameLabel setText:name];
 
  } else if ( [cell isKindOfClass:SomeOtherTableViewCell class]] ) {
    // do other
  }
}

 

My first approach using OCMock

OCMock is great.  It can be used for mocking xibs and stubbing objects that return pre-determined values for specific method invocations and can verify interaction patterns. Naturally I thought about using it for unit testing a table view cell. I couldn’t get it working (and I’ll get to why) but here is the test I wrote out that would expect to work.

 

@implementation TableViewCellTests
 
  - (void)setUp
  {
    _controller = [[MySampleViewController alloc] init];
    _tableViewMock = [OCMockObject niceMockForClass:[UITableView class]];
    [_tableViewMock registerNib:[UINib nibWithNibName:@"MyTableViewCell" bundle:nil] forCellReuseIdentifier:MyTableViewCellIdentifier];
  }
 
    - (void)testTweetImageCell
    {
        TweetObj *tweet = [[TweetObj alloc] init];
        tweet.type = TweetTypeImage;
        tweet.data = [NSMutableDictionary dictionaryWithDictionary:@{ @"first_name" : @"firstname", @"last_name" : @"lastname" }];
        _mockTweets = [NSMutableArray arrayWithObject:tweet];
        [_controller setValue:_mockTweets forKey:@"_tweets"];
 
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [[[_tableViewMock expect] andReturn:[[[NSBundle mainBundle] loadNibNamed:@"TweetImageTableViewCell" owner:self options:nil] lastObject]] dequeueReusableCellWithIdentifier:MyTableViewCellIdentifier forIndexPath:indexPath];
 
        TweetImageTableViewCell *cell = (TweetImageTableViewCell *)[_controller tableView:_tableViewMock cellForRowAtIndexPath:indexPath];
        STAssertNotNil( cell, @"should not be nil" );
        STAssertTrue( [cell.nameLabel.text isEqualToString:@"firstname lastname"], @"should be equal" );
        [_tableViewMock verify];
    }
 
@end

If your’e familiar with OCMock, the test mockup looks legit. If you set breakpoints it’ll even go though configureCell:forIndexPath. The problem is isKindOfClass. The cell doesn’t match any of the cells in the conditional statement and skips over any of the cell rendering so the test fails. I also tried:

id mockCell = [OCMockObject partialMockForObject:[[[NSBundle mainBundle] loadNibNamed:@"MyTableViewCell" owner:self options:nil] lastObject]];
[[[mockCell stub] andReturnValue:OCMOCK_VALUE((BOOL) {YES})] isKindOfClass:[OCMConstraint isKindOfClass:[MyTableViewCell class]]];
[[[_tableViewMock expect] andReturn:mockCell] dequeueReusableCellWithIdentifier:MyTableViewCellIdentifier forIndexPath:indexPath];

After lots and lots of googling, OCMock uses NSProxy to mock and stub objects and isKindOfClass isn’t going to work here.

So what are our options? What we’re trying to test is the data transformation and not necessarily the rendering of the table view cell. If we refactor this and apply a controller to manipulate the data, we can now unit test it without using OCMock.

@interface TweetModelController : NSObject
 
- (instancetype)initWithArray:(NSArray *)model;
- (NSString *)nameAtIndexPath:(NSIndexPath *)indexPath;
 
@end
 
@interface TweetModelController() {
  NSArray *_model;
}
 
@end
 
@implementation @TweetModelController
 
- (instancetype)initWithArray:(NSArray *)model
{
  if( self = [super init] ) {
    _model = [model copy];
  }
  return self;
}
 
- (NSString *)nameAtIndexPath:(NSIndexPath *)indexPath
{
  if( [_model count] &gt; indexPath.row ) {
    NSString *name = //build the name string
    return name;
  }
}
@end

Now lets see this implemented in the table view cell.

- (void)viewDidLoad
{
  [super viewDidLoad];
  // initalize data model
  _modelController = [[TweetModelController alloc] initWithArray:_tweets];
}
 
- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
  if( [cell isKindOfClass:[TweetImageTableViewCell class]] ) {
    [((TweetImageTableViewCell *)cell).nameLabel setText:[_modelController nameAtIndexPath:indexPath];
 
  } else if ( [cell isKindOfClass:SomeOtherTableViewCell class]] ) {
    // do other
  }
}

The key thing to remember is remember all data manipulation should now occur in the controller, if we don’t then we won’t be able to have tests.

@implementation TableViewCellTests
 
- (void)setUp
{
  Tweet *tweet = [[Tweet alloc] init];
  tweet.type = TweetTypeImage;
  tweet.data = [NSMutableDictionary dictionaryWithDictionary:@{ @"first_name" : @"firstname", @"last_name" : @"lastname" }];
  _stubTweets = [NSMutableArray arrayWithObject:tweet];
  _controller = [[TweetModelController alloc] initWithArray:_stubTweets];
}
 
- (void)testTweetImageCell
{
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
  NSString *testString = [_controller nameAtIndexPath:indexPath];
  STAssertTrue( [testString isEqualToString:@"firstname lastname"] );
}
@end

Refactoring so your code can be more testable is a very common practice and in this case it was the right solution.