Shahzad Bhatti

September 17, 2012

Tips from Unusually Excellent: The Necessary Nine Skills Required for the Practice of Great Leadership

Filed under: Business — admin @ 2:17 pm

I recently read Unusually Excellent: The Necessary Nine Skills Required for the Practice of Great Leadership. Here are a few tips I enjoyed from the book:

Credibility

Earning the Right to Lead Through Character

This book shows that in order to gain credibility, you need to be authentic, trustworthy, and have character traits such as courage, integrity, and commitment:

  • Being Authentic
  • Look at Life: Seeing Who You Are
  • Owning Your Past: The Sting of Failure – Adversity demands more of us than normal times do.
  • One Day at a time – An Unexpectedly Bad Day
  • Share the Shame – You can share a couple of your past disappointments with your team mates to connect with them on a personal level
  • Face Time – Meet face to face to build personal relationships
  • The Perception Gap – Get feedback on how others see you
  • The Courage to Listen
  • Honest Feedback – great leaders don’t avoid conflict and give honest feedback but at the same time be authentic and professional.

Being Trustworthy

The book shows that great leaders build a track record of honesty, fairness, and integrity that creates a leadership “equity” within their constituency. Trustworthiness takes precedence over heavyweight attributes like creativity and intelligence.

  • Safely Successful – physical, emotional and professional safety is primarl need.
  • Be honest – match your actions with your words and match those words with the truth we see in the world (no spin).
  • Be vulnerable – showing your weakness or raw emotion
  • Be fair
  • A better place for all – The book recommends building trusted interpersonal relationships that have commitments to work and loyality. On the other hand fear inspires defensive behavior, which leaders can eliminate fear by being transparent, crystal clear, and integrity.
  • A Culture of Trust Is a Culture of Truth – One reason people within enterprises fear telling the truth to each other and to their bosses is that they know the organization cannot properly distinguish between the message and the messenger.
  • Bad News Doesn’t Swim Upstream
  • A Culture of Trust Is a Culture of Innovation – Trust is the basis of safety. Create trust, and you’ll create a safe place to take risks and in turn build culture of innovation. The organizations should not punish “good failure”
  • A Culture of Trust Is a Culture of Performance – you should never punish a good person for delivering bad news—or even, on occasion, bad work.
  • Take Your Pain Quickly and Acutely—and Move On

Being Compelling – Commitment to Winning

The book shows that great leaders evoke the emotion and energy of being involved in a crusade. No one will sacrifice for a project if the leader hasn’t made a full and clear—and public—commitment. Great leaders don’t want to be merely an employee instead they want to be part of a team, working together to create something important.

  • Choice and Obligation – The best, most talented followers are really volunteers, and because of those very attributes they are often in considerable demand elsewhere.
  • Attracting the Best and Brightest – Great leaders engage and listen to people.
  • Keeping Your Best on Board
  • Cheerleader
  • Tell Me the Truth – the best people actually find reality, even if it is bad news, compelling.
  • Keep Me Challenged – Talented people want and need challenging work.
  • No Hard Feelings – leaders must be able to stand in their followers’ shoes and see themselves from that viewpoint.

Competence: Leading on the Field with Skill

  • Leading People Talent to Teams – Hiring great people is arguably the highest-leverage activity that leaders undertake.
  • Seating Chart – talent is useless if the person is not a good match with that role and responsibility and a specific place in the structure of the organization.
  • People First – hire the very best people; only then should you focus on building the right plan for the organization.
  • Engagement – engage people by setting realistic goals with them and fairly rewarding them for meeting or exceeding those expectations.
  • Enrollment
  • Expectations
  • Energy – functional, emotional and career energy.
  • Empowerment – delegate power to other people
  • Retreat to Attack
  • How Has the Nature of Your Enterprise Changed? – As a leader, if you have not prepared your people for that change or you resist that change, you have failed in your responsibilities.
  • Where Is Your Authority or Positional Power Best Used in Leading People? – By carefully setting performance expectations with your key team members, you move the whole game up a notch.
  • What Is Your Plan to Deal with Your Weakest Link? – being aware of poorly performing subordinate and acting on it instead of avoiding it.
  • Will You Distinguish the Bad Performer from a Bad Plan? – think like a venture capitalist, with your project leaders as the entrepreneurs and the project itself a new venture. Have a post-mortem and inquire why project failed.

Leading Strategy – ideas to plans

Leaders need to distinct between leading people, strategy and execution.

  • Process to Plans – plan shows what needs to be done, where as trategy is bigger than plan and includes how things are done and fallback options.
  • The Process: Inclusive and Collaborative – The process must include the best people and the best ideas, from both within and outside the company, and must foster collaborative thinking and constructive, rigorous discussion.
  • Winnowing Out a Plan – solicit ideas from others when you don’t know the domain
  • The Plan: Realistic and Compelling – The book shows that leaders need to be engaged throughout the process to make sure the process moves along with appropriate energy and that the team remains realistic in terms of time, resources, and goals.
  • Stickiness – commitment in the face of adversity

Leading Execution – actions to results

Execution is about results. Leaders need to distinct between leading people, strategy and execution. Execution provides feedback that can be measured against plans.

  • Solve the Hard Problems First – don’t distract yourself with second-tier tasks
  • At the Edges – In order to build high-reliability organizations (e.g. SWAT), you need zero tolerance team execution, which require:
    • reliable communications
    • continuous training
    • standardize and synchronize
    • mission-goal clarity and loyality
    • empower the front line
    • redundancy
  • Leadership Leverage in Execution – The book suggests leading the process and setting the standards for the right goals. This includes leading the design process to create the appropriate metrics, ensuring a winner’s commitment and making sure that attitude permeates the culture.
  • Curb Your Enthusiasm: Focus, Commit, and Deliver – don’t overcommit and follow the rule of “first things first.”
  • It Isn’t Real If You Don’t Measure It – Measuring what matters is an extremely high-leverage opportunity. Use management by objectives (MBO), “as measured by” (AMB) or a key performance indicator (KPI) processes for measureing factors that correlate very highly with winning.
  • Let the Dashboard Drive – Measuring what matters to naturally direct attention, focus, and commitment to the right activities
  • It’s Just Like Pinball: If You Win, You Get to Play Again
    • Winner’s mindset
    • Failing elgantly – No lame excuses
  • Sloppiness – HRO never allow sloppiness because they know it equals death. The book shows that leaders may
    feel like part of being a nice guy, succumbing to that temptation promotes a culture of mediocrity.

  • Performance Feedback – look for data coming back from the field.

Consequence: Creating a Culture, Leaving a Legacy of Values

Trust is the most fragile of assets; at a certain point, different in every situation.

Legacy = Culture + Reputation

A Leader’s Communication

  • Open, Honest Dialogue – The book shows that the ability of leaders to communicate effectively is highest leverage activity in their set of responsibilities and should include:
    • What are we doing? (Vision and mission.)
    • Why are we doing it? (Purpose and goals.)
    • What’s the plan to win?
    • (What’s the strategy here?)
    • How are we doing? (Results and status—health of the business.)
    • What is my part in the game? (What do you expect from me?)
    • What’s in it for me? (Why is this a compelling place for me to be?)
    • How am I doing? (Give me feedback, acknowledgment, appreciation.)

Talking Trust

In order to build trust, leaders not only need to focus on contents but also emotional content of that message and the
connection—the leader’s empathy with the audience.

Checklists and Guideposts

Here are some key points from the book:

  • communication is a core responsibility of leading
  • most of the important things in organizations are the result of the right conversation
  • starving followers from basic information will result in high cost

Here are five C’s for What question leader needs to communicate:

  • A compelling cause
  • Credibility & Competence
  • Character
  • Commitment
  • Contribution

Here are five E’s for Why question leader needs to communicate:

  • Engagement
  • Enrollment
  • Energy
  • Empowerment
  • Endorsement

Here are six C’s for When question leader needs to communicate:

  • Context
  • Confidence
  • Challenge
  • Collaboration
  • Culture
  • Coaching

Here are seven C’s for How question leader needs to communicate:

  • Clarity
  • Consistency
  • Carefulness
  • Courage
  • Conviction
  • Compassion
  • Completion

The Solitary Touch

The book shows that there is really no such thing as a “casual” conversation.

Your 24 × 7 Job

The book shows leader has three basic tasks:

  • Align the interests, energy, and commitment of the team.
  • Reduce fear, confusion, and anxiety.
  • Instill confidence and trust, while rallying support and contributions.

A Leader’s Decision Making Values-Based Choices

The book shows that leader does not need to make most of the decisions, but need to help followers make make better decisions.

Decision Structure

  • What Exactly Are We Deciding?
  • What Flavor Is This Decision? – decisions can be classified as either simple or complex. You need sufficient data to make the decision, otherwise you have to use intuition. Decisions can also be characterized as easy or difficult.
  • When Does This Decision Need to Be Made?

    Total Cycle Time = Time to Decide + Time to Commit + Time to Execute

  • Who Should Make This Decision? – who is best equipped—by skill, experience, proximity
  • Don’t Wait; Decide
  • Chasing Decisions – communicate with followers and empower them to make decisions

A Leader’s Impact The Transfer of Influence from Leader to Follower

Finally, the book shows how to build lasting legacy and reputation:

  • Leader Taking the High Ground
  • Whisper Campaign – use public forums to acknowledge accomplishments, sacrifices and courage. Also, appreciate them in private.
  • All You Leave Behind – using exit interviews to get feedback
  • Collective Memory
  • What to Do
  • Pay attention to change
  • Get More Curious, and Smarter, About Human
  • Nature – leaders tend to gravitate toward the objective and away from the subjective.
  • Give feedback
  • Celebrate success
  • Respect Life Outside of Work
  • Your Greatest Legacy


September 6, 2012

Building a streaming quote server using Node.js and Websockets

Filed under: Javascript — admin @ 5:32 pm

A couple of years ago, I implemented a quote server using XMPP, Bosh, Strophe and Ejabbberd at work and described an overview of the design and code in my blog. We have been looking at Node.js and Websockets recently for streaming data so I will describe a simple implementation of quote server here using those two technologies:

