Monthly Archives: April 2012

I Learned to Speak Four Languages in a Few Years: Here’s How [Learning] (Lifehacker)

Posted by Gabriel Wyner at Lifehacker

Lifehacker reader Gabriel Wyner was tasked with learning four languages in the past few years for his career as an opera singer, and in the process landed on “a pretty damn good method for language learning that you can do in limited amounts of spare time.” Here’s the four-step method that you can use, too (and you don’t have to invest hundreds in a language course like Rosetta Stone). More »


How to connect to a WPA-PSK/WPA2-PSK wireless network (MacOSXHints.com)

Posted by (author unknown) at MacOSXHints.com
When you want to join a WPA-PSK/WPA2-PSK wireless network, your Mac will always refuse to do so. Here’s how you can do it.

In System Preferences, click on the Network icon, then on Wi-fi in the list of networks. Click on the “Advanced…” button at the bottom-right of the window. On the Wi-Fi tab, click on the plus (+) button, then add the following:

  • Network Name: Your Wi-Fi network’s SSID Name
  • Security: Any (Personal)
  • Password: Your Wi-Fi password

Then click on OK. (You may need to enter your administrator’s password to apply the changes.)

Now your Mac will automatically connect to your WPA-PSK/WPA2-PSK network.

[kirkmc adds: I haven’t tested this. What I understand here is that you cannot connect to this type of network via the standard dialog, and you must simply add it manually to your list of networks.]

Add to digg
Add to Reddit
Add to Slashdot
Email this Article
Add to StumbleUpon


Consolidating jQuery Ajax Calls (Dan Wahlin’s WebLog)

Posted by dwahlin at Dan Wahlin's WebLog

As the use of Ajax continues to grow in popularity it’s worth taking the time to think through how Ajax calls are structured and used in an application especially if re-use and maintenance are important. If you analyze a lot of the Ajax code out there you’ll likely find that calls to the server are scattered throughout scripts and pages. For example, if an Ajax call is made to get a list of jobs, a call is made directly in the script that needs the data. If another page/script needs the same type of data another Ajax call is made. This results in code duplication and complicates maintenance since Ajax calls aren’t consolidated.

While there’s certainly nothing wrong with this approach (it gets the job done after all), you can get better re-use out of your Ajax calls by consolidating them into JavaScript objects. In this post I’ll talk about how Ajax calls can be consolidated using JavaScript patterns and describe the benefits this approach provides.

The Case for Consolidation

JavaScript libraries such as jQuery make it so easy to make Ajax calls that we often don’t think much about the code being written and where it’s being used. For example, consider the following code that’s used to retrieve customers from a WCF service and update a page with the retrieved data:

$('#GetCustomersButton').click(function () {     $.getJSON('../CustomerService.svc/GetCustomers',         function (data) {             var cust = data.d[0];             $('#ID').text(cust.ID);             $('#FirstName').val(cust.FirstName);             $('#LastName').val(cust.LastName);         }); });

Although this code works fine, it can’t be re-used across other pages that may also need customer data. If another page or script needs the same data then the getJSON() call will have to be re-written since the manner in which the returned data is processed will more than likely be different. In addition to this potential problem, the code is added into a script that may have completely different responsibilities that are unrelated to calling a service.

In the object-oriented world we strive to follow the single responsibility principle when designing classes to avoid duplication and provide better re-use. Following this same principle in JavaScript code makes a lot of sense and can lead to better re-use, simplified maintenance, and better overall organization of code in an application. By placing Ajax calls into a re-useable JavaScript object we can use them throughout an application more easily, minimize duplicate code, and provide a better maintenance story. Before jumping into how Ajax calls can be consolidated, let’s review a key pattern called the Revealing Module Pattern that can be used to encapsulate JavaScript code.

Encapsulation with the Revealing Module Pattern

