Tuesday, October 27, 2015

How to prevent SQL-Injection in PHP?


Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
  1. Using PDO (for any supported database driver):
    $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
    
    $stmt->execute(array('name' => $name));
    
    foreach ($stmt as $row) {
        // do something with $row
    }
  2. Using MySQLi (for MySQL):
    $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
    $stmt->bind_param('s', $name);
    
    $stmt->execute();
    
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        // do something with $row
    }
If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (e.g. pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.

Correctly setting up the connection

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In the above example the error mode isn't strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are thrown as PDOExceptions.
What is mandatory however is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

What happens is that the SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employeesthe result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.
Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here's an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array('column' => $unsafeValue));

Can Prepared Statements Be Used For Dynamic Queries?

While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.
For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.
// Value whitelist
  // $dir can only be 'DESC' or 'ASC'
$dir = !empty($direction) ? 'DESC' : 'ASC'; 

Wednesday, October 14, 2015

Example of Client-Server Program in C (Using Sockets and TCP)

Below you’ll find an example of a very simple client-server program in C. Basically the client connects to the server, the server sends the message “Hello World”, and the client prints the received message.
Keep in mind that I am configuring the settings manually. If you want your code to be IPV4-IPV6 agnostic, IP agnostic and portable to different plataforms you can use the getaddrinfo() function, as explained in this tutorial.
Second, I am not doing error checking on most function calls. You should implement those checks if you are going to use the code for a real project.
Third, if you want more details about the functions or their arguments please check the man page of each one.
Finally, to test the code you just need to run the server on a terminal and then run the client on a different terminal (or run the server as a background process and then run the client on the same terminal).
Server Code
/****************** SERVER CODE ****************/ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main(){   int welcomeSocket, newSocket;   char buffer[1024];   struct sockaddr_in serverAddr;   struct sockaddr_storage serverStorage;   socklen_t addr_size;   /*---- Create the socket. The three arguments are: ----*/   /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */   welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);      /*---- Configure settings of the server address struct ----*/   /* Address family = Internet */   serverAddr.sin_family = AF_INET;   /* Set port number, using htons function to use proper byte order */   serverAddr.sin_port = htons(7891);   /* Set IP address to localhost */   serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");   /* Set all bits of the padding field to 0 */   memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);     /*---- Bind the address struct to the socket ----*/   bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));   /*---- Listen on the socket, with 5 max connection requests queued ----*/   if(listen(welcomeSocket,5)==0)     printf("Listening\n");   else     printf("Error\n");   /*---- Accept call creates a new socket for the incoming connection ----*/   addr_size = sizeof serverStorage;   newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size);   /*---- Send message to the socket of the incoming connection ----*/   strcpy(buffer,"Hello World\n");   send(newSocket,buffer,13,0);   return 0; }
Client Code

/****************** CLIENT CODE ****************/ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main(){   int clientSocket;   char buffer[1024];   struct sockaddr_in serverAddr;   socklen_t addr_size;   /*---- Create the socket. The three arguments are: ----*/   /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */   clientSocket = socket(PF_INET, SOCK_STREAM, 0);      /*---- Configure settings of the server address struct ----*/   /* Address family = Internet */   serverAddr.sin_family = AF_INET;   /* Set port number, using htons function to use proper byte order */   serverAddr.sin_port = htons(7891);   /* Set IP address to localhost */   serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");   /* Set all bits of the padding field to 0 */   memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);     /*---- Connect the socket to the server using the address struct ----*/   addr_size = sizeof serverAddr;   connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size);   /*---- Read the message from the server into the buffer ----*/   recv(clientSocket, buffer, 1024, 0);   /*---- Print the received message ----*/   printf("Data received: %s",buffer);     return 0; }

Wednesday, October 7, 2015

Creating a RESTful API with PHP

Creating a RESTful API with PHP

What is REST?
REST, or in the full form, Representational State Transfer has become the standard design architecture for developing web APIs. At its heart REST is a stateless client-server relationship; this means that unlike many other approaches there is no client context being stored server side. To counteract that, each request contains all the information necessary for the server to authenticate the user, and any session state data that must be sent as well.

REST takes advantage of the HTTP request methods to layer itself into the existing HTTP architecture. These operations consist of the following:
  • GET - Used for basic read requests to the server
  • PUT- Used to modify an existing object on the server
  • POST- Used to create a new object on the server
  • DELETE - Used to remove an object on the server
By creating URI endpoints that utilize these operations, a RESTful API is quickly assembled.

What is an API

In this sense an API - which stands for Application Programming Interface - allows for publicly exposed methods of an application to be accessed and manipulated outside of the program itself. A common usage of an API is when you wish to obtain data from a application (such as a cake recipe) without having to actually visit the application itself (checking GreatRecipies.com). To allow this action to take place, the application has published an API that specifically allows for foreign applications to make calls to its data and return said data to the user from inside of the external application. On the web, this is often done through the use of RESTful URIs. In our cake example the API could contain the URI of

greatrecipies.com/api/v1/recipe/cake

The above is a RESTful endpoint. If you were to send a GET request to that URI the response might be a listing of the most recent cake recipes that the application has, a PUT request could add a new recipe to the database. If instead you were to request /cake/141 you would probably receive a detailed recipe for a unique cake. These are both examples of sensible endpoints that create a predictable way of interacting with the application.


Making Our Own RESTful API

The API that we're going to construct here will consist of two classes. One Abstract class that will handle the parsing of the URI and returning the response, and one concrete class that will consist of just the endpoints for our API. By separating things like this, we get a reusable Abstract class that can become the basis of any other RESTful API and have isolated all the unique code for the application itself into a single location.

However, before we can write either of those classes there's a third part of this that must be taken care of.

Writing a .htaccess File

A .htaccess file provides directory level configuration on how a web server will handle requests to resources in the directory the .htaccess file itself lives in. Since we do not wish to have to create new PHP files for every endpoint that our API will contain (for several reasons one of which being that it creates issues with maintainability); instead we wish to have all requests that come to our API be routed to the controller which will then determine where the request intended to go, and forward it on to the code to handle that specific endpoint. With that in mind, let's create a .htacccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule api/v1/(.*)$ api/v1/api.php?request=$1 [QSA,NC,L]
</IfModule>

What Did That Do?

Let's walk through this file. The first thing that we do here is wrap everything in a check for the existence of mod_rewrite.c; if that Apache module is present, we can continue. We then turn the RewriteEngine On and prepare it to work by giving it two rules. These rules say to perform a Rewrite if the requested URI does not match an existing file or directory name.

In the next line declares the actual RewriteRule. This says that any requests to api/v1/ that is not an existing file or directory should instead be sent to api/v1/index.php. The (.*) marks a named capture, which is sent along to the MyAPI.php script as well in the request variable through the use of the $1 delimiter. At the end of that line are some flags that configure how the rewrite is performed. Firstly, [QSA] means that the named capture will be appended to the newly created URI. Second [NC] means that our URIs are not case sensitive. Finally, the [L] flag indicates that mod_rewrite should not process any additional rules if this rule matches.

Constructing the Abstract Class

With our .htaccess file in place, it is now time to create our Abstract Class. As mentioned earlier, this class will act as a wrapper for all of the custom endpoints that our API will be using. To that extent, it must be able to take in our request, grab the endpoint from the URI string, detect the HTTP method (GET, POST, PUT, DELETE) and assemble any additional data provided in the header or in the URI. Once that's done, the abstract class will pass the request information on to a method in the concrete class to actually perform the work. We then return to the abstract class which will handle forming a HTTP response back to the client.

Firstly we're going to declare our class, its properties, and constructor:
abstract class API
{
    /**
     * Property: method
     * The HTTP method this request was made in, either GET, POST, PUT or DELETE
     */
    protected $method = '';
    /**
     * Property: endpoint
     * The Model requested in the URI. eg: /files
     */
    protected $endpoint = '';
    /**
     * Property: verb
     * An optional additional descriptor about the endpoint, used for things that can
     * not be handled by the basic methods. eg: /files/process
     */
    protected $verb = '';
    /**
     * Property: args
     * Any additional URI components after the endpoint and verb have been removed, in our
     * case, an integer ID for the resource. eg: /<endpoint>/<verb>/<arg0>/<arg1>
     * or /<endpoint>/<arg0>
     */
    protected $args = Array();
    /**
     * Property: file
     * Stores the input of the PUT request
     */
     protected $file = Null;

    /**
     * Constructor: __construct
     * Allow for CORS, assemble and pre-process the data
     */
    public function __construct($request) {
        header("Access-Control-Allow-Orgin: *");
        header("Access-Control-Allow-Methods: *");
        header("Content-Type: application/json");

        $this->args = explode('/', rtrim($request, '/'));
        $this->endpoint = array_shift($this->args);
        if (array_key_exists(0, $this->args) && !is_numeric($this->args[0])) {
            $this->verb = array_shift($this->args);
        }

        $this->method = $_SERVER['REQUEST_METHOD'];
        if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
            if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
                $this->method = 'DELETE';
            } else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
                $this->method = 'PUT';
            } else {
                throw new Exception("Unexpected Header");
            }
        }

        switch($this->method) {
        case 'DELETE':
        case 'POST':
            $this->request = $this->_cleanInputs($_POST);
            break;
        case 'GET':
            $this->request = $this->_cleanInputs($_GET);
            break;
        case 'PUT':
            $this->request = $this->_cleanInputs($_GET);
            $this->file = file_get_contents("php://input");
            break;
        default:
            $this->_response('Invalid Method', 405);
            break;
        }
    }
}