Quote Server

The quote server uses Web sockets and listens for subscribe-stock-quote message to subscribe for a particular quote and unsubscribe-stock-quote message to unsubscribe.
Here is a simple implementation of the Quote server:

 var express = require('express')
    , sio = require('socket.io')
    , http = require('http')
    , quoteSubscriptions = require('quote_subscriptions')
    , app = express();
 
 var server = http.createServer(app);
 var sequence = 0;
 app.configure(function () {
    app.use(express.static(__dirname + '/public'));
    app.use(app.router);
 })
 
 var io = sio.listen(server);
 io.set('log level', 1);
 server.listen(8080);
 
 io.sockets.on('connection', function(socket) {
    // subscribe to stock quotes 
    socket.on('subscribe-stock-quote', function(symbol) {
       console.log('subscribe-stock-quote received');
       quoteSubscriptions.subscribe(socket, symbol, function() {
          socket.emit('subscribed-stock-quote', 'You have been subscribed to ' + symbol);
       });
    });
 
    // unsubscribe to stock quotes 
    socket.on('unsubscribe-stock-quote', function (symbol) {
       console.log('unsubscribe-stock-quote received');
       quoteSubscriptions.unsubscribe(socket, symbol, function() {
          socket.emit('unsubscribed-stock-quote received', 'You have been unsubscribed to ' + symbol);
       });
    });
 
    // disconnected
    socket.on('disconnect', function() {
       quoteSubscriptions.unsubscribeAll(socket, function() {
          socket.emit('disconnected', socket.symbol + ' has been unsubscribed from stock quotes.');
       });
    });
 });
 
 // update clients every 500 milli-seconds with latest stock quotes
 setInterval(function () {
    quoteSubscriptions.pushUpdates();
    io.sockets.emit('sequence', ++sequence);
 }, 500);
 
 
 

In addition to sending quote updates, the server also sends a loop counter so that we know how many times quotes have been pushed to clients and that message is broadcasted to all clients.

The subscriptions are managed in another module quote_subscriptions, i.e.,:

 ////////////////////////////////////////////////////////////////////////////////////////////
 //
 // This module maintains quote subscriptions for all clients 
 //
 ////////////////////////////////////////////////////////////////////////////////////////////
 var yclient = require('y_client');
 var stocksSubscribers = {};
 var quoteCache = {};
 exports.subscribe = function(socket, symbol, callback) {
    if (typeof socket.stockSymbols === "undefined") {
       socket.stockSymbols = [];
    }
    if (socket.stockSymbols.indexOf(symbol) == -1) {
       socket.stockSymbols.push(symbol);
    }
    //
    var subscribers = stocksSubscribers[symbol];
    if (typeof subscribers === "undefined") {
       subscribers = [];
       stocksSubscribers[symbol] = subscribers;
    }
    if (subscribers.indexOf(socket) == -1) {
       subscribers.push(socket);
    }
    callback();
 }
 
 exports.unsubscribeAll = function(socket, callback) {
    if (typeof socket.stockSymbols === "undefined") {
       return;
    }
    for (var i=0; i<socket.stockSymbols.length; i++) {
       this.unsubscribe(socket, socket.stockSymbols[i], function() {});
    }
    callback();
 }
 
 exports.unsubscribe = function(socket, symbol, callback) {
    if (typeof socket.stockSymbols === "undefined") {
       return;
    }
    var ndx = socket.stockSymbols.indexOf(symbol);
    if (ndx !== -1) {
       socket.stockSymbols.splice(ndx, 1);
    }
    //
    var subscribers = stocksSubscribers[symbol];
    if (typeof subscribers === "undefined") {
       return;
    }
    ndx = subscribers.indexOf(socket);
    if (ndx !== -1) {
       subscribers.splice(ndx, 1);
    }
    callback();
 }
 exports.pushUpdates = function() {
    for (var symbol in stocksSubscribers) {
       var sockets = stocksSubscribers[symbol];
       if (sockets.length == 0) {
          continue;
       }
       quote = quoteCache[symbol];
       if (typeof quote === "undefined") {
          yclient.quote(symbol, function(quote) {
             quoteCache[symbol] = quote;
             sendQuote(quote, sockets);
          });
       } else {
          sendQuote(quote, sockets);
       }
    }
 }
 
 
 function sendQuote(quote, sockets) {
    var rnd = Math.random();
    quote.counter = quote.counter + 1;
    quote.bid = round(rnd % 2 == 0 ? quote.original_bid + rnd :  quote.original_bid - rnd, 2);
    quote.ask = round(rnd % 2 == 0 ? quote.original_ask + rnd :  quote.original_ask - rnd, 2);
    for (var i=0; i<sockets.length; i++) {
       var socket = sockets[i];
       var address = socket.handshake.address;
       console.log('Quote sending ' + quote.symbol + ' ' + quote.counter + ' to ' + address.address + ":" + address.port);
       socket.volatile.emit('receive-stock-quote', quote);
    }
 }
 
 function round(num, dec) {
    return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
 }
 
 
 

The above module defines methods to subscribe, unsubscribe and push quote updates to all clients. Note that above module requests quotes from Yahoo if it doesn’t exist in the cache and then randomly changes bid/ask values.

Yahoo Finance Client

