June 3rd, 2010 by divyang.shah §
It is highly recommended that you use MySqli extension of PHP instead MySql as in near future it will be deprecated from PHP. It is more secure, reliable and object oriented.
Following are some useful links which will give you jumpstart on MySqli:
Overview
http://www.php.net/manual/en/mysqli.overview.php
Prepare statement example
http://www.php.net/manual/en/mysqli-stmt.affected-rows.php
Multi-query example
http://www.php.net/manual/en/mysqli.multi-query.php
Enjoy your new DB classes.
May 11th, 2010 by bhumish.shah §
Today, I will show you an excellent way of doing a code review of your team.
This article is based on Fedora, Redhat, CentOS distribution.
I’ll talk about how to configure an SVN commit event for email notification on repositories named svnmailtesting.
After installing subversion in Linux you can find the subversion-tool in following location:
/usr/share/doc/subversion-1.4.4/tools
You can find mailer.conf in the following location:
/usr/share/doc/subversion-1.4.4/tools/hook-scripts/mailer/mailer.conf.example/
An example for the Mailer.conf. is the main file for configuration. It looks like this after removing the comments:
[general]
smtp_hostname = 192.168.0.208
[defaults]
diff = /usr/bin/diff -u -L %(label_from)s -L %(label_to)s %(from)s %(to)s
commit_subject_prefix = [SVN-Commit]
propchange_subject_prefix =
lock_subject_prefix =
unlock_subject_prefix =
from_addr = [email protected]
to_addr = [email protected]
reply_to =
generate_diffs = add copy modify
show_nonmatching_paths = yes
[maps]
This is a very simple file . You have to just change the smtp server, “from” address and “to” address according to your environment.
You can either configure mailer.conf.example and rename it to mailer.conf file
or
Just copy and paste the above code in mailer.conf file
For example :
#vim mailer.conf
Copy the code above and paste it in the mailer.con file and change the smtp server , “from” address and “to” address. After completing these steps, copy mailer.conf file to following location:
cp mailer.conf /var/www/svn/repo/svnmailtesting/conf/
After completing the steps go to the following path:
/var/www/svn/repo/svnmailtesting/hooks/
Rename post-commit.tpl file to post-commit and make it executeable so the apache user can execute this file:
# cd /var/www/svn/repo/svnmailtesting/hooks/
# mv post-commit.tpl post-commit
# chmod 770 post-commit
#vim post-commit
Add the following line at the end of the file:
/usr/share/doc/subversion-1.4.4/tools/hook-scripts/mailer/mailer.py commit “$REPOS” “$REV”
After completing these steps, whenever a user commit in svn repositories (svnmailtesting), one mail will get sent from [email protected] to [email protected] account with the subject: You have configured in mailer.conf file.
Great, so now you have an excellent way of doing code reviews of the developers.
Please write in comment if I have missed anything here.
September 13th, 2009 by pratik.joshi §

Displaying Google map
The iPhone SDK 3.0 offers a class of map view in MapKit framework. You just need to declare an object of MKMapView and add it to your current view.
MKMapView *mapview=[[MKMapView alloc]initWithFrame:(CGRectMake(0, -20, 320, 320))];
[self.view addSubview:mapview];
Now, to display the user location on map, I was trying to insert a pin annotation on map. Soon, I realized that was wrong approach. User location is meant for changing. It will be updated many time.
The solution for this was to use the MKUserLocation class object. The object of this class will return “Blue dot” of built-in Google map application on iPhone. It will also show animated circle with radius of probable range of user location.
MKUserLocation *ulocation=[[MKUserLocation alloc]init];
[mapview setShowsUserLocation:TRUE];
[mapview addAnnotation:ulocation];
That’s it. You don’t need to worry any more about the current location of user. The ulocation object will change its co-ordinates and display the dot whenever the position is updated.