By declaring this an abstract class we're prohibited by PHP from creating a concrete instance of this class. From there we can create some protected class members. A protected member can only be accessed in the class itself and children thereof, unlike a private variable which can only be accessed in the class that defined the member.

Let's Talk About CORS

One of the core premises of an API is that clients on different domains than the one the API is hosted on will be connecting to the API to send and receive data. There is an inherit security risk here, as this can allow an attacker to create an imitation page and steal data sent back and forth. Therefore this ability must be explicitly enabled on pages that wish to allow what is called Cross-Origin Resource Sharing, aka CORS. One excellent resource to learn more about CORS is the website Enable CORS - it was quite helpful to me as I was trying to understand things.

For our API we need to make sure that this is enabled, so the very first thing that is done in the __construct method is to set some custom headers. The first two are the magic; firstly we allow requests from any origin to be processed by this page, next we allow for any HTTP method to be accepted.

Once the surprisingly simple yet completely crucial step of allowing CORS requests has been completed, it becomes time for our script to understand what the client has asked of it. To do that we're going to take the $request variable which will be sent to our script from the .htaccess file (remember? it contains the original URI that the client requested), and tear it apart into the components we need. Once it's been exploded around the slash by pulling off the very first element we can grab the endpoint, if applicable the next slot in the array is the verb, and any remaining items are used as $args.