I used Yahoo finance to retrieve the quotes, however these quotes are cached and modified by the quote subscription module:

 ///////////////////////////////////////////////////////////////////////////////////////////
 //
 // This module provides quote/chain apis using yahoo finance
 //    
 ////////////////////////////////////////////////////////////////////////////////////////////
 var http = require('http')
   , libxmljs = require('libxmljs')
   , util = require('util')
       
          
 exports.quote = function(symbol, callback) {
    api('download.finance.yahoo.com', '/d/quotes.csv?s=' + symbol + '&f=nb2b3ra2yj3e7gopjkl1xm3m4h', function(text) {
       cols = text.split(',');
       callback({'symbol':cols[0], 'ask':cols[1], 'bid':cols[2], 'counter':0, 'original_ask':cols[1], 'original_bid':cols[2]});    
    });
 }  
 
 function api(host, path, callback) {
    var options = {
        host: host,
        port: 80,
        path: path, 
        method: 'GET',
        headers: {'User-Agent': 'Node'}
    };
    var req = http.request(options, function(res) {
      res.setEncoding('utf8');
      var text = '';
      res.on('data', function (chunk) {
        text += chunk;
      });
      res.on('end', function (e) {
         text = text.replace(/"/g, '');
         callback(text);
      });
      res.on('error', function (e) {
        console.log('Could not send api with response : ' + e.message);
      });
    });
 
    req.on('error', function(e) {
      console.log('Could not send api with response : ' + e.message);
    });
 
    // write data to request body
    req.end();
 }
 
 

Web Client

Here is an example of Web client that allows users to subscribe to different stock symbols and receive streaming quotes every 500 milliseconds.

 <!doctype html> 
 <html lang="en">
    <head>
       <meta charset="utf-8"> 
       <title>OptionsHouse Streaming</title>
       <script src="/socket.io/socket.io.js"></script>
       <script> 
          var socket = io.connect('ws://localhost:8080'); 
          var lastSymbol;
          var lastQuote;
          socket.on('connect', function() { 
             lastSymbol = 'AAPL';
             socket.emit('subscribe-stock-quote', lastSymbol);
          });         socket.on('disconnect', function() {
             alert('remote server died');
          });
          socket.on('sequence',function(seq) { 
             var seqDiv = document.getElementById('sequence');
             seqDiv.innerHTML = seq;
          }); 
          socket.on('receive-stock-quote',function(quote) { 
             var company = document.getElementById('company');
             var counter = document.getElementById('counter');
             var bid = document.getElementById('bid');
             var ask = document.getElementById('ask');
             var bidColor = '<font color="black">'
             var askColor = '<font color="black">'
             if (typeof lastQuote !== "undefined") {
                if (quote.bid > lastQuote.bid) {
                   bidColor = '<font color="green">'
                } else if (quote.bid < lastQuote.bid) {
                   bidColor = '<font color="red">'
                }
                if (quote.ask > lastQuote.ask) {
                   askColor = '<font color="green">'
                } else if (quote.ask < lastQuote.ask) {
                   askColor = '<font color="red">'
                }
             }
             company.innerHTML = quote.symbol;
             counter.innerHTML = quote.counter;
             bid.innerHTML = bidColor + quote.bid + '</font>';
             ask.innerHTML = askColor + quote.ask + '</font>';
             lastQuote = quote;
          });
    
          window.addEventListener('load',function() { 
             document.getElementById('start').addEventListener('click',
             function() { 
                if (typeof lastSymbol !== "undefined") {
                   socket.emit('unsubscribe-stock-quote', lastSymbol);
                }
                var symbol = document.getElementById('symbol').value; 
                socket.emit('subscribe-stock-quote', symbol);
                lastSymbol = symbol;
             }, false); 
             document.getElementById('stop').addEventListener('click',
             function() { 
                var symbol = document.getElementById('symbol').value; 
                socket.emit('unsubscribe-stock-quote', symbol);
             }, false); 
          }, false);
       </script> 
    </head> 
    <body>
       <div id="form">
          Symbol: <input type="text" id="symbol" size="10" value="AAPL" />
          <input type="button" id="start" value="Subscribe" />
          <input type="button" id="stop" value="Unsubscribe" />
       </div>
       <table width="500">
          <tr>
             <th>Company</th>
             <th>Bid</th>
             <th>Ask</th>
             <th>Stock Counter</th>
          </tr>
          <tr>
             <td align="center"> <div id="company"></div> </td>
             <td align="center"> <div id="bid"></div> </td>
             <td align="center"> <div id="ask"></div> </td>
             <td align="center"> <div id="counter"></div> </td>
          </tr>
       </table>
       <p></p>
       Quote Server Loop: <span id="sequence"/>
    </body>
 </html>
 
 

Running the example

You can download all the code from My github account, e.g.

 git clone https://github.com/bhatti/node-quote-server.git  
 cd node-quote-server 
 npm install
 node app
 

Then you can point your browser to http://localhost:8080 and start playing:

Summary

Node.js comes with good support for Websockets so it takes only few lines to build the quote server. I am still testing Node.js and Websockets with different browsers and simulating load with large number of clients and will post those results in future.


August 8, 2012

Back from OSCON 2012

Filed under: Computing — admin @ 5:58 pm

I went back to OSCON last month (July 2012), which was held in Portland again. I saw the biggest crowd this year and over 3000 folks attended the conference. Here are some of the tutorials and sessions I attended:

R

I attended R tutorial on the first day, which I found quite informative. There has been a lot of interest in Data Science and R is a great tool for statistical analysis and graphs.

Scala

On the second half of Monday, I attended Scala Koans, which was disappointing. First, they could not get us started with the session as Wifi died on us and they didn’t have much backup plan. We finally started the session after waiting for an hour and then were mostly left on our own to finish the Koans. Yeah, I could have done that myself by downloading Koans.

Android-Fu

On Tuesday, I attended Android-Fu, which was somewhat useful. I have had quite a bit Android development at work, but I got a few pointers.

Android Testing

The second half of Tuesday, I attended Android Testing, which was useful but the presenter was incredible boring and had hard time keeping awake. [Slides]

Go

The real conference started on Wednesday and I attended Go session, which was mostly about governance behind Go language.

Storm

I then attended session on Storm, which was informative described differences between Hadoop and Storm and showed some actual code.

MongoDB

I then attended session on Running MongoDB for High Availability, which showed some of weak areas and lessons learned while scaling MongoDB. [Slides]

Apache Zookeeper

This session was also very informative and it showed various uses of Zookeeper.

Disruptor

I then attended session on Disruptor, which is incredibly fast concurrency framework. [Slides]

Building Functional Hybrid Apps For The iPhone And Android

I then attended Building Functional Hybrid Apps For The iPhone And Android, which was mostly marketing talk for Websphere IDE and speakers ignored value of PhoneGap (Apache Cordova), which was behind their demo.

Node.js

On thursday, I attended session on Node.js, which was nice introduction with some code samples. [Slides]

I attended another session on Node.js about Node.js in Production: Postmortem Debugging and Performance Analysis, which showed a number of ways to debug your Node.js applications. [Slides]

Advanced MySQL Replication Architectures

This was also very informative session and you can take a look at slides.

The Art of Organizational Manipulation

This was entertaining talk about how to build influence in workplace.

High Performance Network Programming on the JVM

This was another informative talk about building network applications in Java and you would slides very helpful.

Summary

I found very few sessions on mobile this year and there were a couple of sessions on Android and I wanted to see more. There were a lot of vendor sponsored sessions on private clouds and a lot of vendors in exhibition hall were promoting frameworks such as OpenStack, CloudStack, Eucalyptus and others. There were also quite a few sessions on distributed frameworks such as Hadoop, HBase, MongoDB, Zookeeper, Storm, Disruptor, etc, which I enjoyed. I didn’t see a lot of sessions on functional languages as past and wanted to see some sessions on Clojure (which was cancelled).
NoSQL Databases – A few sessions were on HBase, MongoDB and Cassandra. There was a lot of enthusiasm for HTML5 again and a lot of sessions were sold out. Having attended similar sessions in past, I skipped most of them. Overall, I had good time but not sure if I would be back next year. You can read presentation slides from http://www.oscon.com/oscon2012/public/schedule/proceedings.

May 22, 2012

Review of ‘Good Boss, Bad Boss: How to Be the Best… and Learn from the Worst’

Filed under: Business — admin @ 4:27 pm

I recently finished Bob Sutton’s book Good Boss, Bad Boss, who is well known for his book The No Asshole Rule: Building a Civilized Workplace and Surviving One That Isn’t . As most of us, I have many bosses and also manage other people so I have found this book quite useful. Good bosses not only help productivity and work environment but they also reduce stress, diseases or family troubles.

Bob shows that good boses apply Lasorda’s law and use less management, however they don’t ignore their people and help them out. Also, good bosses have mentality of running marathon rather than sprint and they instill grit in followers, where they push them to try a bit harder and be more creative. Bob suggests using small wins and manageable tasks to drive focus and sense of accompllishment in followers. Bob warns against bosses with attitude of toxic tandems, who are self absorbed. Good bosses also back their followers and balance performance and humanity by helping people to do great work and experience pride and dignity.

Here are highlights from Bob’s book:

Take Control

The media generally portrays leaders as heros, but research shows that most bosses have little impact on overall performance of a company. Good bosses use this illusion to their advantage to bring confidence in their followers and increasing odds of their success.

Don’t Dither

Good bosses use crisp language and decide unequivocally, however they are not afraid to change their decisions. They follow the rule of strong opinions that are weakly held.

Get/Give Credit

Bosses get credit no matter what but good bosses also give credit to others. I have worked in environments, where bosses took all the glory and passed shit to their followers. However, everyone wins if boss give credits as much as possible.

Blame yourself

Good bosses also take the heat for team, which builds loyalty of their followers.

Strive to be Wise

Good bosses create balance of over confidence and healthy dose of self doubt. They ask questions and listen instead of talking too much. Wise bosses assume best from their people and show them compassion and love.

Forgive and Remember

Wise bosses forgive and remember the mistakes so that they can learn from them instead of blaming followers or forgetting them altogether.

Safety & Creativity

Wise bosses create safe environment to share ideas and be more creative. They fight for what they believe in but gracefully accept defeat.

Participation

Wise bosses ask good questions, listen and ask for help. They show empathy, compassion and gratitude to their followers. They know their flaws and work with other people to compensate for their weaknesses.

Stars & Rotten Apple

Some organizations glorify solo stars, which undermines team collaboration. Good bosses recruit energizers and eliminate bad apples or energy suckers, who undermine constructive actions.

Keep teams together

Good bosses keep teams together. I have found that a new team takes a couple of months to gel, and having worked in project-based teams (which was awful) I take this advice to the heart.

Link Talk & Action

Good bosses say same simple things and build harmony between their actions and words. They empathizes with their customers by eating their own dog food. They try to reduce complexity and use simple principles, strategies, and metrics.

Don’t shirk Dirty Work

Good bosses confront problems directly, which may include personnel problems such as firing low performer or bad apple. They create realistic expectations for followers and make tough decisions, however they make those decisions with understanding, control and compassion.

Squelch your inner Bosshole

Let’s face it, there are plenty bosses who act like assholes. Unfortunately, most of them are unaware of their attitude and habits. Bossholes create negative work environment and cause health problems for their followers. I have worked in companies, where this was cultural issue and the role models of bossholes was passed from top-down. Nevertheless, this is often the cause of employees leaving companies or having heart attacks. Bob suggests a couple of solutions such as tape method to help manage anger.

Summary

As we spend most part of day at work, it helps if the work environment and the boss is empathetic. Bob provides a lot of advice to bosses so that they can build better work environment for their followers.

April 26, 2012

How to survive in today’s work environments and businesses

Filed under: Business — admin @ 10:39 pm

In modern work environments and businesses, it is crucial to expedite learning cycle and create a knowledge workplace. In order to shorten the learning cycle, you can apply the scientific approach, which comprises of three stages, i.e., making a hypothesis, testing the hypothesis and validating test results. Generally, the test results leads to another hypothesis, and another cycle of experiment, validation and then publishing results. At the end of each cycle, you learn something knew, thus the shorter your cycle the faster you learn. Following are few variations of this approach used in manufacturing, research and development:

OODA

John Boyd revolutionized military aviation strategy by designing lightweight fighter planes that were based on a shorter loop of

  • Observe
  • Orient
  • Decide
  • Act

John showed that light-weight planes that provided quick feedback to pilots proved better in dogfights. It showed that speed of loop beats quality of iteration.

Theory of Constraint

The theyory of constraint creates flow of an activity and finds all constraints from end to end and then tries to remove biggest constraint. It then repeats the process and identifies next biggest constraint and solves that constraint.

Lean Manufacturing

Lean manufacturing is based on Toyota production system that emphasizes waste elimination and creating value for customers. Lean production system stresses reducing activity time from start to finish and continuous improvement or Kaizen.

Lean Software Development

Lean software development applies lessons of Toyota production systems to software development by eliminating waste, reducing in-progress work (inventory), and amplifying learning. It speeds up learning process by short cycle of iterative development.

Lean Startup

The startups generally start with visions or hypothesis that are unproven. Lean startups borrow ideas from Toyota production systems by creating rapid prototypes that test market assumptions and uses customer feedback evolve the product. Just like the scientific approach, it uses a cycle of product-idea or hypothesis, product-development or preparing an experiment, releasing the product, where startups collects data about value to users. The test results help startups adjust the product and another round of tests are followed. The Lean Startups emphasized validated learning that you gain from running actual experiment than just guess work.

Spiral Methodology

Spiral methodology is a software development process that uses iterative development and encourages prototyping and experimenting. Each iteration starts with objectives, constraints, and alternatives, which are then evaluated, developed and then validated.

Scrum Methodology

Scrum is an iterative and incremental agile software methodology for project management. It uses short sprints for software development, where each sprint starts with planning meeting that defines the user stories or features to be delivered, followed by development and release. At the end of sprint, the team holds Sprint review meeting and retrospective to identify impediments so that team can improve the process. The whole process is repeated with another round of short sprints.

Other Agile Methodologies

There are a number of other agile methodologies that also founded on short iterations and incremental development such as Agile Unified Process, Crystal Clear, XP, Feature driven development. These methodologies encourage transparent, collaborative and open work environments, which provide foundation for adoptive and knowledge workplaces.

Test-Driven Development

Test-driven development is a software development process uses a short cycle of development, where developer writes a failing test case for desired functionality, then implements functionality to pass the test and finally refactors the new code. It eliminates the waste by focusing on business functionality that is required and helps build design incrementally. Each cycle of TDD is very short and provides rapid feedback to developer if the code is working.

Integrated Development Environment (IDE)

Modern IDEs are built to shorten development cycle by providing rapid feedback to developer such as syntax warnings, errors and integration to testing, debugging, static analysis, deploying and other tools. The productivity of developer increases when the cycle from edit, build to test, debug or deploy is short.

One-on-One vs Annual Reviews

Unfortunately Annual Reviews are still annual rituals in most companies that provide feedback once a year. Instead weekly one-on-one provide shorter feedback and is more effective.

Opinions vs Data

All of us have plenty of opinions which are nothing more than guesses. Modern development methodologies such as Lean software development or Lean startup encourages data-driven approach by executing short experiments and learning from the experiments.

Summary

We live in rapidly changing knowledge economy. We need to learn how to be nimble and to create a culture that speeds up learning process by performing short experiments. Instead of working in vacuum, we need to validate our assumptions and guesses with actual experiments and take data-driven approach to test our hypothesis. This approach is more bottom-up approach but it doesn’t mean that we don’t have a vision. It just means, we are continuously learning, improving and adopting as our environment changes.

March 10, 2012

Building custom split view controller and tab view controller with horizontal/vertical orientations for iPhone and iPad

Filed under: iPhone development — admin @ 10:49 am

Over the last few years, I have been developing iPhone and iPad applications and one of recurring problem is managing how to present information in flexible way that works on both iPhone and iPad. The iOS platform uses UITabBarController to organize controllers, however it also comes with a number of limitations such as it only show five tabs on iPhone and though you can add more tabs but you have to go through “More” tab to access them. Also, it always show the tabs on the bottom and you cannot change their position.

I would show how you can develop a customized tab controller that works on both iPad and iPhone and supports multiple orientations.

Custom Split View Controller

The first thing I needed was to split screen between tab-bars and the main view and though iPad platform supports split view controller (UISplitViewController), however, there are several limitations of the builtin UISplitViewController class such as it only works on iPad in landscape mode and it does not work in iPhone. Here is an example of customized split view controller:

 #import "MasterDetailSplitController.h"
 #import "MenuViewController.h"
 #import "MenuCellView.h"
 
 
 @implementation MasterDetailSplitController
 
 @synthesize menuViewController = _menuViewController;
 @synthesize detailsViewController = _detailsViewController;
 @synthesize menuView = _menuView;
 @synthesize detailsView = _detailsView;
 
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
     if((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
     }
     return self;
 }
 
 - (void)dealloc {
     [_menuViewController release];
     [_detailsViewController release];
     [_menuView release];
     [_detailsView release];
     [super dealloc];
 }
 
 
 
 #pragma mark - View lifecycle
 
 - (void)viewDidLoad {
     [super viewDidLoad];
     isPortrait = YES;
     
     self.menuViewController = [[[MenuViewController alloc] initWithSplit:self] autorelease];
     self.menuViewController.view.frame = CGRectMake(0, 0, self.menuView.frame.size.width, self.menuView.frame.size.height);
     [self.menuView addSubview:self.menuViewController.view];
     self.menuView.transform = CGAffineTransformMakeRotation(-M_PI * 0.5);
     self.menuView.autoresizesSubviews = YES;
     self.menuView.backgroundColor = [UIColor grayColor];
     [self layoutSubviews];
 
 }
 
 
 - (void)viewDidUnload {
     [super viewDidUnload];
     self.menuViewController = nil;
     self.detailsViewController = nil;
     self.detailsView = nil;
 }
 
 
 - (void) pushToDetailController:(UIViewController *)controller {
     if (self.detailsViewController == controller) {
         return;
     }
     if (self.detailsViewController != nil && [self.detailsViewController isKindOfClass:[UINavigationController class]]) {
         UINavigationController *navCtr = (UINavigationController *)self.detailsViewController;
         if ([navCtr.viewControllers containsObject:controller]) {
             return;
         }
     }
     for (UIView *v in self.detailsView.subviews) {
         [v removeFromSuperview];
     }
     if (![controller isKindOfClass:[UINavigationController class]]) {
         UINavigationController *navCtr = [[[UINavigationController alloc] initWithRootViewController:controller] autorelease];
         [navCtr setDelegate:self];
         controller = navCtr;
     }
 
     [self layoutSubviews];
 
     controller.view.frame = CGRectMake(0, 0, self.detailsView.frame.size.width, self.detailsView.frame.size.height);
     controller.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth
     | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin
     | UIViewAutoresizingFlexibleRightMargin  | UIViewAutoresizingFlexibleLeftMargin;
     
     self.detailsView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;    
     self.detailsViewController = controller;
     [self.detailsView addSubview:controller.view];
 
 }
 
 
 
 
 #pragma mark -
 #pragma mark STANDARD METHODS
 
 - (void) viewWillAppear:(BOOL)animated {
     [super viewWillAppear:animated];
     
     [self.menuViewController viewWillAppear:animated];
     [self.detailsViewController viewWillAppear:animated];
 }
 
 - (void) viewDidAppear:(BOOL)animated {
     [super viewDidAppear:animated];
     [self.menuViewController viewDidAppear:animated];
     [self.detailsViewController viewDidAppear:animated];    
 }
 
 - (void)viewWillDisappear:(BOOL)animated {
     [super viewWillDisappear:animated];
     [self.menuViewController viewWillDisappear:animated];
     [self.detailsViewController viewWillDisappear:animated];
 }
 
 - (void)viewDidDisappear:(BOOL)animated {
     [super viewDidDisappear:animated];
     [self.menuViewController viewDidDisappear:animated];
     [self.detailsViewController viewDidDisappear:animated];
 }
 
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
     return YES; 
 }
 
 - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
     isPortrait = toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown;
     if (isPortrait) {
         self.menuView.transform = CGAffineTransformMakeRotation(-M_PI * 0.5);
     } else {        
         self.menuView.transform = CGAffineTransformIdentity;
     }
     [self.menuViewController willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
     [self.detailsViewController willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
 }
 
 
 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
     isPortrait = fromInterfaceOrientation != UIInterfaceOrientationPortrait && fromInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
     [self layoutSubviews];
     [self.menuViewController didRotateFromInterfaceOrientation:fromInterfaceOrientation];
     [self.detailsViewController didRotateFromInterfaceOrientation:fromInterfaceOrientation];
 }
 
 - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
     [self.menuViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
     [self.detailsViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
 }
 
 - (void)willAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
     [self.menuViewController willAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
     [self.detailsViewController willAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
 }
 
 - (void)didAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
     [self.menuViewController didAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation];
     [self.detailsViewController didAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation];
 }
 
 - (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration {
     [self.menuViewController willAnimateSecondHalfOfRotationFromInterfaceOrientation:fromInterfaceOrientation duration:duration];
     [self.detailsViewController willAnimateSecondHalfOfRotationFromInterfaceOrientation:fromInterfaceOrientation duration:duration];
 }
 
 
 #pragma mark -
 #pragma mark Helpers
 - (CGSize) sizeRotated {    
     UIScreen *screen = [UIScreen mainScreen];
     CGRect bounds = screen.bounds;
     CGRect appFrame = screen.applicationFrame;
     CGSize size = bounds.size;
     
     float statusBarHeight = MAX((bounds.size.width - appFrame.size.width), (bounds.size.height - appFrame.size.height));
     
     if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) 
     {
         // we're going to landscape, which means we gotta swap them
         size.width = bounds.size.height;
         size.height = bounds.size.width;
     }
     
     size.height = size.height - statusBarHeight -self.tabBarController.tabBar.frame.size.height;
     return size;
 }
 
 - (void) layoutSubviews {    
     CGSize size = [self sizeRotated];
     if (isPortrait) {
         self.detailsView.frame = CGRectMake(0, 0, size.width, size.height-kMENU_CELL_HEIGHT);
         self.menuView.frame = CGRectMake(0.0, size.height-kMENU_CELL_HEIGHT, size.width, kMENU_CELL_HEIGHT);
     } else {        
         self.menuView.frame = CGRectMake(0.0, 0.0, kMENU_CELL_WIDTH, size.height);
         self.detailsView.frame = CGRectMake(kMENU_CELL_WIDTH, 0, size.width-kMENU_CELL_WIDTH, size.height);
     }
 }
 
 
 
 - (void) loadView {
     CGSize size = [self sizeRotated];
     
     UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)] autorelease];
     view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
     self.view = view;
     
     self.menuView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, kMENU_CELL_WIDTH, size.height)] autorelease];
     self.menuView.autoresizesSubviews = YES;
     self.menuView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
     self.menuView.backgroundColor = [UIColor colorWithWhite:1.000 alpha:1.000];
     self.menuView.contentMode = UIViewContentModeScaleToFill;
     self.detailsView = [[[UIView alloc] initWithFrame:CGRectMake(kMENU_CELL_WIDTH, 0, size.width-kMENU_CELL_WIDTH, size.height)] autorelease];
     self.detailsView.autoresizesSubviews = YES;
     self.detailsView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
     self.detailsView.backgroundColor = [UIColor colorWithWhite:1.000 alpha:1.000];
     self.detailsView.contentMode = UIViewContentModeScaleToFill;
     
     [self.view addSubview:self.menuView];
     [self.view addSubview:self.detailsView];
 }
 
 
 
 
 @end
 

