Monthly Archives: October 2010

Sencha, My First iphone application

Here we are, Iphone application development  is being more and more easier for web developers, all you have to know is Javascript, html and Css .. 

Sencha is a HTML5 Mobile web application framework .. in other words it simplify creation of mobile application using HTML5 features.

In this article i will try to list all the tweets where the keyword  “hbensalem” exists, i’m using Twitter Api and search.twitter.com.

Setting the project

First of all you’ll need to download sencha-touch from Sencha website.

Then create a html file with this content :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Sencha</title>
        <!-- Sencha Touch CSS -->
        <link rel="stylesheet" href="./sencha-touch/resources/css/sencha-touch.css" type="text/css">
        <!-- Sencha Touch JS -->
        <script type="text/javascript" src="./sencha-touch/ext-touch-debug.js"></script>
        <!-- Application JS -->
        <script type="text/javascript" src="index.js"></script>
        <style>
            .tweet {
                border-bottom: 1px solid #EEEEEE;
                margin: 0;
                overflow: hidden;
                padding: 15px 5px;
                background-color: grey
            }

            .avatar {
                float: left;
                height: 50px;
                overflow: hidden;
                width: 50px;
            }
            .tweet-content {
                font-size: 16px;
                line-height: 17px;
                margin-bottom: 2px;
                margin-left: 58px;
            }
        </style>
    </head>
    <body></body>
</html>

We need to pay attention to :

  • sencha-touch.css
  • ext-touch-debug.js

Building the application “script.js”

Ext.setup({
    tabletStartupScreen: 'tablet_startup.png',
    phoneStartupScreen: 'phone_startup.png',
    icon: 'icon.png',
    glossOnIcon : false,
    onReady: function() {

        var timeline = new Ext.Component({
            title: 'Timeline for hbensalem',
            cls: 'timeline',
            scroll: 'vertical',
            tpl: [
                '<tpl for=".">',
                    '<div class="tweet">',
                            '<div class="avatar"><img src="{profile_image_url}" /></div>',
                            '<div class="tweet-content">',
                                '<h2>{from_user}</h2>',
                                '<p>{text}</p>',
                            '</div>',
                    '</div>',
                '</tpl>'
            ]
        });

        var panel = new Ext.TabPanel({
            fullscreen: true,
            items: [timeline]
        });

        var reader =  Ext.util.JSONP.request({
                url: 'http://search.twitter.com/search.json',
                callbackKey: 'callback',
                params: {
                    q: 'hbensalem'
                },
                callback: function(data) {
                    data = data.results;
                    timeline.update(data);
                }
            });
    }
});

Some explanations :

Timeline is the component who deals with data from JSON request, the tpl section is for Template, data content is parsed and every token is replaced by the good value.

Panel : is the main container.

Reader : is the JSON reader, we told him where to search and we passed the query. Callback function is called when the loading of request is finished.

And this is the result :

Source and further reading :
http://dev.sencha.com/deploy/touch/getting-started.html

Raphael js, Drawing a funny monster

When i was young i discovered that it’s possible to draw using Qbasic language .. So i passed all my time exploring circles, lines sprites and etc. Now the web is populated by great tools for simple and complex graphics, Rapahel is one of them.

Raphael is a javascript library for vectorial graphics, but it can also be used to make nice animations and it is using SVG.

In this tutorial i will try to explain how to draw a funny monster face (which looks like Domo) view Demo , or Download source files.

So first of all you’ll need to download raphael js library and create a simple html file :

Setting up

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Domo like</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="raphael.js"></script>
        <script>
            window.onload = function(){
                var paper = Raphael("canvas", 640, 480);
            }

        </script>
    </head>
    <body>
        <div id="canvas"></div>
    </body>
</html>

The important thing is “paper” value which is the raphale object :

 var paper = Raphael("canvas", 640, 480);

1 . drawing the head and the mouth :

var head = paper.rect(180, 50, 320, 340, 15);
head.attr({
    'stroke-width' : 6,
    'fill' : '15-#AA0000-#511'
});
mouth = paper.rect(200, 150, 240, 200, 5);

mouth.attr({
    'stroke-width' : 10,
    'fill' : '#000'
})

This code will give us :

2. Adding eyes and tongue

var eyes = paper.set();

eyes.push(
    paper.rect(200, 100, 15, 10, 5),
    paper.rect(410, 100, 35, 20, 5)
);

eyes.attr({
    'stroke-width' : 10,
    'fill' : '#000'
});
tongue = paper.ellipse(350, 310, 60, 20);
tongue.attr({
    'stroke-width' : 3,
    'fill' : '#FF0000'
});

Result :

3. Adding teeth

Okey our little monster needs some teeth we’ll use loops to draw em.

teeth = paper.set();