There are several different patterns that can be used to structure JavaScript code and provide a way for functions to be encapsulated inside of class-like structures (given that JavaScript doesn’t officially support the concept of a class). One pattern that can be used is the Revealing Module Pattern. By using the pattern you can encapsulate variables and functions into an object, achieve re-use, simplify maintenance, and can also help avoid naming collisions. There are several other patterns such as the Prototype Pattern and Revealing Prototype Pattern that can be used (to name just two) but the Revealing Module Pattern provides a simple way to get started creating JavaScript objects that are similar in purpose to C# or Java classes.

The following code shows an example of some simple code that has no structure applied to it (I call it “Function Spaghetti Code”). With this approach variables and functions are scattered throughout a file with no rhyme or reason as to how they relate to each other. All of the variables and functions defined this way are automatically placed in the global scope which can lead to naming collisions.

$('#GetCustomersButton').click(function () {     $.getJSON('../CustomerService.svc/GetCustomers',         function (data) {             var cust = data.d[0];             $('#ID').text(cust.ID);             $('#FirstName').val(cust.FirstName);             $('#LastName').val(cust.LastName);         }); }); 

Listing 1. Function-based JavaScript Code with no encapsulation.

Listing 2 shows this same code refactored to follow the Revealing Module Pattern. In this simple example the code is encapsulated in an object named car. Following this pattern allows the code to be organized, variables and functions to be taken out of the global scope, and a re-useable object to be defined that can be used in one or more pages or applications.

var engine = 'V8';  function start() {     alert('Car started ' + engine + ' engine'); }  function stop() {     alert('Car stopped ' + engine + ' engine'); }  function turn() {     alert('Car turned') }

Listing 2. Organize functions in an object to provide encapsulation, re-use, easier maintenance, and to help avoid naming collisions.

Looking through the code in Listing 2 you’ll see that 3 functions are defined including start(), stop(), and turn(). All three are publicly exposed to consumers using the return object that’s defined (an object literal). Any functions not listed in the return object are inaccessible to consumers making them similar to private members in object-oriented languages. Since the car object is self-invoked (note the parenthesis at the end of Listing 2) you can call it directly using code such as the following:

car.start(); car.stop(); car.turn();

If you want to create a new instance of car the code in Listing 3 can be used instead of the code shown in Listing 2. Notice that the Car object starts with an upper-case character so that the consumer knows to create a new instance of the object to use it. This is a common convention being used more and more among JavaScript developers.

 

var Car = function (engine) {     var start = function () {         alert('Car started ' + engine + ' engine');     },     stop = function () {         alert('Car stopped ' + engine + ' engine');     },     turn = function () {         alert('Car turned');     };      return {         start: start,         stop: stop,         turn: turn     }; };

Listing 3. Using the Revealing Module Pattern to create a Car object that can be created using the “new” keyword.

To use the Car object the following code can be written:

var car = new Car('V8'); car.start(); car.stop(); car.turn(); 

If you only need one object in memory as an application is running the code shown in Listing 2 works well. If you need multiple instances of an object the self-invoking parenthesis can be removed as shown in Listing 3.

Now that you’ve seen how the Revealing Module Pattern can be used to structure JavaScript code, let’s see how it can encapsulate Ajax functions into an object.


Consolidating Ajax Calls

A sample application named Account at a Glance (download it here – an image from the application is shown below) built to demonstrate several HTML5, jQuery, and general JavaScript concepts relies on the Revealing Module Pattern to consolidate Ajax calls into a single object that can be re-used throughout the application. By following this pattern, an Ajax call used to retrieve market quotes can be defined in one place and then called from other scripts that may need the data. This approach provides several benefits including more modular, re-useable, and maintainable code. If something changes with an Ajax call you can go to one place to make the core modifications rather than searching through multiple scripts and pages to find where changes need to be made.

clip_image002


To access market quote data in the application the following call could be made as data is needed in a given script:

$.getJSON('/DataService/GetQuote', { symbol: sym }, function (data) {     //process data here  }); 

Although this code works, it’s much better from a re-use and maintenance standpoint to consolidate calls into an object. Listing 4 shows an example of an Ajax-specific object named dataService that the Account at a Glance application uses to retrieve different types of JSON data from the server.

 

var dataService = new function () {     var serviceBase = '/DataService/',     getAccount = function (acctNumber, callback) {         $.getJSON(serviceBase + 'GetAccount', { acctNumber: acctNumber },           function (data) {               callback(data);           });     },      getMarketIndexes = function (callback) {         $.getJSON(serviceBase + 'GetMarketIndexes', function (data) {             callback(data);         });     },      getQuote = function (sym, callback) {         $.getJSON(serviceBase + 'GetQuote', { symbol: sym }, function (data) {             callback(data);         });     },      getTickerQuotes = function (callback) {         $.getJSON(serviceBase + 'GetTickerQuotes', function (data) {             callback(data);         });     };      return {         getAccount: getAccount,         getMarketIndexes: getMarketIndexes,         getQuote: getQuote,         getTickerQuotes: getTickerQuotes     };  } ();

Listing 4. Consolidating Ajax calls into a dataService object.

The dataService object follows the Revealing Module Pattern discussed earlier to encapsulate the various functions. A single instance is created initially at runtime (the dataService function is self-invoked as the script initially loads) that exposes four functions responsible for getting account, market, quote, and ticker data from the server.

Looking through each function in the dataService object you’ll notice that they all accept a callback parameter. Because each function is re-useable, it won’t know how to handle the data that’s retrieved from a given service – processing of data is unique to the caller of the function. As a result, each function in dataService allows the caller to pass a callback function that is invoked once the data returns from the service to the client. An example of calling the dataService object’s getAccount() function is shown next:

dataService.getAccount(acctNumber, renderAccountTiles);

When the data is returned the getAccount() function will invoke the renderAccountTiles callback function shown in Listing 5.

 

renderAccountTiles = function (data) {     $('div.tile[id^="Account"]').each(function () {         sceneStateManager.renderTile(data, $(this), 500);     }); }

Listing 5. The renderAccountTiles() function handles data returned from the call to dataService.getAccount().

Note that a nested/inline callback function could be passed to getAccount() as well as shown next:

 

dataService.getAccount(acctNumber, function (data) {     //Process data here }); 

Anytime a script in the application needs to retrieve data from the server a call can be made to one of the dataService object’s functions and required parameters can be passed along with the callback. This technique provides a flexible way for Ajax functionality to be consolidated into an object while remaining flexible as far as callbacks go.

This technique can be applied to other parts of an application as well to create additional objects that encapsulate related variables and functions. By focusing on objects rather than functions you can more efficiently organize code in an application and achieve many of the benefits mentioned earlier such as better re-use and simplified maintenance. Eliminating Function Spaghetti Code is definitely a good thing.

If you’d like additional details about structuring JavaScript code or building an end-to-end application check out my Structuring JavaScript Code or Building an ASP.NET MVC, EF Code First, HTML5, and jQuery courses from Pluralsight.

Avoid Jet Lag with This Start to Finish Cheat Sheet [Travel] (Lifehacker)

Posted by Thorin Klosowski at Lifehacker

Jet lag can be difficult to overcome no matter how used to travelling you are, but blogger and illustrator Yumi Sakugawa has put together a simple start to finish graphic to help you overcome even the longest flights. More »


Multi-Target: The Guide [Doug Davies] (iDevBlogADay)

Posted by Doug Davies at iDevBlogADay

In a previous blog entry I had mentioned that I combined my Full and Lite versions of each of my apps into one XCode project using targets.  This was something that pre-XCode 4 was pretty hard to do, thus my decision to keep them as separate projects until recently.

Another reason to create multiple targets would be to keep your iPhone and iPad versions in the same project.  This probably becomes even more important nowadays if you don’t wish to go the Universal App route and prevent retina assets app bloat.  Plus it gives you the option of pricing your iPad app differently than your iPhone app if you choose to do so.

I didn’t go into much detail the previous time around other than to give a few quick pointers.  This time I’ve created a sample project and will guide you through step-by-step with screen captures where appropriate.  The project can be found here (you’ll need it because I’m not going to go through every single step in this tutorial).

The first thing I did was create a new “Single View” project.

This created a target with the same name as the project.

I really wanted to create 2 targets with different names than the project.  So I created 2 new “Single View Application” targets (File->New->Target).  The first one I called MultiTargetIphone and the second MultiTargetIpad, making sure to select the right “Device Family” for both.

I then removed the original MultiTarget target, scheme, and directory.  You do this by selecting Product->Manage Schemes.  Click the minus sign to remove MultiTarget.  Then select the target in the TARGET view, right click, and delete.  Also remove it from the files view and the physical directory in the project (show in finder).  If anyone has a better way to remove a target and all it’s files, let me know.  It seems like a lot of areas to remove.

Here’s what my project looked like after this step

And in Finder

To prove that these are indeed 2 different targets and binaries I’m going to add some shared code and assets as well as specific target code and assets.  When we’re done we’ll examine the resulting bundles and make sure only the necessary assets are included.  When adding files and assets make sure you specify what target they should be included in.

or you can do this after the fact in the File Inspector panel

In this example I’m using a separate XIB file per target.  I’m going to put 2 buttons in each.  One button will call a target specific IBAction and the other will call an IBAction that will use a shared class to perform it’s behavior.  Both targets include SharedStuff.m and shared.png, however they each have their own ViewController that handles the specific behaviors for that target as well as their own button images (ipad.png and iphone.png).

The one thing I did notice is that Interface Builder doesn’t seem to honor the “Target Membership” settings.  That is, when I’m editing the XIB for the iPad it allows me to select iphone.png as the background button image even though I only added that file to the iPhone target.  The button DOES end up empty as expected when you run the executable (because the png file is not included in the bundle), but just be aware interface builder may be showing you things it shouldn’t (let me know if you have a different understanding of this).

I’m not going to go into the details of wiring up the IBActions, building the UI, or writing the code in the action.  You have the source and can play around with that.  Here’s what my project structure now looks like.

My directory structure in Finder looks like this

You’ll notice I also added icon.png and icon-72.png for both the iPhone and iPad.  You can select the icon to use in the target’s summary panel

Ok, now let’s run the 2 targets.  First select the iPad one and run it on the iPad simulator.

You’ll see the following

The top button is using ipad.png to display it’s contents.  The bottom button is using shared.png.  Clicking on each will call the appropriate IBAction in the ViewController and display an alert dialog.  The shared one will use SharedStuff which is common code (and asset) shared by both targets.

Now let’s run the iPhone one in the iPad simulator to prove that they are indeed 2 different binaries.  You’ll know this because the iPhone version will run in 1x mode and not take up the full screen.

You’ll also notice two different icons on the SpringBoard.

Ok, but how do you know the bundles only include what is necessary for each platform?  One way is to look at the “Build Phases”.

Notice that the iPad target includes it’s version of main.m, AppDelegate.m, and ViewController.m, and includes the shared SharedStuff.m.  But it doesn’t reference any of the code files for the iPhone target.  In the resources it has it’s own InfoPlist.strings, ViewController.xib, and ipad.png, and shares shared.png, but doesn’t reference iphone.png or it’s interface builder files.

Another option is to build for the device and use PhoneView to inspect the package contents.

You don’t see any of the iPhone assets in the iPad bundle.

Whew… I hope that helps understanding how to build an iOS app that can target multiple devices separately and yet share common assets.  Or you might use it to provide full and lite versions of your app.  You’d just add a LITE_VERSION compiler flag to the build settings for your lite version and ifdef your code accordingly.

There really is no reason not to try and combine different versions of your app into one project now that Apple has made it easy.  While this use to be hard before XCode 4 it’s obvious Apple has given this considerable thought since then.

UPDATE: Last weekend I submitted Jiggle Balls Studio to Apple.  It’s the update to Jiggle Balls HD that is now FREE and supports In-App Purchases.  I’m still waiting for it to be approved, but in the meantime you can go get the previous version for FREE and get yourself ready for the update.  Enjoy!

Keep Your Garden Pest Free with These Natural Pesticides, Made with Ingredients Already in Your Pantry [Gardening] (Lifehacker)

Posted by Alan Henry at Lifehacker

If you’re getting started with your backyard or container garden and want to be ready for when the inevitable unwanted guests move in, you don’t have to run out and grab a couple of bottles of commercial pesticide from your local hardware store—there are safer, more natural options that won’t leave your fledgling produce covered in chemicals. Best of all, you probably have the ingredients for them in your pantry already. More »


SNRHUDKit (Cocoa Controls)

Posted by Cocoa Controls at Cocoa Controls
SNRHUDKit is a framework that brings missing HUD controls and interface elements to AppKit. All of the controls are drawn in code and fully compatible with OS X 10.6 and 10.7. SNRHUDKit is nowhere near complete at this time. The only controls/elements that have been at least partially implemented are: Window, Segmented control, Text view, Basic rounded button, Text field.

image of this control

Push Notifications and Urban Airship [Tod Cunningham] (iDevBlogADay)

Posted by Tod Cunningham at iDevBlogADay

I have been considering putting Push Notifications into Picross HD for some time now.  This weekend, I decided to take the plunge and give it a try.  I will try to cover some of the hiccups and things that I have been trying.

Why Push Notifications

Ken and I aren’t very good at the marketing side of things, but everyone I talk with about marketing asks if we use push notifications.  I finally decided there must be something to this so let’s give it a try.

There are a couple of uses for push notifications that I would like to try:

  1. Notify Picross HD users of new puzzle packs being available.  We plan on releasing one new puzzle pack a month, and we would like to notify users when they are available.
  2. Notify users about our other puzzle games.  This one makes me a bit nervous as I don’t wont to spam our users, but I also think many Picross HD users would also enjoy some of our other puzzle games.  I’m figuring to give it a try and see what kind of response we get.

I would be interested in hearing what you use push notifications for or what you like or dislike about push notification uses.

Urban Airship

One thing about push notifications is that you need a service to bridge between you and Apple’s push notifications servers.  I considered setting up my own server for this, but I decided to go with Urban Airship for now.  For the level of service I need, their service would be “free” and seemed to be the easiest way to get started with Push Notifications.

Getting Started

Urban Airship has a good getting started guide for push notification.  However, I do have a couple of tips.

Tip 1:  You will need to regenerate your provisioning profiles after you enable push notifications for your existing App Id.  If you don’t, you will get an error when trying to registerForRemoteNotificationTypes as the provisioning profiles needs to be configured for push notifications.

Tip 2: The getting started guide walks through the steps of using a AirshipConfig.plist to switch between production and development for the notification servers.  I don’t like this technique as it is too error prone.  It’s too easy to forget how you have it configured.  They suggest using build scripts to manipulate this file, but I don’t like that from a maintenance perspective plus I didn’t find a quick example of how to do this.  Fortunately, you can do this programmatically instead of using the AirshipConfig.plist.  Here is an example of how taken from the Urban Airship forums (but modified a bit by me). 

- (void)setupUrbanAirshipPushNotificationsWithLaunchOptions:(NSDictionary *)launchOptions{    // Set passed in launch options    NSMutableDictionary *takeOffOptions = [[NSMutableDictionary alloc] init];    [takeOffOptions setValue:launchOptions forKey:UAirshipTakeOffOptionsLaunchOptionsKey];      // Create and set dictionary for AirshipConfig values    NSMutableDictionary *airshipConfigOptions = [[NSMutableDictionary alloc] init];    [takeOffOptions setValue:airshipConfigOptions forKey:UAirshipTakeOffOptionsAirshipConfigKey];      [airshipConfigOptions setValue:@"Application Key" forKey:@"DEVELOPMENT_APP_KEY"];    [airshipConfigOptions setValue:@"Application Secret" forKey:@"DEVELOPMENT_APP_SECRET"];      [airshipConfigOptions setValue:@"Application Key" forKey:@"PRODUCTION_APP_KEY"];    [airshipConfigOptions setValue:@"Application Secret" forKey:@"PRODUCTION_APP_SECRET"];      [UAirship setLogging:YES];      #ifdef PRODUCTION_PUSH_NOTIFICATIONS        [airshipConfigOptions setValue:@"YES" forKey:@"APP_STORE_OR_AD_HOC_BUILD"];    #else        #warning PUSH NOTIFICATIONS SET TO DEVELOPMENT        [airshipConfigOptions setValue:@"NO" forKey:@"APP_STORE_OR_AD_HOC_BUILD"];    #endif      [UAirship takeOff:takeOffOptions];      [[UAPush shared] setDelegate:self];    [[UAPush shared] resetBadge];   //zero badge on startup    [[UAPush shared] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |                                                         UIRemoteNotificationTypeSound |                                                         UIRemoteNotificationTypeAlert)];} 

This can be called from within application:didFinishLaunchingWithOptions. 

Tip 3: In order to test notifications you can use the command line utility curl.  However, I ended up using an app called RESTed available on the Mac App Store.  Its UI could be a bit better, but I was able to edit the Push payload easier in RESTed then trying to do it on the command line.  I also found that with curl the payload didn’t like being split on multiple lines using line continuations.

Tip 4: Add the application:didFailToRegisterForRemoteNotificationsWithError to your app delegate.  The guide doesn’t instruct you to do this, but if something goes wrong during device registration, its very handle to have this method log the error information.

Processing Push Notifications

When processing push notifications it’s up to the App to figure out what to do with the notifications (including showing them).  The UAPush class from Urban Airship helps manage push notifications by handling things like badges and parsing of push notifications.   Setting up UAPush is easy, as you can see in the example code above.

In order for UAPush to parse the notifications, you need to pass them to UAPush via its handleNotification:applicationState method.

This was taken from example code for the UAPush.  However, I modified it to remove the applicationState check.   application:didReceiveRemoteNotification can be called before the application has been made active.  However, I still want to display an alert even if we are becoming active.  From what I can tell the method only gets called while the application is being “launch” or “restored”, it doesn’t get called while the app is backgrounded.  However, if handleNotification:applicationState is called with an inactive state, it won’t call its delegate parsing methods.  Which isn’t what I wanted.  I want the App to display a notification if the notification is clicked on outside the app.

I still looking into understanding the implications of this, but I think for my purposes (of displaying an alert) it is fine.

Localization Implications

Picross HD is localized into 5 languages so when sending notifications, I would like them to be localized.  However, I haven’t figured out how to send a localized push alert  (see “loc-key”) without having the text pre-localized and stored in the application’s Localizable.strings file(s).

While you can send custom push notifications that are localized, iOS won’t know how to display them.  For notifications within the App that isn’t an issue because the App has control of that, but when the app is in a background iOS can only display “toast” messages for types it knows about such as alerts.

This means you have to predetermine the messages you might want to send if you want them localized.  You can also supply message arguments to fill in placeholders in the message such as %@.  However, I don’t believe the arguments are localized.

Conclusion

I’m still working on the implementation and trying to figure out the types of messages and workflows I want to do.  For example, if I do an announcement of a new puzzle pack some people may be on the old version that doesn’t have that puzzle pack available and some may be on the new version that has the new puzzle pack.  In the first case, I may want to provide an option for the use to update to the latest version, in the later case I may want to take them to the new puzzle pack so they can try it out.

I hope this was useful.  Please try out Picross HD and our other puzzle games for iOS.

- Tod

LayoutScrollView (Cocoa Controls)

Posted by Cocoa Controls at Cocoa Controls
A layout ScrollView / ViewController pair that implements iOS5 containment and allows for swiping between multiple top level root view controllers. Implements Android style app navigation on iOS.

image of this control

Control of the Week: OCCalendar (Cocoa Controls)

Posted by Cocoa Controls at Cocoa Controls

Our control of the week, OCCalendar is a very simple component for iPhone/iPad that provides a “Popover” date picker controller. It is very easy to add to your project, and is 100% CoreGraphics code, so it uses no images, and is resolution independent. BSD licensed.

Find out more, or check it out on YouTube first:

WP Like Button Plugin by Free WordPress Templates