You can customize offset of split controller by setting values for kMENU_CELL_WIDTH and kMENU_CELL_HEIGHT. Note that split view controller transforms the menu-view controller and rotates it 90″ when orientation changes to portrait so that table can be scrolled horizontally.

Building Menu Controller, that can scroll vertically and horizontally

Next, you need a UITableViewController, which can scroll horizontal and vertically. You can use transform to change the view such as:

 #import "MenuViewController.h"
 #import "SampleTableController.h"
 #import "Configuration.h"
 #import "MenuCellView.h"
 #import "MenuInfo.h"
 #import "CustomNavigationController.h"
 
 
 
 @implementation MenuViewController
 @synthesize menuItems = _menuItems;
 @synthesize masterDetailSplitController = _masterDetailSplitController;
 
 
 - (id)initWithSplit:(MasterDetailSplitController*)split {
     self = [super initWithStyle:UITableViewStylePlain];
     if (self) {        
         self.masterDetailSplitController = split;
         self.tableView.separatorColor = [UIColor clearColor];
         self.menuItems = [[[NSMutableArray alloc] initWithCapacity:10] autorelease];
     }
     return self;
 }
 
 
 -(void)refresh {
     MenuInfo *menu = nil;
     [self.menuItems removeAllObjects];
     CustomNavigationController *settingsCtr = [[[CustomNavigationController alloc] initWithStyle:UITableViewStylePlain] autorelease];
     menu = [[[MenuInfo alloc] initWithLabel:@"Settings" andOnImage:@"onSettings.png" andOffImage:@"offSettings.png" andController:settingsCtr] autorelease];
     [self.menuItems addObject:menu];
     
     NSArray *orderList = [[Configuration sharedConfiguration] getNavigationOrder];
     for (NSString *order in orderList) {
         MenuKind kind = (MenuKind) [order intValue];
         SampleTableController *ctr = [[[SampleTableController alloc] initWithStyle:UITableViewStylePlain] autorelease];
         switch (kind) {
             case ONE:
                 ctr.heading = @"One";
                 menu = [[[MenuInfo alloc] initWithLabel:@"One" andOnImage:@"onDown.png" andOffImage:@"offDown.png" andController:ctr] autorelease];
                 break;
             case TWO:
                 ctr.heading = @"Two";
                 menu = [[[MenuInfo alloc] initWithLabel:@"Two" andOnImage:@"onDownLeft.png" andOffImage:@"offDownLeft.png" andController:ctr] autorelease];
                 break;
             case THREE:
                 ctr.heading = @"Three";
                 menu = [[[MenuInfo alloc] initWithLabel:@"Three" andOnImage:@"onDownRight.png" andOffImage:@"offDownRight.png" andController:ctr] autorelease];
                 break;
             case FOUR:
                 ctr.heading = @"Four";
                 menu = [[[MenuInfo alloc] initWithLabel:@"Four" andOnImage:@"onLeft.png" andOffImage:@"offLeft.png" andController:ctr] autorelease];
                 break;
             case FIVE:
                 ctr.heading = @"Five";
                 menu = [[[MenuInfo alloc] initWithLabel:@"Five" andOnImage:@"onNext.png" andOffImage:@"offNext.png" andController:ctr] autorelease];
                 break;
             case SIX:
                 ctr.heading = @"Six";
                 menu = [[[MenuInfo alloc] initWithLabel:@"Six" andOnImage:@"onPrevious.png" andOffImage:@"offPrevious.png" andController:ctr] autorelease];
                 break;
             case SEVEN:
                 ctr.heading = @"Seven";
                 menu = [[[MenuInfo alloc] initWithLabel:@"Seven" andOnImage:@"onRight.png" andOffImage:@"offRight.png" andController:ctr] autorelease];
                 break;
             case EIGHT:
                 ctr.heading = @"Eight";
                 menu = [[[MenuInfo alloc] initWithLabel:@"Eight" andOnImage:@"onUp.png" andOffImage:@"offUp.png" andController:ctr] autorelease];
                 break;
             case NINE:
                 ctr.heading = @"Nine";
                 menu = [[[MenuInfo alloc] initWithLabel:@"Nine" andOnImage:@"onUpLeft.png" andOffImage:@"offUpLeft.png" andController:ctr] autorelease];
                 break;
             case TEN:
                 ctr.heading = @"Ten";
                 menu = [[[MenuInfo alloc] initWithLabel:@"Ten" andOnImage:@"onUpRight.png" andOffImage:@"offUpRight.png" andController:ctr] autorelease];
                 break;
         }
         [self.menuItems addObject:menu];
     }
     selected = 0;
     [self.tableView reloadData];
 }
 
 - (UIViewController *) selectedController {
     MenuInfo *info = [self.menuItems objectAtIndex:selected];
     return info.controller;
 }
 
 
 - (void)dealloc
 {
     [_masterDetailSplitController release];
     [_menuItems release];
     [super dealloc];
 }
 
 
                                
 #pragma mark - View lifecycle
 
 - (void)viewDidLoad
 {
     [super viewDidLoad];
     isPortrait = YES;
     UIView *bgView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
     bgView.transform = CGAffineTransformMakeRotation(M_PI * 0.5);
     self.tableView.backgroundView = bgView;
     self.view.backgroundColor = [UIColor blackColor];
 }
 
 - (void)viewWillAppear:(BOOL)animated
 {
     [super viewWillAppear:animated];
     self.tableView.showsVerticalScrollIndicator = NO;
     self.tableView.showsHorizontalScrollIndicator = NO;        
     self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
     self.tableView.separatorColor = [UIColor clearColor];
     
     [self refresh];
     [self.masterDetailSplitController pushToDetailController:[self selectedController]];    
 
 }
 
 
 
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
 {
     return YES;
 }
 
 -(NSArray *)allControllers {
     NSMutableArray *list = [[[NSMutableArray alloc] initWithCapacity:10] autorelease];
     for (MenuInfo *info in self.menuItems) {
         [list addObject:info.controller];
     }
     return list;
 }
 
 - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
     isPortrait = toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown;
 
     for (UIViewController *ctr in [self allControllers]) {
         [ctr willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
     }
     [self.tableView reloadData];
 }
 
 
 
 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
     for (UIViewController *ctr in [self allControllers]) {
         [ctr didRotateFromInterfaceOrientation:fromInterfaceOrientation];
     }
 }
 
 - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
     for (UIViewController *ctr in [self allControllers]) {
         [ctr willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
     }
 }
 
 - (void)willAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
     for (UIViewController *ctr in [self allControllers]) {
         [ctr willAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
     }
 }
 
 - (void)didAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
     for (UIViewController *ctr in [self allControllers]) {
         [ctr didAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation];
     }
 }
 
 - (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration {
     for (UIViewController *ctr in [self allControllers]) {
         [ctr willAnimateSecondHalfOfRotationFromInterfaceOrientation:fromInterfaceOrientation duration:duration];
     }
 }
 
 
 #pragma mark - Table view data source
 
 - (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView
 {
     return 1;
 }
 
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 {
     return [self.menuItems count];
 }
 
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
     static NSString *CellIdentifier = @"MenuCell";
     MenuCellView *cell = (MenuCellView *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     if (cell == nil) {
         cell = [[[MenuCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
     }
     MenuInfo *menu = [self.menuItems objectAtIndex:indexPath.row];
     NSString *imageName = selected == indexPath.row ? menu.onImage : menu.offImage;
     cell.imageView.image = [UIImage imageNamed:imageName];
     
     if (isPortrait) {
         cell.transform = CGAffineTransformMakeRotation(M_PI * 0.5);
     } else {
         cell.transform = CGAffineTransformIdentity;        
     }
     
     return cell;
 }
 
 /**
  * Displays the specified controller view
  */
 -(void) displayControllerView:(UIViewController*)controller {
     if (controller != nil) {
         [self.masterDetailSplitController pushToDetailController:controller];
     }
     [self.tableView reloadData];
 }
 
 
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     selected = indexPath.row;
     
     UIViewController *controller = [self selectedController];
  
     [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
     [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
 
     [self displayControllerView:controller];
 }
 
 
 
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
         return kMENU_CELL_WIDTH * 3;
     } else {
         return kMENU_CELL_WIDTH;
     }
 }
 
 
 
 @end
 

The height of cells for iPad is stretched so that you can test scrolling across the screen. The cells are also rotated 90″ when orientation is in portrait mode so that they are displayed properly on the horizontal table. Also, if you have a background image, then you will need to rotate it as well.

Customizing order of tabs

You can also allow users to change the order by storing order in a configuration, here is an example of controller that allows reordering:

 #import "CustomNavigationController.h"
 #import "MenuViewController.h"
 #import "Configuration.h"
 #import "AppDelegate.h"
 
 @implementation CustomNavigationController
 
 @synthesize controllers;
 
 static NSArray *kControllerNames;
 
 + (void) initialize {
     kControllerNames = [[NSArray arrayWithObjects:@"One", @"Two", @"Three", @"Four", @"Five", @"Six", @"Seven", @"Eight", @"Nine", @"Ten", nil] retain];    
 }
 
 
 
 - (id)initWithStyle:(UITableViewStyle)style
 {
     self = [super initWithStyle:style];
     if (self) {
     }
     return self;
 }
 
 
 
 #pragma mark - View lifecycle
 
 - (void)viewDidLoad
 {
     [super viewDidLoad];
     controllers = [[NSMutableArray alloc] initWithCapacity:10];
     [super setEditing:YES animated:YES];
     [self.tableView setEditing:YES animated:YES];
     self.navigationItem.title = @"Navigation";
     self.tableView.backgroundColor = [UIColor clearColor];
     [self.tableView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
     self.tableView.separatorColor = [UIColor blackColor];
 }
 
 
 -(void)viewWillAppear:(BOOL)animated {
     [super viewWillAppear:animated];
 
     [controllers removeAllObjects];
     NSArray *list = [[Configuration sharedConfiguration] getNavigationOrder];
     for (NSString *ctr in list) {
         [controllers addObject:[NSNumber numberWithInt:[ctr intValue]]];
     }
     
     [self.tableView reloadData];
 }
 
 
 - (void)viewDidUnload
 {
     [super viewDidUnload];
     self.controllers = nil;
 }
 
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
 {
     return YES;
 }
 
 #pragma mark - Table view data source
 
 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
     return 1;
 }
 
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 {
     return [controllers count];
 }
 
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
     static NSString *CellIdentifier = @"CustomNavigationCellView";
     
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     if (cell == nil) {
         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
     }
     
 
     NSNumber *num = [controllers objectAtIndex:indexPath.row];
     cell.textLabel.text = [kControllerNames objectAtIndex:[num intValue]];
 
     return cell;
 }
 
 
 
 #pragma mark - Table view delegate
 
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
 
 }
 
 
 
 - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
     return UITableViewCellEditingStyleNone;
 }
 
 
 - (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
     [self.tableView reloadData];    
 }
 
 
 #pragma mark Row reordering
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
     return YES;
 }
 
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
       toIndexPath:(NSIndexPath *)toIndexPath {
     NSNumber *item = [[controllers objectAtIndex:fromIndexPath.row] retain];
     [controllers removeObject:item];
     [controllers insertObject:item atIndex:toIndexPath.row];
     [item release];
 
     NSMutableArray *list = [[[NSMutableArray alloc] initWithCapacity:10] autorelease];
     for (NSNumber *num in controllers) {
         [list addObject:[num stringValue]];
     }
     [[Configuration sharedConfiguration] setNavigationOrder:list];
 
     AppDelegate *delegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
     [delegate.splitViewController.menuViewController refresh];
 }
 
 
 
 - (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
     return NO;
 }
 
 -(void)dealloc {
     [controllers release];
     [super dealloc];
 }
 @end
 