Sending encoded image
You can send images to web service either by mail or by encoding it to string. I have used base64 encoding method to encrypt the image taken from iPhone camera and to send it to web service.
Generally, the image taken from iPhone camera is of very large size (800 kb to 2 mb). So, it may take very long time to encode the image.
I found another way to do the same thing. After taking the picture, you can display the image taken in full view of screen (320*480). Then take the screenshot at that stage and fetch the new image for encoding. In this way, you can make your encoding faster as this was the same picture taken using camera.
I have used following process to take the screenshot.
UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];
UIGraphicsBeginImageContext(screenWindow.frame.size);
[screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *screenshotPNG = UIImagePNGRepresentation(screenshot);
Now, since you have the image in screenshotPNG, you can encode it using your base64 method.
NSString *dstring=[[NSString alloc]init];
dstring=[self base64StringFromData:screenshotPNG length:[screenshotPNG length]];
Playing a specific song
With iPhone SDK 3.0, we have the access to iPod library on iPhone. The apple documentation “iPodLibraryAccess Guide” covers most of the part needed for understanding this functionality. Here, I will describe how to play a specific song stored on iPhone.
Let’s assume our song name is in songtitle which is NSString. To begin, we need objects of
MPMusicPlayerController and a MPMediaQuery.
MPMusicPlayerController* iPodMusicPlayer;
MPMediaQuery *everything = [[MPMediaQuery alloc] init];
everything=[MPMediaQuery songQuery];
NSArray *itemsFromGenericQuery = [everything items];
for (MPMediaItem *song in itemsFromGenericQuery)
{
NSString *mysong = [song valueForProperty: MPMediaItemPropertyTitle];
if([mysong isEqualToString:songtitle])
{
iPodMusicPlayer=[MPMusicPlayerController iPodMusicPlayer];
[iPodMusicPlayer setNowPlayingItem:song];
[iPodMusicPlayer play];
break;
}
}
Using Facebook Connect on iPhone
Facebook Connect used in iPhone lets user connect to their facebook account. I am facing one problem in maintaining session of facebook. The sample application provided with facebook sdk allows user to stay logged-in even if iPhone application is terminated. So, the user will not have to enter facebook account username and password next time.
We can know the status of user if he is logged in by using -
(void)dialogDidSucceed:(NSURL*)url and – (void)sessionDidLogout:(FBSession*)session method from FBLoginDialog.m.
Whenever user logsin using facebook account, the session will stored using NSUserDefaults. We can know this by tracking -(void)save; method in FBSession.m file.
The save method in FBSession.m stores 4 objects in userdefaults: FBUserId, FBSessionKey, FBSessionSecret and FBSessionExpires.
I am facing problem here. Whenever I try to resume previous session, using -(BOOL)resume; method in FBSession.m, I get correct userid, but rest of the values will be nil. i.e.session key, sesison secret and session expirary date are nil. So, I get one fatal error at that time saying: “attempt to insert nil value (key: session_key)” I am still trying to find out the solution for that.
August 26th, 2009 by Brijesh Patel §

Palm Pre
Palm Pre is mobile technology and it mainly includes the following functionality
- Move and open multiple applications very easily.
- Palm Services like Backup and restore important data and erase data remotely if phone is stolen or misplace.
- Palm web OS™ platform are integrated with other apps on the phone
What is webOS?
Palm webOS is an embedded operating system developed by Palm, Inc. for a range of devices. It includes many features like designing, coding and debugging.
What is Mojo?
Mojo is “an application framework based on the HTML5, CSS, and JavaScript standards”. Applications built with Mojo “are installed and run directly on the device at native speeds and have access to a wide range of device services”.
While Mojo should be sufficient for developing a wide range of applications, other graphics-intensive programs such as games would probably require a lower-level webOS API. There has been some speculation that Palm will release a second API that enables developers to access the hardware more directly for these types of applications.
Scene:
Scenes are mutually exclusive views of the application within a stage. Most applications provide different kinds of scenes within the same stage, while simple applications (such as Calculator) only have a single scene. Typically, a new scene is pushed after a user action, such as a tap on a UI widget, and the old scene can return with a “back” gesture. Scenes are managed by a scene stack, with new scenes pushed onto and off of the stack with the last scene visible.
Scene assistant:
A scene assistant is a “controller” for a scene. It contains the logic behind how the scene behaves and responds to user input.
Widgets:
Widgets support webOS user interface, and Mojo definies styles for each of the widgets. The styles are available simply by declaring and using the widgets, or they can be overridden either collectively or individually with custom CSS.
The List widget is the most important in the framework, as “the webOS user experience was designed around a fast and powerful list widget, binding lists to dynamic data sources with instant filtering and embedding objects within other widgets and lists.”
Simple widgets include buttons, checkboxes, sliders, indicators, and containers.
The Text Field widget includes text entry and editing functions, including selection, cut/copy/paste, and text filtering, and can be used in conjunction with a list widget.
Menu widgets can be used with specified areas of the screen, including the view and command menus that are completely under your control. The app menu is handled by the system, but custom items can be added to the menu, as well as functions to service the help and preferences items.
Picker and viewer widgets are more complex, with pickers used for browsing and filtering files or contacts, or for selecting addresses, dates or times. Viewers are used to play or view items such as audio, pictures, video or web content within your application.
Requirement for development in Palm Pre
How to start development in Palm Pre?
Before starting development in Palm Pre you need to download VirtualBox, Mojo SDK and Eclipse 3.4.2 version. Install VirtualBox first, then only download and install Mojo SDK. It is pre-requisite for Mojo SDK installation. When you start installing Mojo SDK, make sure that VirtualBox is not running.
Now Double-click the Palm SDK Installer file.
- The Palm emulator becomes available in the Applications folder.
- The Palm command-line tools become available from the Terminal.
- Create or choose a directory to use as your application development workspace.
You can start the Palm Emulator by double clicking on its icon in the Application directory. At that time Virtual box starts up and creates virtual machine that hosts the Palm Web OS Platform. When you start VirtualBox first time there are several message will come. Just click ok on that diaglog box and continue.
In Eclipse you need to add Mojo SDK plug-ins. For that,
- Start Eclipse.
- go to Help Menu, Select Software Updates and click on Available Software tab.
- click and select Add Site button. and in the location field http://cdn.downloads.palm.com/sdkdownloads/1.1/eclipse-plugin/eclipse-3.4/site.xml and click Ok.
- check Palm Mojo SDK and click Install.
- Restart Eclipse.
After installing Mojo SDK add plugins in the Eclipse,
Selecting the webOS Perspective
1. Select Window > Open Perspective… > Other…
2. Select webOS from the Open Perspective dialog.
3. Click OK.
Preparing webOS Application
From the New Project menu:
1. Start Eclipse.
2. Select File > New Mojo Application.
3. On the next screen, type a name in the Project Name field.
4. Enter your application info:
5. Click Finish.
From the New App toolbar menu:
1. In the Eclipse toolbar, click the Mojo Wizard icon and select New App from the drop down menu.
2. On the New Project Wizard screen, type a name in the Project Name field.
3. Enter your application info:
4. Click Finish.
Adding a scene to your webOS Application,
From the New Project Menu:
1. Select File > New > Mojo Scene.
2. On the New Mojo Scene Screen, make sure the correct project is selected.
3. Enter a name for your scene and click Finish.
From the New Scene toolbar menu:
1. In the eclipse toolbar, click the Mojo Wizard icon and select New Scene from the drop down menu.
2. On the New Mojo Scene Screen, make sure the correct project is selected.
3. Enter a name for your scene and click Finish.
Running a webOS Application
1. Select Run > Run Configurations…
2. Select Palm Application and click the New Configuration icon to create a new launch configuration.
3. Change the name.
4. Select your project from the drop-down list.
5. Select the Target:
-
- Palm Emulator if you are using the emulator.
- Palm Device if you are using a device (make sure your device is in Developer Mode).
6. Click Run to install and run the application.
Installation starting problem when you run emulator first time.
If you are running on installing the application for the first time in Palm Emulator there is a possibility of getting following error.

Error Message
To fix it you simply need to enter the following two commands in your terminal command prompt:
$ sudo chmod 644 /Library/LaunchDaemons/com.palm.novacomd
$ sudo /opt/nova/bin/post-install.sh
For more information please go through following site, you will find out more regarding this error.
http://www.ozmox.com/2009/07/25/webos-on-mac-os-x/
Tutorial of your First Palm Pre Application development:
Now how to develop first Palm Pre Application, following steps will guide you in details of Palm Pre development.
For that from New Project menu:
1. Start Eclipse.
2. Select File > New Mojo Application.
Give the name of the application.
What is a Stage?
Now in the application you need to set the stage. A stage is the platform on which you build the user interface for your application. A stage generally corresponds to a single card, or application window. Most simple applications have a single stage, contained in the file index.html. An application that lets the user perform more than one action concurrently might require more than one stage. For example, an email application might show the inbox on one stage, but launch a second stage to compose a new email message. Notification and background applications have no stages at all.
So change in the Index.html page.
<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en“>
<head>
<title>PalmTest</title>
<script src=”/usr/palm/frameworks/mojo/mojo.js” type=”text/javascript” x-mojo-version=”1″ />
<script src=”app/assistants/stage-assistant.js” type=”text/javascript“></script>
<script src=”app/assistants/first-assistant.js” type=”text/javascript“></script>
<!– application stylesheet should come in after the one loaded by the framework –>
<link href=”stylesheets/main.css” media=”screen” rel=”stylesheet” type=”text/css” />
</head>
<body>
<h2> Testing Application
</h2>
<p>
One stage application
</p>
</body>
</html>
Now create new scene named “First-scene”. It will add two files and one json file.
The palm-generate command creates the view and the assistant for the first scene. It also adds a few lines to sources.json to correlate the assistants and scenes. Take a look at the following files:
- /app/views/first/first-scene.html — This is the view.
- /app/assistants/first-assistant.js — This is the assistant.
- sources.json — This file now includes JSON information that binds first-assistant.js to the first scene.
Now modify the first scene html file for adding new controls.
Open first-scene.html and replace the content with the following
<div>
<div class=”palm-header”>Header</div>
<div id=”count”>0</div>
<div id=”MyButton” x-mojo-element=”Button”></div>
</div>
Now to show the scene, you have to tell stage to push the scene.
To push the application scene
1. Open stage-assistant.js.
2. Edit the StageAssistant function to contain the following:
function StageAssistant () {
}
StageAssistant.prototype.setup = function() {
this.controller.pushScene(“first”);
}
Now how to bind and register the handler, there are two steps.
- binding the handler to the scene assistant’s scope, using bind(this)
- registering the handler as a listener, using Mojo.Event.listen()
Now open first-assistant.js and edit setup function and add following code into that.
FirstAssistant.prototype.setup = function() {
// set the initial total and display it
this.total = 0;
this.controller.get(“count”).update(this.total);
// a local object for button attributes
this.buttonAttributes = {};
// a local object for button model
this.buttonModel = {
“buttonLabel” : “CLICK HERE”,
“buttonClass” : “”,
“disabled” : false
};
// set up the button
this.controller.setupWidget(“MyButton”, this.buttonAttributes, this.buttonModel);
// bind the button to its handler
Mojo.Event.listen(this.controller.get(“MyButton”), Mojo.Event.tap, this.handleButtonPress.bind(this));
}
After creating build, run the application. It will shows the count that how many times you pressed “Click Here” button. It will increase every time you press click button.

PalmPre Sample
Same way you can add more than one scene and navigate from one scene to other scene using following script which will help you to redirect to second scene by pushing the scene.
FirstAssistant.prototype.nextScene = function(event){
if (this.textModel.value == “Testuser”)
{
Mojo.Controller.stageController.pushScene(“second”,this.textModel.value,this.Passowrdmodel.value);
}
else
{
this.labelmodel.value=”Invalid User and Password”;
}
}
And you have your first Palm Pre application ready! I hope you enjoy Palm Pre development and leverage the first mover advantage of the platform.
Following are some good references for Palm Pre development:
http://developer.palm.com/
http://www.weboshelp.net/webos-mojo-development-resources
July 24th, 2009 by kuldip.bhatt §
When ever we write script or code in SQL Server we all face problem like following.
“We store the value in database with the delimiter. Now we want to use that value in the another Procedures or Views and may be to display in reports or any where else in the system. At that time we face problem in getting data out of those delimiter”
So lets see how to get the data in the table format from one column value in which values are stored with some delimiter.
Below is the table value function which gives desired output in the table format.
Parameters which need to be passed in function are:
@String = string value which needs to be formatted for e.g. string like ‘IT,Marketing,Production’. Here as we can see values are separated by comma “,”.
@Delimiter = Delimiter like coma(,) , Pipe(|) etc.
Function Code
==========
Create FUNCTION dbo.Split_String(@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (Items nvarchar(4000))
AS
BEGIN
DECLARE @No INT
DECLARE @Item nvarchar(4000)
– Initilize the @no variable with 1
SELECT @No = 1
– if null then return
IF @String IS NULL RETURN
WHILE @No !=0
BEGIN
– get the first o
SELECT @No = CHARINDEX(@Delimiter,@String)
– get the value in the @item variable
IF @No !=0
SELECT @Item = LEFT(@STRING,@No – 1)
ELSE
SELECT @Item = @String
– Put the values in the Result Set
INSERT INTO @Results(Items) VALUES(@Item)
– Remove the item from the main string
SELECT @STRING = RIGHT(@String,LEN(@String) – @No)
– break it work done
IF LEN(@String) = 0 BREAK
END
RETURN
END
Lets check Example of it:
==============================
Select * from dbo.Split_String(‘IT,Marketing,Production’,',’)
Output in table format:
==============================
IT
Marketing
Production
Great! we have all the data in tabular format now which you can easily use anywhere else in your code.
I hope this little function will help you save lot of time and frustration. Please comment if you know any better solution for this.
July 23rd, 2009 by divyang.shah §
Today I am going to share something I know about indexing. I am sure you all must be using it somewhere or must have heard of it.
Let’s see one wonderful example of its usage today which will show how important it is to use indexes properly in Database. I would like to thank my client and my mentor Stephen Fegel of Galatea Systems for imparting this wonderful knowledge.
We all use “Select” for retrieving data from the tables. In most cases if data is not too much it takes minimal time to fetch records without indexing also. But in case of large data this may be a severe problem.
Lets take an example:
I have two tables one is houses which is my main table and it has 25,666 records.
And another table is house_desc which has 6,04,255 records.
And the query is
SELECT
SQL_NO_CACHE h.*,
(SELECT
SQL_NO_CACHE desc_value
FROM
house_desc AS d
WHERE
language_id = ‘EN’
AND
d.house_id = h.house_id
AND
(
desc_type = ‘description’
OR
desc_type = ‘introduction’
)
ORDER BY desc_type
LIMIT 0 , 1
)
AS
desc_value
FROM
houses AS h
WHERE
house_id
IN (’12345678′)
Now lets join both the tables and fire sub query for retrieving data from house_desc table.
Structure of the house_desc is
`c_code` varchar(50)
`house_id` int(10)
`country` char(2)
`language_id` enum(‘NL’,'EN’,'DE’,'FR’,'ES’,'IT’)
`desc_type` varchar(50)
`desc_value` longtext
So when I fire the query without indexing and I get following result
Showing rows 0 – 0 (1 total, Query took 13.0067 sec)
It returns only 1 row but still it took 13 secs!!
Now just see the magic of indexing here. Just set the index on house_id field
Fire the same query again and here is the result:
Showing rows 0 – 0 (1 total, Query took 0.0899 sec)
Output is same but just look at the difference in time to fetch records!
Before indexing it took 13.0067 seconds and after indexing it took 0.0899 seconds i.e. it is 1000 time faster than without indexing.
The result may be different in your case as in sometimes it can be 100 time faster or 10 time faster but one thing is for sure that it will be faster than without indexing (if done correctly!).
When you have large amount of records in your table and you want to search that table then it is better to set index on those fields which are there in where clause.
You can’t set index on all the fields from table. It is also very important thing on which filed you set the index.
You can read more on indexing from this
http://www.informit.com/articles/article.aspx?p=377652
July 10th, 2009 by vishal.shukla §
When developing desktop based or similar applications, it becomes headache to synchronize data between different pages. Say when Delete is clicked in context menu of some node of tree, Grid and some other panels need to be notified. Here is one simple way for accessing data of other panels. We have singleton session object (only one object at runtime) at each client’s runtime. So when we have some data that need to be used in other pages, we can put those objects in the session map and access it from the other class. Here is how we can create class that gives singleton instance of session map.
import java.util.HashMap;
public class SessionFactory {
private static HashMap session;
private SessionFactory(){
}
public static HashMap getSessionInstance(){
if(session==null){
session = new HashMap();
}
return session;
}
}
June 27th, 2009 by divyang.shah §
Facebook has always been touted to have strong privacy controls. To most extent it is true and it is much better than most of the other social networks. But as a biggest social network they do have loopholes which can be easily exploitable by atleast developers like us.
Today I am going to talk about one such exploit:
How to view albums of people who are not your friends?
So when we search for interesting people on Facebook most of the time you will find their profile having restrictions. Mostly you will be able to see their profile photo and will be able to send message to them. So to see their full profile or albums we have to send “add friend” request and if they approve then and then only we can see their photos and profile.
But here is one way to bypass this:
First you have to add developers application in Facebook which can be added from following link:
Link: http://www.facebook.com/developers/?ref=sb
Then go to this link
http://developers.facebook.com/tools.php
It will open below page and choose you response formate and also method = photos.getalbum as shown in below image.

So after that enter facebook user id whose photos you want to see, in “uid text box” as shown in below image and then press “call method button”.
Get the facebook id from the address bar/url bar or find the “add as a friend” link in the web page and move your mouse cursor over it and you will get facebook id in the status bar as shown in image.

And you will get details of all the albums of that user if he or she have albums as shown in below image in right side box.
Just you have to copy link content from right box and paste it to another browser or tab and press enter and then you can see all photos from that album without adding the user as a friend.

Note: I have changed all the ids they are not real.
I hope with the help of this article and community, facebook will notice this bug and will resolve it.
So enjoy peeking on stranger’s albums. 
Update: It seems that Facebook has resolved this bug now.
June 14th, 2009 by vishal.shukla §
In last post, we identified what issues can arise if we keep going with the design shown in Etymology Of Decorator Pattern. Lets take a quick look at what fundamental design problems exists in the design that we have already discussed.
In the existing design, we have all the possible toppings of Pizza hard-coded into the Pizza class. Which are, in fact, individual Object in the real world. So in a way, they are Add-on objects that can be used to decorate our pizza. If we want to add new item as toppings, we need to modify the class. Ideally, we should be able to add any new topping “without modifying the class”, hence we come to know Open-closed principal.
“Classes should be closed for modification and open for enhancement.”
Now question is how to achieve this. Let’s note down what approach we need to follow to get maximum flexibility in design (maximum in terms of toppings and calculating its cost) in creating one FreshVeggiePizza with Paneer and Olives.
1. Take plain Pizza object.
2. Decorate it with Paneer.
3. Decorate it with Olives.
4. Call cost() method, which will be delegated to “Add-on” or “Decorator” objects also to add up their cost.
Read More >>
June 5th, 2009 by vishal.shukla §
Today our purpose is to know why decorator pattern. In last post, we found that there is class explosion if we go with the first trial. Now what we can do to improve this design is, we can have one abstract super-class Food which will be specialized by Pizza and Sandwich classes. Food class will be abstract:
public abstract class Food {
private List ingredients;
private String description;
public abstract double cost();
}
Pizza class will extend this Food class and add pizza specific property in this class. For example, crustType, extraCheese, olives, jalapano, paneer etc. If the pizza subclass needs to add jalapano in the toppings, value of jalapano will be true. Similarly, we can have Sandwich class, extending Foot class and adding some Sandwich specific properties to it.
Read More >>