The HTTP method will describe the purpose of this request. GET requests are easy to detect, but DELETE and PUT requests are hidden inside a POST request through the use of the HTTP_X_HTTP_METHOD header. Once a method has been picked, the appropriate data source is parsed and cleaned for safety before being executed.

Completing the Abstract Class

The rest of the Abstract class comes next. Right now we're missing a function that will call the methods in the concrete class, and then one that will handle returning the response. Here's the rest of the abstract class:
abstract class API
{
    ...

    public function processAPI() {
        if (method_exists($this, $this->endpoint)) {
            return $this->_response($this->{$this->endpoint}($this->args));
        }
        return $this->_response("No Endpoint: $this->endpoint", 404);
    }

    private function _response($data, $status = 200) {
        header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
        return json_encode($data);
    }

    private function _cleanInputs($data) {
        $clean_input = Array();
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                $clean_input[$k] = $this->_cleanInputs($v);
            }
        } else {
            $clean_input = trim(strip_tags($data));
        }
        return $clean_input;
    }

    private function _requestStatus($code) {
        $status = array(  
            200 => 'OK',
            404 => 'Not Found',   
            405 => 'Method Not Allowed',
            500 => 'Internal Server Error',
        ); 
        return ($status[$code])?$status[$code]:$status[500]; 
    }
The one function worth mentioning here is the processAPI() method. This is the one publicly exposed method in the API, and its job is to determine if the concrete class implements a method for the endpoint that the client requested. If it does, then it calls that method, otherwise a 404 response is returned. The rest of the new code is simply an array map of all the possible HTTP codes and an input sanitizer.