Note that we are storing the order of tabs in the configuration and saving it when user moves the navigation items.

Screen shots

iPhone Portrait

iPhone Landscape

iPad Portrait

iPad Landscape

(Note that iPad images are stretched to show that they are horizontal and vertical scrollable)

Download the code

I am not showing all code here but the full code is available from https://github.com/bhatti/SplitControllerAndCustomNavigation. I hope you find it useful.


November 16, 2011

Using self-signed certificates and resolving SSL version with iOS5 SDK

Filed under: iPhone development — admin @ 7:32 am

Using Self-signed certificates with iOS5

There have been a few changes to SSL in iOS5 SDK, which caused some snafus to our iPhone app. We have been using ASIHTTPRequest library for accessing our web services that require SSL and we use self-signed certificates in test environment. I noticed that the iPhone app wasn’t able to connect to the server after upgrading to iOS5 SDK. The original code in ASIHTTPRequest.m that accepted self-signed certificates looked like:

  NSDictionary *sslProperties = [[NSDictionary alloc] initWithObjectsAndKeys: 
                                       [NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
                                       [NSNumber numberWithBool:YES], kCFStreamSSLAllowsAnyRoot,
                                       [NSNumber numberWithBool:NO], kCFStreamSSLValidatesCertificateChain,
                                       kCFNull,kCFStreamSSLPeerName, nil];
 
   CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySSLSettings, (CFTypeRef)sslProperties);
 

