Saturday, November 5, 2011

MeeGo 1.2 for Netbooks in Virtualbox ( Windows and Ubuntu )





These are the steps for installing MeeGo 1.2 for Netbooks in Virtualbox. These steps were tested on Ubuntu 10.04 and Windows 7. Steps are the same on both OSs, and screenshots were taken from Ubuntu 10.04.

First, you should download the latest version of MeeGo from: https://meego.com/downloads
and install Virtualbox, whether from : https://www.virtualbox.org/wiki/Downloads or from Ubuntu Software Center.

Second, covert the extension from the downloaded MeeGo image from (*.img) to (*iso).

Then, open Virtualbox and create a new machine.

Make sure you indicate the machine as a Fedora Linux version, with Ram 512MB or higher (MeeGo Wiki says 1GB) and at least 5GB of disk space. Also make sure you enable the options of "Enable PAE/NX" and "Enable 3D Acceleration".

Here are screenshots of this step:













Now let's start our new virtual machine. From the menu appearing, chose "Installation Only", wait until some operations end, then the UI wizard will appear. The steps of installation are almost straight forward. And after installation, A message will say that you should not remove the USB stick (or the virtual CD ROM in our case) until you press the "Close" button. So press "Close" and then un-mount the CD ROM from the Virtualbox menu: Machine -> CD/DVD Devices -> Unmount. Then reboot the machine from: Machine -> Reset.










After restarting, the wizard will continue with some basic settings. When going through these steps, they went fine on Windows 7, but on Ubuntu 10.04 I had to reset the machine a couple of times to finish the settings steps and move to the next step. BTW: The blue splash screen at the beginning of these steps may stay for a few seconds.








Now we come to a little dirty part. At this moment, the machine may start normally without any effort. But some other times you need to do the following steps. These steps are the best I could write after searching and trying for hours:

First wait until the first blue screen appears and press "ESC" on the keyboard. This will view a list with one option to boot MeeGo. Press "Tab" key to edit the command of launching MeeGo, remove the last part of "quite vga=current" and replace it with "init 3" then hit the "Enter" key.

Some commands will appear quickly on the screen, wait until you see the login screen.





Do a login with the username/password you have set in the previous steps. Then write:
sudo su
[enter the password again]
chmod +s /usr/bin/Xorg
uxlaunch

Now you should wait for a few seconds to see the MeeGo home screen appearing.




If you want to shutdown the machine in a legal way, you will notice that there is no "Shutdown" button. But you can still choose "Machine -> ACPI Shutdown" from the virtual machine menubar.




There is another final note: Although I had to write the terminal commands whenever I launch the machine on Windows 7, I found the machine booting normally on Ubuntu 10.04 once I hit the "Start" button.
Update: It booted fine on both OSs. The problem was because I did not make a legal shutdown, so the session was not saved.

Wednesday, October 12, 2011

Read/Edit Phone Contacts Using Qt

Here I'm posting a code snippet I used to modify my contacts on both SIM card and phone memory. What this code does is that it loops over all available memories on phone and edits each number according to a criteria I set. To simplify the code, I removed the business parts and posted only the parts related to Qt Framework and the loop over the contacts.

 The skeleton of the process is as follows:

  1. Get all available manager on device. In my case they where "symbian" (i.e: phone memory) and "symbiansim" (i.e: SIM card)
  2. Loop over the list of managers.
  3. For each manager, get the ids of available contacts.
  4. For each contact id, get all the available phone numbers.
  5. For each phone number, decide if it needs to be changed (the business part), or just output the number or use it however you want.
  6. A couple of flags are set to save any changes in a number/contact


[*.pro]
symbian:TARGET.CAPABILITY += ReadUserData WriteUserData

CONFIG += mobility
MOBILITY += contacts


[*.h]
#include <QContactManager>
#include <QContact>
#include <QContactPhoneNumber>

QTM_USE_NAMESPACE


[*.cpp]
//find all the available mamagers on device
QStringList managers = QContactManager::availableManagers();