That's all there is for the Abstract class. Now, finally time to implement a Concrete example.

Creating a Concrete API

Think back to our talk earlier about Cross-Origin Resource Sharing (CORS). Remember how it introduces a security vulnerability? We're going to work to close that as tightly as possible here by tying an Origin to a unique API Key. This means that only known and allowed external hosts will be able to connect to our API service through a pairing of their domain name and a uniquely generated API Key. For the purposes of this example I'm going to leave some of the code to verify the API Key abstracted out. Additionally our API will require a unique token in every request to verify the User.
require_once 'API.class.php';
class MyAPI extends API
{
    protected $User;

    public function __construct($request, $origin) {
        parent::__construct($request);

        // Abstracted out for example
        $APIKey = new Models\APIKey();
        $User = new Models\User();

        if (!array_key_exists('apiKey', $this->request)) {
            throw new Exception('No API Key provided');
        } else if (!$APIKey->verifyKey($this->request['apiKey'], $origin)) {
            throw new Exception('Invalid API Key');
        } else if (array_key_exists('token', $this->request) &&
             !$User->get('token', $this->request['token'])) {

            throw new Exception('Invalid User Token');
        }

        $this->User = $User;
    }

    /**
     * Example of an Endpoint
     */
     protected function example() {
        if ($this->method == 'GET') {
            return "Your name is " . $this->User->name;
        } else {
            return "Only accepts GET requests";
        }
     }
 }

Using the API

Creating the concrete class is as simple as that. For each additional endpoint you wish to have in your API, simply add new functions into the MyAPI class whose name match the endpoint. You can then use the $method and $verb and $args to create flow paths within those endpoints.

To actually implement the API we need to create the PHP file that the .htaccess file is forwarding all of the requests to. In this example I named it api.php:

// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
    $_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}

try {
    $API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
    echo $API->processAPI();
} catch (Exception $e) {
    echo json_encode(Array('error' => $e->getMessage()));
}

If you visit /api/v1/example (and have the User and Token system setup) you should see the output from that endpoint there.

That's a Wrap

That's all there is to it...which is, well, really quite a lot actually.

Thursday, October 1, 2015

Native vs Hybrid Mobile App Development


People enjoy using their smartphones because they can accomplish many things on the go such as reading e-mails, social networking, watching movies and plenty of other activities. We enjoy smartphones because they have many applications that make everyday activities easier.

If you are thinking of developing for the mobile application market, an important decision is to decide between developing a native application or a hybrid one.

It’s an age old question that refuses to go away, we thought it was time to revisit… Which is the best?

Native over Hybrid

Building native applications means using the native language of the platform, Objective-C on iOS, and Java on Android. The main advantage of native applications is their performance. Native apps are compiled into machine code (Dalvik byte code under Android), which gives the best performance you can get from the mobile phone.

Best performance includes fast and fluid animations as well as full access to phone hardware, multi touch support and the latest APIs.

Native development is far from easy. Despite the great number of resources that can be found, it may not be understandable to everyone. As code must be written specifically for each platform, the same code will have to largely be rewritten with little able to be shared. The logic may be the same, but the language, APIs and the development process is different. This process can be relatively long for complex applications.

Going Native

If you are new to mobile development and want to build performance-critical mobile apps and/or take advantage of native APIs, you would need a good resource on learning mobile native development.

Let’s take iOS for example. If you want to be a native iOS developer, firstly get yourself a Mac. You can write code anywhere, but a Mac is needed to build the code into an application as is an iOS Developer Account ($99 per year).

You can get a great intro to Objective-C by creating your own Flappy Bird game in your browser. A single online tutorial won’t quite do the trick though, Apple provides its own tutorial which is helpful for beginners and experienced developers. This tutorial introduces application design, structure and code implementation while building a ToDoList app (ToDo lists seem to be the ‘Hello, World!’ applications for mobile development).

As for Android development, I would recommend Learning Android, 2nd Edition by O’Reilly. It gives a good insight at of Android development while building a Twitter-like mobile client.

Hybrid over Native

Hybrid applications are web applications (or web pages) in the native browser, such as UIWebView in iOS and WebView in Android (not Safari or Chrome). Hybrid apps are developed using HTML, CSS and Javascript, and then wrapped in a native application using platforms like Cordova. This allows you to use any web-native framework you want, and there are plenty of these.