However, the iOS5 SDK deprecated kCFStreamPropertySSLPeerCertificates, kCFStreamSSLAllowsExpiredCertificates, kCFStreamSSLAllowsExpiredRoots, kCFStreamSSLAllowsAnyRoot and requires using kCFStreamSSLValidatesCertificateChain to disable certificates, e.g.:

 
   CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySSLSettings, 
         [NSMutableDictionary dictionaryWithObject:(NSString *)kCFBooleanFalse forKey:(NSString *)kCFStreamSSLValidatesCertificateChain]);
   [[self readStream] setProperty:[NSDictionary dictionaryWithObjectsAndKeys: 
         (id)kCFBooleanFalse, kCFStreamSSLValidatesCertificateChain, nil] forKey:(NSString *)kCFStreamPropertySSLSettings];
 
 

Here is a complete example if you need to skip validation without using ASIHTTPRequest:

 - (void)start {
     CFStringRef bodyString = CFSTR("xml....");
     CFDataRef bodyData = CFStringCreateExternalRepresentation(kCFAllocatorDefault, bodyString, kCFStringEncodingUTF8, 0);
 
     CFHTTPMessageRef request = CFHTTPMessageCreateRequest(NULL, CFSTR("POST"), (CFURLRef) [NSURL URLWithString:@"https://optionshouse.com:443/m?"], kCFHTTPVersion1_1);
     CFHTTPMessageSetBody(request, bodyData);
 
     CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(NULL, request);
 
     self.inputStream = (NSInputStream *) readStream;
 
     [self.inputStream setProperty:[NSDictionary dictionaryWithObjectsAndKeys:(id) kCFBooleanFalse,    kCFStreamSSLValidatesCertificateChain, nil ] forKey:(NSString *) kCFStreamPropertySSLSettings];
 
     [self.inputStream setDelegate:self];
     [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
     [self.inputStream open];
 
     CFRelease(readStream);
     CFRelease(request);
 }
 
 - (void)stop {
     [self.inputStream setDelegate:nil];
     [self.inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
     [self.inputStream close];
     self.inputStream = nil;
 }
 
 - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
     switch (eventCode) {
         case NSStreamEventOpenCompleted: {
             NSLog(@"open");
         } break;
         case NSStreamEventHasBytesAvailable: {
             NSInteger   bytesRead;
             uint8_t     junk[1024];
 
             NSLog(@"has bytes");
             bytesRead = [self.inputStream read:junk maxLength:sizeof(junk)];
             if (bytesRead == 0) {
                 NSLog(@"read end");
                 [self stop];
             } else if (bytesRead < 0) {
                 NSLog(@"read error");
                 [self stop];
             } else {
                 NSString *string = [[[NSString alloc] initWithBytes:junk
                                                         length:bytesRead
                                                       encoding:NSUTF8StringEncoding] autorelease];
                 NSLog(@"Read %@", string);
             }
         } break;
         case NSStreamEventErrorOccurred: {
             NSError * error = [self.inputStream streamError];
             NSLog(@"error %@ / %zd", [error domain], (ssize_t) [error code]);
             [self stop];
         } break;
         case NSStreamEventEndEncountered: {
             NSLog(@"end");
             [self stop];
         } break;
         default: {
             assert(NO);
             [self stop];
         } break;
     }
 }
 
 

Using SSL with old F5 load balancers

Another issue I found with iOS5 was that despite using valid certificate in production environment, the SSL was still not working. Based on Apple's documentation, it turned out that the default version for SSL has been changed to TLS 1.0 and our production environment used F5 load balancer, which required SSLv3. So, I had to explicitly specify SSL version in ASIHTTPRequest.m

     const void* keys[] = { kCFStreamSSLLevel };
     // kCFStreamSocketSecurityLevelTLSv1_0SSLv3 configures max TLS 1.0, min SSLv3
     // (same as default behavior on versions before iOS 5).
     // kCFStreamSocketSecurityLevelTLSv1_0 configures to use only TLS 1.0.
     // kCFStreamSocketSecurityLevelTLSv1_1 configures to use only TLS 1.1.
     // kCFStreamSocketSecurityLevelTLSv1_2 configures to use only TLS 1.2.
     const void* values[] = { CFSTR("kCFStreamSocketSecurityLevelTLSv1_0SSLv3") };
     CFDictionaryRef sslSettingsDict = CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
     CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySSLSettings, sslSettingsDict);
     CFRelease(sslSettingsDict);
 

With these changes, our iPhone app was working as expected.

Acknowledgement

Many thanks for Apple Engineer "Quinn", who helped resolving the SSL issues.


August 17, 2011

Implementing Application Search and Custom Suggestions in Android

Filed under: Android — admin @ 2:44 pm

Being a search company, Google provides search button on most Android devices and allows a simple API to create search bar in the Android application. In addition, you can also use suggestions API to add your own suggestions either from the database or remote service. In this blog, I will demonstrate how to add the search and suggestions to your Android application.

Searchable configuration

The first thing you would need to configure is searchable.xml in res/xml directory. Here is an example file:

 <?xml version="1.0" encoding="utf-8"?>
 <searchable xmlns:android="http://schemas.android.com/apk/res/android"
     android:label="@string/app_name" android:hint="@string/search_hint"
     android:searchMode="showSearchLabelAsBadge"
     android:searchSettingsDescription="suggests symbols"
     android:queryAfterZeroResults="true"
     android:searchSuggestAuthority="com.plexobject.service.SearchSuggestionsProvider"
     android:searchSuggestSelection=" ? " android:searchSuggestIntentAction="android.intent.action.VIEW">
     >
 </searchable>
 

Search Activity

Next you would create your search activity, which would be automatically started when a user hits the hard search button or search option from menu/actionbar.

 package com.plexobject.activity;
 
 import android.app.Activity;
 import android.app.SearchManager;
 import android.content.Intent;
 import android.net.Uri;
 import android.os.Bundle;
 import android.util.Log;
 
 import com.plexobject.R;
 
 public class SearchActivity extends Activity {
     private static final String TAG = SearchActivity.class.getSimpleName();
 
     public SearchActivity() {
     }
 
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.search_activity);
         this.setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL);
 
         final Intent queryIntent = getIntent();
 
         final String queryAction = queryIntent.getAction();
         if (Intent.ACTION_SEARCH.equals(queryAction)) {
             this.doSearchQuery(queryIntent);
         } else if (Intent.ACTION_VIEW.equals(queryAction)) {
             this.doView(queryIntent);
         } else {
             Log.d(TAG, "Create intent NOT from search");
         }
 
     }
 
     @Override
     public void onNewIntent(final Intent queryIntent) {
         super.onNewIntent(queryIntent);
         final String queryAction = queryIntent.getAction();
         if (Intent.ACTION_SEARCH.equals(queryAction)) {
             this.doSearchQuery(queryIntent);
         } else if (Intent.ACTION_VIEW.equals(queryAction)) {
             this.doView(queryIntent);
         }
     }
 
     private void doSearchQuery(final Intent queryIntent) {
         String queryString = queryIntent.getDataString(); // from suggestions
         if (query == null) {
             query = intent.getStringExtra(SearchManager.QUERY); // from search-bar
         }
 
         // display results here
         bundle.putString("user_query", queryString);
         intent.setData(Uri.fromParts("", "", queryString));
 
         intent.setAction(Intent.ACTION_SEARCH);
         queryIntent.putExtras(bundle);
         startActivity(intent);
     }
 
     private void doView(final Intent queryIntent) {
         Uri uri = queryIntent.getData();
         String action = queryIntent.getAction();
         Intent intent = new Intent(action);
         intent.setData(uri);
         startActivity(intent);
         this.finish();
     }
 }
 
 