for(i=200; i<= 420; i+=20){
    teeth.push(paper.rect(i, 150, 20, 70 , 5));
    teeth.push(paper.rect(i, 310, 20, 40, 5));
}

teeth.attr({
    'fill' : '#FFFFFF'
})

Final Result :

Et voilà ! Hope you like the result ! ^^

View Demo Download
 
   

CouchDb, Creating views

The first couchDb tutorial that i’ve wrote was about simple operations like creating, updating or deleting documents, in this post i will explain how to create views, and how to call them ;

Creating views

The simplest way to create views is to use “Futon” (the phpmyadmin like for couchDb) accessible via :

http://localhost:5984/_utils/

And if everything is ok we should have something like this :

Then choose database where to create View, then on the select box in front of ‘View‘ select ‘Temporary view‘ :

When you click run button :

the last time we have created database called ‘contacts‘ with documents having this structure :

{
   "_id": "johnsmith",
   "_rev": "3-94052866ba060f57508fde265a243b47",
   "firstName": "John",
   "lastName": "Smith",
   "email": [
       "johnsmith@example.com"
   ],
   "phone": "(555) 555-5555"
}

The default function to show database content is :

function(doc) {
  emit(null, doc);
}

And when you hit run it will display all entries from the database “contact“, know let’s try to get contacts with a specific criteria, for example : “all contacts having a phone number” :

function(doc) {
  if(doc.phone){
	emit(doc._id, doc.phone);
  }
}

As result :

Saving the temporary view

Okey now that we are satisfied of the result let’s save the temporary view a permanent one :

  1. Click “Save As” button
  2. Set a design Name
  3. Set a view Name

That’s all ! our view will be accessible from the “View” Select Box :

Getting view result with curl

To query the server will use curl :

curl -X GET http://127.0.0.1:5984/contacts/_design/contacts/_view/phones

Result :

{"total_rows":1,"offset":0,"rows":[
  {"id":"johnsmith","key":"johnsmith","value":"(555) 555-5555"}
]}

Some explanations about params passed to curl :
– First argument “contact” is database name
– Second argument “_design” with value “contacts” is the design name that we have set when we saved the view
– Third argument “_view” with value “phone” is simply the view name

We can also pass other params at the end to tell the server how many entries to return, or to order them :

curl -X GET http://127.0.0.1:5984/contacts/_design/contacts/_view/phones?limit=11&descending=true

Hope this was helpful to understand how to create simple views with couchDb.

Drupal 6, Theming Search Box

In this tutorial i will try to explain how to modifiy default search box provided by Drupal module “Search“, this one of many other methods and i think it’s the simplest way.

First of all you’ll need to enable it from admin>build>modules interface then associate it to a region.

Creating theme file

First of all create a file on you theme directory called : ‘search-block-form.tpl.php‘ which is a copy of template file of search box module, the problem whith drupal generated forms are the hidden fields and input file names so we need to pay attention to them :

<?php
// $Id: search-block-form.tpl.php,v 1.1 2007/10/31 18:06:38 dries Exp $
?>
<div class="container-inline">
    <?php
    //Default form call.
    //print $search_form;
    ?>
    <label>
<span>
<!-- input type text with correct name search_block_form -->
  <input name="search_block_form" type="text" class="keywords" id="edit-search-theme-form-l" maxlength="50" value="Search..." />
 </span>
<!-- action name "op" -->
<input name="op" type="image" src="<?= url(path_to_theme() . '/images/search.gif', array('absolute' => true)) ?>" class="button" />
    </label>

    <?php
    //hidden values !important
    print $search["hidden"];
    ?>
</div>

That’s all ! there’s an interesting forum topic where you can find other methods like preprocess functions etc. :
http://drupal.org/node/224183

Sqlite, emulating on duplicate update functionnality

On my last article i’ve spoken about what a common MySQL developer needs to know to use Sqlite. In this article we’ll try to simulate a missing feature which is updating if key exists “on duplicate update on MySQL” using PHP Exceptions.


            try {
                // init database cnx.
                $db = new PDO('sqlite:' . $databasePath);
                $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                $sql = "INSERT INTO table
                        (id, content)
                        VALUES
                        (:id, :content)";

                // Prepare statement
                $stmt = $db->prepare($sql);

                // bind the params
                $stmt->bindParam(':id', $id);
                $stmt->bindParam(':content', $content);

                //
                $stmt->execute();
            // Exception code for constraint violation is 23000
            // That's why we catch this error code and do update :
            } catch (Exception $e) {
                if ($e->getCode() == 23000) {
                    try {
                        $sql = "UPDATE
                            table
                            SET
                            content = :content
                            WHERE
                            id = :id";
                        $stmt = $db->prepare($sql);
                        $stmt->bindParam(':content', $content);
                        $stmt->bindParam(':id', $id);
                        $stmt->execute();
                    } catch (Exception $e) {
                        echo $e->getMessage();
                    }
                }
            }