The application development is faster, simpler, more rapid and the application is easier to maintain. You can change platforms anytime you need, Cordova lets you build your application for more than one platform just by one adding line of code. As for the phone hardware such as the camera or Bluetooth, Cordova has a large repository of plugins you may use.

The main problem with hybrid apps is that they still depend on the native browser, which means they are not as fast as native apps.

Going Hybrid

If you decided to develop hybrid applications, then you should know that there are two main ‘competitors’ in this field. One is Cordova (and Cordova-based tools like PhoneGap) and the other is Appcelerator Titanium. They both target mobile platforms but work in very different ways.

Developing with Cordova is just like developing a webpage. You create HTML, CSS and JavaScript local files, test them in the browser and then wrap them in a native web view with Cordova (you’ll still need native SDKs and development tools for this step).

Using Titanium is a bit different, you don’t any HTML and CSS files, unless you want to create an application that uses both native and HTML-based User Interfaces. Titanium provides a very useful mobile tool set that helps you emulate (or simulate) your application on the real platform, not in the browser. When your app is run on the device, it doesn’t get wrapped into a web view, but gets interpreted by a Javascript engine (JavaScriptCore in iOS or Rhino in Android).

Appcelerator provides a good tutorial (surprisingly not a ToDo application).

There are also several other less known hybrid development options such as Xamarin, Rho, Corona and MoSync. All of these work in slightly different ways and may benefit you more depending on your current programming experience.

Conclusion

Both native and hybrid are ways to fulfill the different needs and preferences of users and developers, and none of them can be thought as a perfect solution. They have their strengths and weaknesses and it is up to you to decide which of them fits you better and which one you will use in your application.

Friday, August 21, 2015

5 Methods For Innovation You Should Try with Your Team

As winner of the 2014 Design for Experience award for Experience Design Strategy, SAP’s Design & Co-Innovation Center based at the AppHaus in Heidelberg impressed judges with a novel approach to getting clients involved in the design process.
Inspired by the Bauhaus movement, which emphasizes the power of bringing different disciplines together, the SAP AppHaus Heidelberg leverages the psychology of space to create environments where innovation and collaboration can occur spontaneously through hands-on prototyping and experimentation.

Here, Ann-Sofie Ruf, working in Marketing & Communication at SAP’s Design & Co-Innovation Center, describes an element of their experience design strategy that keeps team members sharp and open to co-creation: Method Mondays.
AppHaus project highlights
Benjamin Franklin once said: “Tell me and I forget, teach me and I may remember, involve me and I learn.”
At the SAP Design & Co-Innovation Center (DCC) we frequently organize something called “Method Mondays,” a regular one-hour meeting series in which the team members share, practice, and test different methods to support our design work.
Here are the five most-effective methods we've found thusfar.

1. Brainstorming: the Walt Disney method

We love brainstorming, and the Walt Disney Method is a simple technique for everyone to take part in. It involves role-playing with three facets of Disney’s personality.
According to Robert B. Dilts, “there were actually three different Walts: the dreamer, the realist, and the spoiler." So who are the three characters? The dreamer is a subjective and enthusiastic individual. His task is to think about the ideal way to answer the given challenge. The typical question for a dreamer is: “What can I do if everything is possible?” The realist is the pragmatic and practical thinker who wants to realize the dreamer’s ideas. His leading question is: “How can I do it?” The spoiler judges and provokes the ideas and gives positive feedback. He or she has to deal with the question “What can go wrong?”
In the role-playing exercise, you go through the different roles either on your own or in a group. Always spend about 15 minutes in each role and do several iterations. The number of iterations respective to the level of detail you want to dig into at each point.

2. Empathy Mapping

We are continuously looking for new methods. When we came across a new approach for clustering research results, we simulated a workshop situation in which the empathy map was used to cluster results based on what the interviewees had said and done—focusing on thoughts and feelings, pains and gains. We found the empathy map a great tool since it is applicable to every business and provides valuable insights about what customers and partners actually want—knowledge that is crucial for the success of your company.
AppHaus workshop
It all begins with a large white poster and a sketch of a character’s head. Divide the poster into five sections that portray what the character sees, hears, thinks, and feels as well as the challenges the character faces. Ask the players of the game to change perspectives. Fill the map with results from real research about the persona’s experiences. This helps team members identify with the persona and project themselves onto it.
During the game, all players should write down their ideas about the targeted persona’s experiences on post-its and then stick them onto the respective section of the empathy map. Once it is complete, analyze the results in a team and think of ways to apply them to your service or product. Here's a more detailed description and the online game.