Note that you would need to implement viewing logic after the search in doSearchQuery method. Also, if your search service is being called from the search bar, you would get query string from SearchManager.QUERY parameter in the intent and if your search service is being called from the suggestion, the query string would be in getData or getDataString. You would then declare the activity in your AndroidManifest.xml such as:

         <activity android:name=".activity.SearchActivity"
             android:configChanges="orientation|keyboardHidden" android:label="@string/app_name"
             android:launchMode="singleTop">
             <intent-filter>
                 <action android:name="android.intent.action.SEARCH" />
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
             <meta-data android:name="android.app.searchable"
                 android:resource="@xml/searchable" />
         </activity>
 

For all the activities that would be using search activity would declare SearchActivity in their definition inside AndroidManifest.xml such as:

         <activity android:name=".activity.MyActivity"
             android:configChanges="orientation|keyboardHidden" android:label="@string/app_name"
             android:launchMode="singleTop">
             <intent-filter>
                 <action android:name="android.intent.action.VIEW" />
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
             <meta-data android:name="android.app.default_searchable"
                 android:value=".activity.SearchActivity" />
         </activity>
 
 

In order to support soft search, I added an option for search to the action-bar as well as menu item and then invoked following method when the search menu was clicked:

     @Override
     public boolean onSearchRequested() {
         startSearch("default-search", true, null, false);
         return true;
     }
 

This would start your search activity described above.

Suggestions Provider

I already added com.plexobject.service.SearchSuggestionsProvider in the searchable.xml file above, which provides custom implementation of suggestions.

 package com.plexobject.service;
 
 import java.util.List;
 
 import android.app.SearchManager;
 import android.content.ContentValues;
 import android.content.SearchRecentSuggestionsProvider;
 import android.database.Cursor;
 import android.database.MatrixCursor;
 import android.net.Uri;
 import android.util.Log;
 
 public class SearchSuggestionsProvider extends SearchRecentSuggestionsProvider {
     static final String TAG = SearchSuggestionsProvider.class.getSimpleName();
     public static final String AUTHORITY = SearchSuggestionsProvider.class
             .getName();
     public static final int MODE = DATABASE_MODE_QUERIES | DATABASE_MODE_2LINES;
     private static final String[] COLUMNS = {
             "_id", // must include this column
             SearchManager.SUGGEST_COLUMN_TEXT_1,
             SearchManager.SUGGEST_COLUMN_TEXT_2,
             SearchManager.SUGGEST_COLUMN_INTENT_DATA,
             SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
             SearchManager.SUGGEST_COLUMN_SHORTCUT_ID };
 
     public SearchSuggestionsProvider() {
         setupSuggestions(AUTHORITY, MODE);
     }
 
     @Override
     public Cursor query(Uri uri, String[] projection, String selection,
             String[] selectionArgs, String sortOrder) {
 
         String query = selectionArgs[0];
         if (query == null || query.length() == 0) {
             return null;
         }
 
         MatrixCursor cursor = new MatrixCursor(COLUMNS);
 
         try {
             List list = callmyservice(query);
             int n = 0;
             for (MyObj obj : list) {
                 cursor.addRow(createRow(new Integer(n), query, obj.getText1(),
                         obj.getText2()));
                 n++;
             }
         } catch (Exception e) {
             Log.e(TAG, "Failed to lookup " + query, e);
         }
         return cursor;
     }
 
     @Override
     public Uri insert(Uri uri, ContentValues values) {
         throw new UnsupportedOperationException();
     }
 
     @Override
     public int delete(Uri uri, String selection, String[] selectionArgs) {
         throw new UnsupportedOperationException();
     }
 
     @Override
     public int update(Uri uri, ContentValues values, String selection,
             String[] selectionArgs) {
         throw new UnsupportedOperationException();
     }
 
     private Object[] createRow(Integer id, String text1, String text2,
             String name) {
         return new Object[] { id, // _id
                 text1, // text1
                 text2, // text2
                 text1, "android.intent.action.SEARCH", // action
                 SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT };
     }
 
 }
 
 

You may store your suggestions in the database and may need to query the database and return database cursor. However, above provider makes a remote call and then populate Cursor using MatrixCursor from the objects that are returned from the remote service. I omitted actual remote calls that return your suggestions as it can be very application specific. As our implementation does not add anything in the database, it throws exceptions in the insert, update and delete methods. The suggestions provider can support one-line or two-line suggestions and above implementation is using two-line suggestions.
Finally, you will need to add provider and default search activity to your AndroidManifest.xml:

         <provider android:name=".service.SearchSuggestionsProvider"
             android:authorities="com.plexobject.service.SearchSuggestionsProvider"></provider>
         <meta-data android:name="android.app.default_searchable"
             android:value=".activity.SearchsActivity" />
 

As you would be calling remote service you would need following permission in your AndroidManifest.xml: :

         <uses-permission android:name="android.permission.INTERNET" />
 

If you were using database suggesgtion provider, you can add suggestions to the database as:

         SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, SearchSuggestionsProvider.AUTHORITY, SearchSuggestionsProvider.MODE);
         suggestions.saveRecentQuery(queryString, null);
 

and remote suggestions from the database as:

         SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
                 SearchSuggestionsProvider.AUTHORITY,
                 SearchSuggestionsProvider.MODE);
         suggestions.clearHistory();
 

Summary

As you can see with a few line of configuration and code you can create application wide search. You can also expose your search to default Android search and you can read Android documentation for more information.


June 21, 2011

Overview of Trading Floor Game for iOS

Filed under: iPhone development — admin @ 4:51 pm



Introduction

The Trading Floor is a social game based on auction-styled stock trading where you trade virtual stocks and options with your friends and family. Each game lasts for a day, where you join a game as a stock broker with objective of buying stocks at low-price and selling at high-price, thus making most money from the trades. Unlike a real-world stock market, each game is limited to a single exchange, which can be public or private. In addition to trading, the Trading Floor brings a lot social aspects to the game such as building private exchanges, which can be only joined by your friends and expressing like-ability for a company, which determines a Buzz for the company. Also, the members can view activities for other players in a game, view their gain/loss from the trading, view ranking of the players in terms of gain/loss and comment on their trades. At the end of a game, the top players for each game are awarded badges, which are permanently visible from their profile.

Getting Started

You can download Trading Floor from Apple AppStore.

iPad iPhone

You would see listing o active games that you can join. A game is started for each exchange in the system which can be public or privately created by the users.

Joining a game

When you click on games, you would see listing of all games such as:


From there you can select the game that you wish to join and you would be prompted to enter a nick name that you can use to join the game such as:

iPad iPhone

If an exchange is private, you would require a password to join and would need to contact the owner of the exchange. After clicking the Join button the Trading Floor would allocate a virtual cash of $10,000 to you and would create a portfolio with stocks and options for ten companies, where five of the companies are chosen from your favorite companies and five companies are randomly chosen. It takes about a minute to populate all the portfolio and then you can start trading. After joining the game you can also browse other players, view activities, portfolio, capital gains, orders and badges. There are also buttons below to quickly select between players, view rankings, floor bids, comments and lookup quotes, e.g.

iPad iPhone

Browsing Players

You can see list of players that have joined the game by touching “Browse Players” option, e.g.

iPad iPhone

When you select the player, you will see more details about the player and view activities, orders, portfolio, capital gains, badges, etc. as displayed above.

Selling Stocks/Options from Portfolio

When you select “Portfolio” option, you would see summary of your available cash and list of all stocks/options you hold such as:

iPad iPhone

When you select “Sell” link, you would be taken to the order screen such as:

iPad iPhone

You can specify your selling price and then select “Sell” button to submit the bid. It would take you to the Floor Bid, which lists all bids for buying and selling stocks/options.

Floor Bids

The Floor Bids show all companies available for buy or sell. When you post bids to sell or buy, the go to the floor bids. You can accept the bids that other players have posted for stock/option sell or buy on the Floor Bids. Note that when you post bids you specify the price for the stock but when you accept bids you don’t negotiate. If you need to change the price for your bids, you can edit your open orders. Also, when you trade stocks or options, you are only trading to the people who are in the same exchange.

iPad iPhone

When another user accepts your bid, the sale is completed and you would collect gain/loss from the trade.

Capital Gains

You can view your overall capital gains as result of trading or portfolio gain because the market price for your stocks went up from the player details, orders or portfolio screen. You can drill deep into your capital gain and find out how much profit/loss you made for each order by selecting Capital Gains option from the home screen or selecting Capital Gains row from the player details, orders or portfolio screen.

iPad iPhone

Quote Lookup

You can lookup stock/option quotes as well as latest news for the companies from Quote-Lookup menu option. You can also buy or sell stocks from the Quote-Lookup screen based on your portfolio.

iPad iPhone

In addition to buying and selling stocks/options, you can express how you feel about a company by liking/disliking/loving/hating. This in turn determines the buzz quote for that company. The more players like a company, the higher the buzz quote value that company would have. Unlike buying and trading stocks/options, which are limited to a single exchange (both public and private), the buzz quote is calculated across all exchanges. However, buzz quote is reset when the Trading Floor market is closed (11pm EST). Here is another benefit of Buzz Quote, the BOT player would buy stocks from you at the Buzz Quote price. So, if a stock becomes popular you can make more profit by selling it to the BOT.

Orders history

You can view your past orders for selling or buying stocks/options by selecting “Orders” option, which would show something like:

iPad iPhone

You can also drill into details for each order by selecting the row for the order such as:

iPad iPhone

Player Rankings

You can view your the rankings of players for each game by selecting “Rankings” option which lists players sorted by the capital gains they earned, e.g.

iPad iPhone

Comments

You can view comments on the game by selecting “Comments” option, e.g.


You can add your own comment by selecting “+” icon and typing your message, e.g.

My Badges

The top players for each game get badges at the end of the game, which are permanently visible under the “Badges” option, e.g.


When you select your badge, you will be taken to the old game that you played and can go back to your portfolio, orders and other details.