//loop on all the available managers
for(int m=0; m<managers.length(); m++)
{
    //initialize a new contact manager with one of the ids in "mamagers" list
    QContactManager cManager(managers.at(m));

    QList<QContactLocalId> idsList = cManager.contactIds();
    
    //loop on all the available contacts
    for(int i=0; i<idsList.length(); i++)
    {
        QContact contact = cManager.contact(idsList.at(i));
        bool contactEdited = false;
        
        //get all contact details the can be considered a phone numbers (mobile, home .. etc)
        QList<QContactPhoneNumber> phoneNumbers = contact.details<QContactPhoneNumber>();

        //iterate on the phone numbers of the contact
        for(int idx=0; idx<phoneNumbers.length(); idx++)
        {
            QContactPhoneNumber phone = phoneNumbers.at(idx);
            QString number = phone.value(QContactPhoneNumber::FieldNumber);
            bool numberEdited = false;

            // ################### Editing Zone #################
            
            // here you put any operations related to editing the number
            // and set the "edited" flag to true if you changed the number
            
            // ##################################################

            //if the number is edited, save it in the "contact" object
            if(numberEdited)
            {
                phone.setNumber(number);
                contact.saveDetail(&phone);
                
                //raise the contactEdited flag to save the contact later
                contactEdited = true;
            }
        } // end of numbers loop

        if(contactEdited)
        {
            //save the edited contact
            cManager.saveContact(&contact);
        }
    } // end of contacts loop
} // end of managers loop


Here are some notes about this code:
- If you need to interact with one manager, just pass one item to the "managers" list, or simply remove the managers loop.and set the manager manually.
QContactManager cManager("symbiansim");
- It is a good practice to not freeze the application with all these nested loops. So if you are sure that no other event can cause a problem while executing these operations, you can insert this line inside each loop.
qApp->processEvents();
- Self-signing is enough to get this code running on a Symbian device.




Wednesday, September 21, 2011

Book Review: Play Framework Cookbook

Ok, after some reading in parts of the book and touring some other parts (remember my previous entry?), here are my notes about this book. But first I have to mention the beckground I come from:
- Basically I come from a front-end development environment.
- C++ is my main interest, then comes Java.
- I've just started to learn Play framework and found it interesting to go deeper into.

Now let's get to the review:



1- From the book intro, the author indicated that proceeding with a Play tutorial plus some web developer skills—HTML and JavaScript. So I thought it would not be that hard to get started, and it wasn't at the very beginning, then it accelerated very quickly that I had to skip more parts chapter after chapter. Maybe I needed more that some knowledge or skills, I needed the "web culture".

2- I liked how the examples were introduced along with test cases. Examples on the internet may settle with some code and leave the testing to the user, so the book made it more professional.

3- Some code parts seemed to be eligible to be put inside real projects, not just dummy examples. They were well designed.

4- Most of the times I notice how the author tends to to stop at some part of the explanation or move faster. So I sometimes had the feeling that parts of the book were more like highlights.

5- This book can be useful as a reference while coding or preparing materials for a course/project. But not a solid tutorial to take (remember my background, it is still useful as I mentioned).


Thursday, September 8, 2011

To Read: Play Framework Cookbook


Today I had the opportunity to receive a softcopy of a new book: Play Framework Cookbook , by Alexander Reelsen, Packt Publishing.

And since Play Framework has not so many books to find, It was a good opportunity I cannot miss. What is attractive in this book? From the first look, it does not require deep experience with Play Framework. You just need to follow a couple of examples ( link1link2 ) on the internet to be ready for this book which already explains some basics in the first chapter and promises to mention some basic throughout the book.

Now let me start reading and give my review. If you are in a hurry to see the book from inside, here is a link to a sample chapter: (download)

Stay tuned ...

Friday, July 8, 2011

Play Framework Tutorial



A couple of weeks ago, I attended a introductory one-hour session about Play Framework. And it was interesting as it was my first time to experience anything related to the web. So I decided to give it a try. And guess what, I could navigate inside the framework and make my first simple service within two hours (remember: zero web experience and not so much Java experience), And thought I could write about it. Why? Because I wanted a tutorial that gives me the basics without going deeps, then gives me the keywords and options to go deeper in any part, and did not find what I want, so I did it my way.