3. Belbin Characters

Dr. Meredith Belbin found that when groups work together, there is always a set of nine characters: and each of them is essential for getting the group successfully from start to finish. This doesn't mean that you need nine different individuals on your team, however, because even a single person may not necessarily behave the same way all of the time. Being able to identify the different characters in a project or the workplace and being able to adapt your own behavior to the strengths and weaknesses of your team can be a great advantage.
True to the Bauhaus style, we decided that everybody could share their favorite working methods
tweet this

The nine roles can be divided into three orientations: act-oriented, subject-oriented, and communication-oriented. To run the exercise, we usually use the game “build a bridge.”
After splitting into groups of 4 to 6, we provide each group with a big stack of paper, a full half-liter bottle, and two tables or chairs as base for the bridge. The distance between the chairs or tables can vary from 50 centimeters to 1 meter. After 30 minutes of construction using paper, the bottle is placed on the bridge and supported for 20 seconds.
It is up to you if you want to distribute cards with the characteristics of each role at the beginning of the game so that the people behave according to their role, or if you want introduce the characters after the exercise. In both cases you end with a reflection on the people’s behaviors as they try to solve a problem together.

4. Remember the Future

“Remember the Future” is an easy game that helps us to better understand our customers’ definition of success and deepen their understanding of how to reach their goals. It centers on the question “What should your product do?” which is often trivially answered: “Our product should be better.” There are actually unlimited possible and plausible futures to think of and to answer the question together with your customers, give everyone a few pieces of paper and let them imagine they have been using their product continuously until some day in the future. Now ask them to write down as much as possible about what your product will have done to make them happy up to that point.
AppHaus office space
The results will change drastically depending on the wording of the question, so phrase it carefully. It’s quite unlikely that each customer will come up with the same imagined scenario. The true magic of the game is in the discussion about how your customers actually perceive their future. The next step is to compare current product development with the newfound perceptions of the future, looking for areas of possible improvement. For more details consult “Remember the Future. Understand Your Customers’ Definition of Success” in Luke Hohmann’s book: Innovation Games. Creating Breakthrough Product Through Collaborative Play.

5. A Day In the Life

We want to understand others better. As a combination of research and storytelling, the “Day in the Life” method is very valuable for gaining in-depth user insights. Designers are accustomed to observing individuals through a typical workday, recording their activities and taking notes about how they experience their environment. However, it's not always possible to conduct deep field research, so we use the “Day in the Life” method as an alternative in the workshops we hold at AppHaus. We let customers recount their typical workdays while others take notes. Paying close attention to how people spend their time allows us to gather a realistic picture of their work settings.
Next, we cluster all the information we gathered about the daily routine and sort it on a timeline similar to a customer journey. Mapping a day in the life illustrates how time is assigned to different activities and helps identify obvious or potential problems at every single step. Lastly, we brainstorm ways for improving this daily sequence. “A Day in the Life” can be repeated over several days to get a balanced perspective. Customers might also present a typical week or any relevant time span.

Why the Methods Work

We’re open to more than just creativity methods and tools—we also test storytelling techniques, warm-ups, sketching, and psychology theories for group dynamics. Anything that might support us during our project work is highly welcome.
AppHaus guest wall
Our team at the Design & Co-Innovation Center is composed of members with a rich background in different disciplines of design, creativity, and psychology. True to the Bauhaus style, we decided that everybody could share their favorite working methods or new methods they would like to test. After each test, we sit together and discuss what we liked about the method, what we would change in the next attempt, and which scenarios would call for using the method.
It is a pleasure to have the freedom to pause normal project work and spend time with the colleagues on these activities. It helps us test and validate new methods and to make mistakes and learn from them. All of us grow through these experiences, and our knowledge is enriched every time we meet.

Wednesday, April 22, 2015