Exchanges

The exchanges are places where public companies are listed for trading. You can join exchanges created by your friends or build your exchanges. A unique game is started for each exchange, where member players trade against other member players. You can view both public and private exchanges by selecting “Exchanges” from main menu . You would see three types of exchanges: mine, public and private. Mine would list all exchanges that you have created, public would list all public exchanges and private would list top private exchanges. You can also search private exchanges.

iPad iPhone

You can create your own exchange by selecting “+” icon and typing in the exchange symbol, name and password, e.g.



You can then let your friends know about the exchange symbol and password so that they can join them.

Industries

You can view top level industries by selecting “Industries” from the main menu, e.g.

iPad iPhone

When you select an industry, it would list all companies that belong to that industry.

Companies

You can browse or search over 20,000 companies by selecting “Companies” option from the main menu, e.g.

iPad iPhone

When you select a company, it would show latest quote, news and buzz quote for that company.

Companies Around Me

Trading Floor takes advantage of your geo-location capabilities and finds companies that are located near your location, e.g.


Leader Board

The leader board shows top players with most capital gains for all the games that they have played over last month. This option uses Game Center and requires login to the Game Center. You can post your scores to the leader board by selecting the \”Post Capital Gains\” option from the main menu. Also, you can send match invites to your friends at Game Center.

In the end, I hope you find Trading Floor, a fun game for your friends and family and you may learn a few things about the stock market as well. Enjoy!.

June 1, 2011

Deploying Rails 3.0 App on Amazon EC2

Filed under: EC2 — admin @ 12:56 pm

It’s been a few years since I wrote a short HOW-TO on working with EC2 , but recently I tried to migrate the backend of Trading Floor – Facebook and iOS game I have been developing to EC2. So I am documenting the steps for setting up the EC2 for Rails 3.0.

Pre-requisites

I assume you already signed up for EC2, otherwise go to http://aws.amazon.com/ec2/ to signup. Also, you will need Java 5.0 or above, which you can download it from Oracle.

Download EC2 API Tools

First, download EC2 from http://developer.amazonwebservices.com/connect/entry.jspa?externalID=351 and uncompress it in your root directory.

Create a X.509 Certificate

Next, create a X.509 certificate from the AWS Account section. You can then download your certificate and key safely, e.g. I saved them in .ec2 directory under my home directory. Note that you will not be able to download the key again, so don’t lose it.

Environment Variables

Next, I changed my shell as:

 export EC2_HOME=~/ec2-api-tools-1.4.2.4
 export PATH=$PATH:$EC2_HOME/bin
 export EC2_KEY_DIR=~/.ec2
 export EC2_PRIVATE_KEY=$EC2_KEY_DIR/pk-HFG55OCFPZARA6YHW5JGIE6JFD7EQE72.pem
 export EC2_CERT=$EC2_KEY_DIR/cert-HFG55OCFPZARA6YHW5JGIE6JFD7EQE72.pem
 

Where EC2_PRIVATE_KEY and EC2_CERT points to the X.509 key and certificate I downloaded from the Amazon.

Create a Key-Pair

Then I created a pair of keys as:

 ec2-add-keypair plexobject
 

Create a Security Group

I then created a security group for the server

 ec2-add-group web -d 'Web Server'
 ec2-authorize web -P tcp -p 22 -s 0.0.0.0/0
 ec2-authorize web -P tcp -p 80 -s 0.0.0.0/0
 ec2-authorize web -P tcp -p 443 -s 0.0.0.0/0
 

Finding a basic Ubuntu based AMI

Previously I used S3 based AMI, but Amazon now supports EBS based AMIs that has advantage that any changes to the root survive instances of EC2. I launched EC2 instance with basic Ubuntu 11.0 Natty from http://alestic.com/ as:

 ec2-run-instances ami-06ad526f --instance-count 1 --instance-type m1.small \
 --key plexobject --group web -z us-east-1d -m
 

Where -z describes the availability zone and -m turns on monitoring.

Installing Ubuntu Packages

I then proceeded to install basic packages such as Java, Curl, Git, Build, Ruby (1.8.7) and Rails (3.0.3) based on Rails/Ubuntu docs such as:

 sudo apt-get install openjdk-6-jdk
 sudo apt-get install mercurial
 sudo apt-get install curl git-core build-essential zlib1g-dev libssl-dev libreadline5-dev
 sudo  apt-get install libcurl4-openssl-dev 
 sudo apt-get install ruby
 sudo apt-get install rubygems1.8
 sudo gem install rubygems-update
 sudo update_rubygems
 sudo gem install rails
 

I then edited /etc/profile /etc/bash.bashrc and added environment variables

 export PATH=$PATH:/var/lib/gems/1.8/bin/
 export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk/
 

Next, I installed Sqlite and Mysql:

 sudo apt-get install sqlite3 libsqlite3-dev
 sudo gem install sqlite3-ruby
 sudo apt-get install mysql-server mysql-client
 sudo apt-get install libmysql-ruby libmysqlclient-dev
 

Next, I installed Apache and Passenger:

 sudo apt-get install apache2 apache2-mpm-prefork apache2-prefork-dev
 sudo apt-get install apache2-dev libapr1-dev libaprutil1-dev
 sudo gem install passenger
 sudo /var/lib/gems/1.8/gems/passenger-3.0.7/bin/passenger-install-apache2-module*
 

I then edited /etc/apache2/apache2.conf and added:

 LoadModule passenger_module /var/lib/gems/1.8/gems/passenger-3.0.7/ext/apache2/mod_passenger.so
 PassengerRoot /var/lib/gems/1.8/gems/passenger-3.0.7
 PassengerRuby /usr/bin/ruby1.8
 

and then restarted apache

 /etc/init.d/apache2 restart
 

Creating EBS Volume for Data

Next, I created an EBS volume to store all data such as database tables and Rails application from the AWS Console and then attached it to the instance as:

 ec2-stop-instances i-73ab181d 
 ec2-attach-volume  vol-612eaa0a -i i-73ab181d -d /dev/sdf
 ec2-start-instances i-73ab181d 
 

Note that you have to create the EBS volumen in the same availability zone as your instance. I then logged into my machine using

 ssh -i plexobject.pem ubuntu@ec2-50-19-134-251.compute-1.amazonaws.com
 

and then formatted the newly built EBS volume as:

 sudo fdisk -l
 sudo mkfs -t ext4 /dev/xvdf
 

I then edited /etc/fstab and added

 /dev/xvdf       /data   auto    defaults,nobootwait,noatime     0       0
 

and then rebooted machine

 sudo reboot
 

Moving Mysql Data Directory

Mysql installs data directory on the root volume in /var/lib/mysql directory, which I wanted to move to newly created volume. So I created a directory /data/mysql so I stopped mysql:

 sudo /etc/init.d/mysql stop
 

I then copied mysql data directory such as:

 sudo cp -R -p /var/lib/mysql/mysql /data/mysql
 sudo chown -R mysql:mysql /data/mysql/
 

I didn’t copy entire mysql directory, only mysql subdirectory. Next I edited /etc/mysql/my.cnf and changed datadir to /data/mysql directory and then edited /etc/apparmor.d/usr.sbin.mysqld and changed all /var/lib/mysql to /data/mysql. Finally I restarted AppArmor profiles as:

 sudo /etc/init.d/apparmor reload
 

Then restarted mysql:

 sudo /etc/init.d/mysql restart
 

I changed my root password and created a local mysql user as

 mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('mypass');
 mysql> GRANT ALL PRIVILEGES ON *.* TO 'tfuser'@'localhost' IDENTIFIED BY 'mypass' WITH GRANT OPTION;
 mysql> GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON dbname.* TO 'tfuser'@'localhost' IDENTIFIED BY 'mypass';
 

I copied my app to /data/trading_floor and changed permissions of all files to www-data

 sudo chown -R www-data:www-data /data/trading_floor
 

Then created /etc/apache2/sites-available/tf with

 
         ServerAdmin shahbhat@gmail.com
         ServerName tf.plexobject.com
         DocumentRoot /data/trading_floor/public/
         
                  AllowOverride all
                 Options -MultiViews
                 RailsEnv production
          
 
 

Finally, I restarted apache

 /etc/init.d/apache2 restart
 

Creating Elastic IP address

I wanted a permanent IP address for the server so I created EIP using AWS Console. Then associated my instance with the new IP address:

 ec2-associate-address 50.19.248.7 -i i-73ab181d
 

It rebooted your machine with the new IP address. I then changed DNS zone and pointed tf.plexobject.com to 50.19.248.7 (this may take hours to propagate). Next, I changed my Facebook app’s configuration and iOS app’s configuration to point to tf.plexobject.com.

Creating my EBS Image

Once I was happy with the server configuration, I created EBS image for future use. First, I detached data volume and then created image as follows:

 ec2-stop-instances i-f97ca197
 ec2-detach-volume vol-3f65d954
 ec2-create-image i-f97ca197 -n tf-20110601 -d 'Trading Floor Application Server'
 

I terminated my previous instance as

 ec2-terminate-instances -i  i-f97ca197 
 

and created instance with the new image

 ec2-run-instances ami-80837ae9 --instance-count 1 --instance-type m1.small --key tf --group web -z us-east-1d -m
 

After the launch, you would have to reattach the data volume

 ec2-stop-instances i-73ab181d 
 ec2-attach-volume  vol-612eaa0a -i i-73ab181d -d /dev/sdf
 ec2-start-instances i-73ab181d 
 

Summary

Voila, I had my game application running on the cloud. In order to cut per/hour cost I reserved instances for entire year. I am not quite done with my server and am now working on application specific configuration and adding better monitoring/backup. As, we have learned from recent Amazon Cloud outage that deploying your app on the cloud is only half the work, making it performant, scalable and fault tolerant is other half which is still manual work. Finally, I plan to release the Facebook app for Trading Floor and submit iOS app in a couple of weeks, be sure to try it and send me your suggestions.

« Older PostsNewer Posts »

Powered by WordPress