Note: Even for the front-end developer, knowing the basics of web applications. Why? Imagine making an application that depends on a web service, say, BBC RRS feed). To test the application you have to make some scenarios like: service down, content with special characters, etc. So you have to create a "development environment" different from the "production environment" (which usually cannot be halted for some front-end testing).

In this tutorial I will make a service that takes a city name and returns a four-day forecast from Google weather API.

Installation:

This is straight forward. Just go to http://www.playframework.org/ and download the latest version. (for Ubunutu, I had to go to http://download.playframework.org/miscellaneous/ to download the debian package)

Starting a new Project:

[I'm using Play 1.0.2.1 on Ubuntu 10.10]
1- Open Terminal
2- Assuming we want to make a project called "MyWeatherService", write:
play new MyWeatherService

3- It will ask for application name (the previous name was the project name, so write:
MyWeatherService

4- Now the project is created and can be accessed by typing:
play run MyWeatherService



5- Now the service is running. Open your web browser and type
http://localhost:9000/
(9000 is the default port, let's see this later)

6- To stop the service, just go back to the terminal and press: Ctrl+C


Editing project from NetBeans:

For easier development, the Play! project can be opened in different IDE's like NetBeans and Eclipse. So I'm going to use NetBeans.

1- From terminal type:
play netbeansify MyWeatherService
(there is also "eclipsify")

2- From NetBeans: File -> Open Project

3- In my case, the project is located in
/home/adly/MyWeatherService


Project's Basic Structure:

Let's take an overview on the must-know basics before proceeding, The Play! project follows the MVC stucture, so We are dealing with:
Model: where database queries, mathematical computations .. etc happen
View: the template used for rendering the data from the model. The view can be HTML/XML.
Controller: maps model data to fit in the view.

and there is and important file: conf -> routes. This file defines how the user can talk to the web service, and which controller handles each route.


Creating our web service:

1- Lets create the model first. Right click on app -> models and choose new -> Java Class .And let's name it WeatherModel.



2- Make this class extend Model.

3- Create a method to be interfaced by the controller. I made a getAllWeatherStates() method which returns an array list of the weather states representing today and some days to come. I'm not going to use databases ad relations and all these stuff, I want to keep it simple as a beginning. So all I'm going to do is call a Google weather API, parse data, create WeatherState objects, put them in an ArrayList and return this ArrayList to the caller.

First, I created a simple class and called it WeatherState that has nothing but strings of data/state/max/min.

[WeatherState.java]
package models;

public class WeatherState {
    
    public String date;
    public String state;
    public String max;
    public String min;
    
    public WeatherState(String date, String state, String max, String min){
        this.date = date;
        this.state = state;
        this.max = max;
        this.min = min;
    }
}

Now let's see the code of the our model

[WeatherModel.java]
/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package models;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import play.db.jpa.Model;

/**
 *
 * @author adly
 */
public class WeatherModel extends Model{
    
    /**
     * A controller should call this method
     */
    public static ArrayList getAllWeatherStates(String cityName){
        try {
            return getCityStates(cityName);
        } catch (IOException ex) {
            ArrayList weatherStates = new ArrayList();
            return weatherStates;
        }
    } 
    
    
    /**
     * A private method that calls a Google weather API, parses content,
     * and returns an ArrayList on WeatherState objects
     */
    private static ArrayList getCityStates(String cityName) throws IOException {
        
        ArrayList weatherStates = new ArrayList();
        try{
            
            /**
             * Download XML data
             */
            
            URL connectURL = new URL("http://www.google.com/ig/api?weather="+cityName);
            HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection(); 
            
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false); 
            conn.setRequestMethod("GET"); 
            // connect and flush the request out
            conn.connect();

            InputStream inStream = conn.getInputStream();
            
            /**
             * Parse data into an ArrayList
             */
            
            try{
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document dom = builder.parse(inStream);
                Element root = dom.getDocumentElement();
                NodeList items = root.getElementsByTagName("forecast_conditions");
  
                for(int i=0; i<items.getLength(); i++){
                    String day = "";
                    String low = "";
                    String high = "";
                    String condition = "";
                    
                    Node item = items.item(i);
                    NodeList properties = item.getChildNodes();
                    for(int j=0; j<properties.getLength(); j++){
                        Node property = properties.item(j);
                        String name = property.getNodeName();
                        if(name.equalsIgnoreCase("day_of_week")){
                            Element child = (Element) property;
                            day = child.getAttribute("data");
                        }else if(name.equalsIgnoreCase("low")){
                            Element child = (Element) property;
                            low = child.getAttribute("data");
                        }else if(name.equalsIgnoreCase("high")){
                            Element child = (Element) property;
                            high = child.getAttribute("data");
                        }else if(name.equalsIgnoreCase("condition")){
                            Element child = (Element) property;
                            condition = child.getAttribute("data");
                        }
                    }
                    WeatherState weather = new WeatherState(day, condition, high, low);
                    weatherStates.add(weather);
                }
            }
            catch(Exception e)
            {
                //parsing exception
            }
        }
        catch(Exception e)
        {
            //downloading exception
        }

        return weatherStates;
    } //end of 'getCityStates' method
    
}

Note that the code of getCityStates method is pure Java, I actually used it before in an android project.

So this is all we had to make for or model. And the big part of "coding" is done.


4- Now let's make the controller. It is the one containing a method the will be called when a user requests with a certain URL (to see that later).

5- Right click on app -> controllers and choose new -> Java class. And let's name it Weather.



6- Make it extend Controller. And let's make a requestWeather method that will call the model and then the appropriate view by a method called render().

7- The code is as simple as this:

[Weather.java]
/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.util.ArrayList;
import models.WeatherModel;
import play.mvc.Controller;

/**
 *
 * @author adly
 */
public class Weather extends Controller{
    
    /**
     * Called when a user requests weather with a certail URL containing
     * city name
     */
    public static void requestWeather(String cityName) {
        ArrayList weatherStates = WeatherModel.getAllWeatherStates(cityName);
        render(weatherStates);
    }
}


8- Now let's make the view for this controller. I want to make an XML file that appears to the user when the weather of a certain city is requested. And views an error message if city name is not valid.

9- Right click on app/views -> new -> other and chose a new folder with name: Weather (the same name of the controller)





10- Right click on Weather folder and choose new -> XML Document and name it requestWeather (the same name of the controller requesWeather() method)





11- The content of returned XML file will be multiple blocks of "forecast" tags, so I made a loop on the weatherStated list passed to this XML view by the render() method in the controller. An if-else condition is added to view an error message is case of an invalid city name.

[requestWeather.xml]
#{set title:'Weather Forecast' /}

#{ifnot weatherStates}
<forecasts>
<error>city not available</error>    
</forecasts>
#{/ifnot}

#{else}
<forecasts>
    #{list items:weatherStates, as:'weather'}
    <forecast>
        <date>${weather.date}</date>
        <state>${weather.state}</state>
        <max>${weather.max}</max>
        <min>${weather.min}</min>
     </forecast>
    #{/list}
</forecasts>
#{/else}

12- Now we are almost done. The only missing thing is defining a URL the user can use to access this service. So let's go to the conf -> routes file and add the following line

[routes]
# Request Weather Forecast
GET     /forecast/{cityName}                    Weather.requestWeather(format:'xml')
This line defines the format concatenated to the service IP & port to access the weather service. I chose to add the "forecast" word first, then accept the "cityName" variable from user. When a URL with this format is called, The requestWeather method in the Weather class (the controller) will be called and will render the output as xml.

13- Now the service is ready to run. Just save your work and make sure the service is running (from terminal window) and call the following two URLs to see the results:
http://localhost:9000/forecast/cairo
<forecasts>
     <forecast>
        <date>Fri</date>
        <state>Scattered Thunderstorms</state>
        <max>91</max>
        <min>74</min>
     </forecast>
     <forecast>
        <date>Sat</date>
        <state>Scattered Thunderstorms</state>
        <max>93</max>
        <min>74</min>
     </forecast>
     <forecast>
        <date>Sun</date>
        <state>Scattered Thunderstorms</state>
        <max>93</max>
        <min>74</min>
     </forecast>
     <forecast>
        <date>Mon</date>
        <state>Scattered Thunderstorms</state>
        <max>94</max>
        <min>75</min>
     </forecast>
</forecasts>


http://localhost:9000/forecast/cair
<forecasts>
    <error>city not available</error>
</forecasts>

Note 1: A good thing about Play! Framework is that you do not need to compile anything after editing your code. Just save the edited file and refresh the requested page.

Note 2: Although your service is running fine, it is still not ready for production for many reasons. For example, try the following URL:
http://localhost:9000/@kill
This kills the service. And it happens because you are running in something called "dev mode" not "prod mode". Please check conf -> application.conf file for more details and options

[application.conf]
# Application mode
# ~~~~~
# Set to dev to enable instant reloading and other development help.
# Otherwise set to prod.
application.mode=dev


Done! This was a quick tutorial to get hands into the framework. You can enjoy the documentation on their website, it is a very useful one.

Download this example from here.


Enjoy :)

Wednesday, July 6, 2011

Developing My First Android Game

So, this entry is less about explaining and more about showing references. To come up with this game, I was studying and playing for a while with Qt/Python/Android code because I was not intending to come up with a real product. But anyways, it appeared that moving between languages is not that hard once you got used to it.

This is the very basic beginning of the game where I was learning the basics of game logic, the complete game should better go to the market that be posted as a project (sorry about that). But I guess the the coding is not much from this point. It is all about a better architecture of game objects/logic and graphics design (activity lifecycle, levels, special items, licensed graphics ... etc).

And do not worry about me posting the names and graphics, these are dummy names and graphics for learning :D

Here is a look at the game:




Download Project: here
(if you have problems with compilation, check the "target=android-10" line in "default.properties" file)

This is what I read, not all Android, but still logically helpful:
1- Tile-Based Games
2- Invent Your Own Computer Games with Python
3- Android Tutorial: How to make a basic game loop and FPS counter
4- Against the Grain: The Android Game Loop (the most help I could find)

Finally, this a great daily journal of an Android developer upgrading his game (Light Racer). I've read it a couple of months ago and had a great impact on how I think:
- The Light Racer 3D Development Journal


I hope I can find the time to complete the game and post it on the market.

Tuesday, July 5, 2011

Nokia and Operating Systems [presentation]

This is a presentation I prepared for a small session about current Nokia devices and operating systems on them. The presentation depended on talking plus viewing, but I guess it can still be somehow useful alone.

Thanks to Mamdouh Al-Shamy for introducing Prezi to me.


Saturday, June 18, 2011

Vodafone USB Modem on Ubuntu 10.10

[Note: I also tried the following commands/steps on Ubuntu 11.04 from a virtual machine, but could not test the hardware. You can give it a try]


As mentioned here, the last driver for Vodafone USB modem on Ubuntu is for Ubuntu 10.04, and it is a beta version. I still gave these steps a try on Ubuntu 10.10 and hoped it worked (and it did).

I had to go through two ways to run the USB modem.

Way #1:

1- Install the dependencies as mentioned on website, except for python-gnome2-extras (which is not available). And also two important drivers.

sudo apt-get install wvdial hal python-twisted python-serial python-sqlite python-tz python-gobject python-dbus python-cairo python-crypto python-gtk2 python-gnome2  lsb-release python-glade2
sudo apt-get install usb-modeswitch ozerocdoff

2- Download the Vodafone USB Connect folder from this link.

3- Uncompress the package and install it.
[assuming I downloaded it in /tmp]
cd /tmp
tar xvfz Ubuntu.tgz
cd ./Ubuntu
sudo dpkg -i vodafone-mobile-connect_2.20.01-1_all.deb

4- Run the application from the terminal with the command
vodafone-mobile-connect-card-driver-for-linux
or from the Applications/Internet menu.









Way #2:

After trying this and working with it, I had today the following problem: the USB modem was not recognized, and did not want to get recognized for a while (but after a couple of hours I tried again and worked fine).


So I tried to search for another solution and found that option from the connections icon to "Set up a Mobile Broadband Connection"




[as far as I know, the plans are: Contract,Prepaid]


But this way does not give me the options I use like: Usage, Speed, SMS.



This was all my experience with Vodafone USB Modem on Ubuntu 10.10. I hope it helps.