HTML5 Interview Questions and Answers

1. What is the use of Canvas Element in HTML5? 
HTML5 Canvas element can be used to draw graphics images on a web page by using JavaScript.
2. Can you give an example of Canvas element how it can be used?

<canvas id=“KCCanvas” width=“500″ height=“400″>
</canvas>
<script type=“text/javascript”>
var KCCanvas=document.getElementById(“KCCanvas”);
var KCText=KCCanvas.getContext(“2d”);
KCText.fillStyle=“#82345c”;
KCText.fillRect(0,0,150,75);
</script>
This book is far better than any other learning material. It has very basic information that includes both HTML5 and CSS3 with sample code and comprehensive examples.
3. What is the purpose of HTML5 versus XHTML?
HTML5 is the next version of HTML 4.01, XHTML 1.0 and DOM Level 2 HTML. It aims to reduce the need for proprietary plug-in-based rich internet application (RIA) technologies such as Adobe Flash, Microsoft Silverlight, Apache Pivot, and Sun JavaFX. Instead of using those plugins, it enables browser to serve elements such as video and audio without any additional requirements on the client machine.

4. What is the difference between HTML and HTML5?
HTML5 is nothing more than upgraded version of HTML where in HTML5 supports the innovative features such as Video, Audio/mp3, date select function , placeholder , Canvas, 2D/3D Graphics, Local SQL Database added so that no need to do external plugin like Flash player or other library elements.
5. WHAT are some other advantages of HTML5?
a) Cleaner markup than earlier versions of HTML
b) Additional semantics of new elements like <header>, <nav>, and <time>
c) New form input types and attributes that will (and in Opera’s case, do) take the hassle out of scripting forms.

6. What is the <!DOCTYPE>? Is it mandatory to use in HTML5?
The <!DOCTYPE> is an instruction to the web browser about what version of HTML the page is written in. The <!DOCTYPE> tag does not have an end tag. It is not case sensitive.
The <!DOCTYPE> declaration must be the very first thing in HTML5 document, before the <html> tag.  As In HTML 4.01, all <! DOCTYPE > declarations require a reference to a Document Type Definition (DTD), because HTML 4.01 was based on Standard Generalized Markup Language (SGML). WHERE AS HTML5 is not based on SGML, and therefore does not require a reference to a Document Type Definition (DTD).
7. What are the New Media Elements in HTML5?
New Media Elements in HTML5 are:
TAG
DESCRIPTION
<audio>
For multimedia content, sounds, music or other audio streams
<video>
For video content, such as a movie clip or other video streams
<source>
For media resources for media elements, defined inside video or audio
elements
<embed>
For embedded content, such as a plug-in
<track>
For text tracks used in media players

8. What is the major improvement with HTML5 in reference to Flash?
Flash is not supported by major mobile devices such as iPad, iPhone and universal android applications. Those mobile devices have lack of support for installing flash plugins. HTML5 is supported by all the devices, apps and browser including Apple and Android products. Compared to Flash, HTML5 is very secured and protected. That eliminates major concerns that we have seen with Flash.
9. What is the sessionStorage Object in html5? How you can create and access that?
The HTML5 sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window. We can create and access a sessionStorage, created “name” as session
<script type=“text/javascript”>
sessionStorage.name=“KoolClasses”;
document.write(sessionStorage.name);
</script>

10. Can a <section> contain <article> elements? Can an <article> contain <section> elements? Provide usage examples.
The answer to both questions is yes; i.e., a <section> can contain <article> elements, and an <article> can contain <section>elements.
For example, a personal dashboard page might contain a <section> for social network interactions as well as a <section> for the latest news articles, the latter of which could contain several <article> elements.
Conversely, an <article> might contain a <section> at the end for reader comments.

11. Can a web page contain multiple <header> elements? What about <footer> elements?
Yes to both. In fact, both the <header> and <footer> tags are designed to serve their respective purposes in relation to whatever their parent “section” may be. So not only can the page <body> contain a header and a footer, but so can every <article> and <section> element. In fact, a <header> should be present for all of these, although a <footer> is not always necessary.

12. How do you indicate the character set being used by an HTML5 document? How does this differ from older HTML standards?
In HTML5, the encoding used can be indicated with the charset attribute of a <meta> tag inside the document’s <head> element:
<!DOCTYPE html>
<html>
<head>
...
<meta charset="UTF-8">
...
</head>
...
</html>
This is a slightly simpler syntax from older HTML standards, which did not have the charset attribute. For example, an HTML 4.01 document would use the <meta> tag as follows:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    ...
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    ...
  </head>
  ...
</html>

13. Write the code necessary to create a 300 pixel by 300 pixel <canvas>. Within it, paint a blue 100 pixel by 100 pixel square with the top-left corner of the square located 50 pixels from both the top and left edges of the canvas.
Here is one simple implementation:
<canvas id="c" width="300" height="300"></canvas>
<script>
  var canvas = document.getElementById( "c" );
  var drawing_context = canvas.getContext( "2d" );
  drawing_context.fillStyle = "blue";
  drawing_context.fillRect( 50, 50, 100, 100 );
</script>

14. Briefly describe the correct usage of the following HTML5 semantic elements: <header>, <article>, <section>, <footer>.
The <header> element is used to contain introductory and navigational information about a section of the page. This can include the section heading, the author’s name, time and date of publication, table of contents, or other navigational information.
The <article> element is meant to house a self-contained composition that can logically be independently recreated outside of the page without losing its meaning. Individual blog posts or news stories are good examples.
The <section> element is a flexible container for holding content that shares a common informational theme or purpose.
The <footer> element is used to hold information that should appear at the end of a section of content and contain additional information about the section. Author’s name, copyright information, and related links are typical examples of such content.

15. Describe the relationship between the <header> and <h1> tags in HTML5.
In previous specifications of HTML, only one <h1> element was typically present on a page, used for the heading of the entire page. HTML5 specifies that <h1> represents the top-level heading of a “section”, whether that be the page <body>, or an <article> or <section> element. In fact, every <header> element should at least contain an <h1> element. If there is no natural heading for the section, it is a good indication it should not use an <article> or <section> tag.

16. What are some of the key new features in HTML5?
Key new features of HTML5 include:
Improved support for embedding graphics, audio, and video content via the new <canvas>, <audio>, and <video> tags.
Extensions to the JavaScript API such as geolocation and drag-and-drop as well for storage and caching.
Introduction of “web workers”.
Several new semantic tags were also added to complement the structural logic of modern web applications. These include the <main>, <nav>, <article>, <section>, <header>, <footer>, and <aside> tags.
New form controls, such as <calendar>, <date>, <time>, <email>, <url>, and <search>.

17. What were some of the key goals and motivations for the HTML5 specification?
HTML5 was designed to replace both HTML 4, XHTML, and the HTML DOM Level 2.
Major goals of the HTML specification were to:
Deliver rich content (graphics, movies, etc.) without the need for additional plugins (e.g., Flash).
Provide better semantic support for web page structure through the introduction of new structural element tags.
Provide a stricter parsing standard to simplify error handling, ensure more consistent cross-browser behavior, and simplify backward compatibility with documents written to older standards.
Provide better cross-platform support (i.e., to work well whether running on a PC, Tablet, or Smartphone).

18. What is the HTML5 email form field input?
In HTML5, there is a new type that is specifically for email inputs on a form. The markup <input type=”email”> basically tells the browser that it should not allow the form to be submitted if the user has not entered what the browser determines to be a correctly formatted email address.
Remember that the browser must do the validation – HTML5 is just a standard that means nothing until the browser actually implements it. Also, this doesn’t mean that the browser is supposed to actually check to see if the email address is a real email address (that would be very difficult to do), but only that it’s format is valid (like it contains an “@” sign, etc.).

Empty email form field inputs

Just like any other input type, a user can submit a form with an empty email input field – unless of course there is a “required” attribute for the input field.

The email input and “multiple” attribute


The HTML5 email input type can also have what’s known as the multiple attribute, which, when used inside an input tag with type “email”, basically means that the value of the field can be a list of comma -separated, valid email addresses. This would just look something like this: <input type=”email” multiple>. But, this functionality doesn’t mean that the user has to put in a comma separated list manually. The browser could possibly offer some suggestions for which emails to add to the input field – through a contacts list stored somewhere – the point is that it’s up to the browser to display other options to the user in this scenario.