Tuesday, 27 September 2011

Facebook base64 url decode for signed_request in Ruby On Rails

While working with the Facebook API and Ruby on Rails and I was trying to parse the JSON that comes back. The problem i was facing was that Facebook base64URL encodes their data. There is no built-in base64URL decode for Ruby(1.8.7). For ruby 1.9.2 they've included method in base64 module.

While decoding with base64, I kept getting malformed JSON and finally discovered that it was due to the padding.

Fix for this consists of three steps:-
1) Count the length of the payload and see if it’s divisible by 4 (with the modulus operator). If the remainder is 2 then we add 2 equal signs. If the remainder is 3 then we add 1 equal sign to the end of the payload(part after dot operator in signed_request).
2) Replace the character ‘-’ with ‘+’, and ‘_’ with ‘/’

Combining these steps into a method. I created a helper method.

 def base64_url_decode(str)
   str += '=' * (4 - str.length.modulo(4))
   Base64.decode64(str.tr('-_','+/'))
 end
 

Hope it helps someone else trying to base64 decode Facebook’s signed_request in Ruby on Rails.

Thursday, 2 June 2011

To connect remote server database

Reasons which cause remote server fail
1)      Server is not up.
Solution:--- Ensure that server is up, before remote connection(telnet serverIP).
2)      Mysql uses different port than default.
Solution:-- check for mysql configuration file(my.conf), it hast entry for port used for database connection, if it is other than default(3306), try connecting with port specified in file.
3)      Privileges are not granted for remote access on database.
Solution:--
·         You need the root or mysql username and password to log in to MySQL using Telnet or an SSH client. This then allows you to perform queries at the command prompt. At the command prompt, type

mysql -u username -p
Enter password when prompted.

 Once logged in, you can list all available databases by typing :
SHOW DATABASES;

You can set up database to allow connections from only the server it resides on (localhost), from a specific domain (remotedomain.com) or from any domain  except localhost(%).

GRANT ALL PRIVILEGES ON databasename.* TO user@localhost IDENTIFIED BY "password"

GRANT ALL PRIVILEGES ON zingaya.* TO  root@serverIP IDENTIFIED BY "password"

GRANT ALL PRIVILEGES ON databasename.* TO  user@"%" IDENTIFIED BY "password"
·         If you modify the grant tables manually (using INSERT, UPDATE, etc.), you should execute a FLUSH PRIVILEGES statement to tell the server to reload the grant tables

·         If earlier step does not work:------
Locate file my.conf(if not this you may find my-small.conf, my-medium.conf, my-large.conf, my-huge.conf) and chage following things:--
Make sure line skip-networking is commented (or remove line) and add following
line         bind-address=YOUR-SERVER-IP



Where,
a)       bind-address : IP address to bind to.
b)       skip-networking : Don’t listen for TCP/IP connections at all. All interaction with mysqld must be made via Unix sockets. This option is highly recommended for systems where only local requests are allowed. Since you need to allow remote connection this line should removed from file or put it in comment state.
·         Restart your mysql service to take change in effect:
# /etc/init.d/mysql restart
·         For testing, from remote system or your desktop type the command:
$ mysql -u user –h remote_serverIP –p

4)      Host from which you are connecting is not allowed to access that machine.
Solution:-- For this, look at /etc/hosts.allow and /etc/hosts.deny.
/etc/hosts.allow are hosts that are allowed to connect to said services using tcp_wrappers /etc/hosts.deny are host that aren't allowed to connect to said services using tcp_wrappers.
*
Access will be granted when a (daemon,client) pair matches an entry in the /etc/hosts.allow file.
*
Otherwise, access will be denied when a (daemon,client) pair matches an entry in the /etc/hosts.deny file.
*
Otherwise, access will be granted.
                For example:---
                # /etc/hosts.deny
                    ALL:ALL EXCEPT localhost:DENY
    ALL:ALL specifies that none is allowed to connect
    EXCEPT localhost

#/etc/hosts.allow

#Allow localhost
    ALL : 127.0.0.1

# Allow my other box tr0n to connect to any service
   ALL : 192.168.1.2
First line allow any connection to any services from localhost Second line allow any connections to any services from 192.168.1.2



5)      Firewall settings are enabled.
Soultion:--
Try connecting using ssh:---
1)      From your console you can connect using command:--
ssh  -L 3307:127.0.0.1:3306 user@remote.rjmetrics.com
for this you need root password,this command is used to create tunnel on remote machine.
once you provide correct password, you can excute shell commands on remote  machine from   your console
2)      From code:--
Accessing remote machine, there is extention provided in php;--
For this you have to copy php_sh2.dll in your php extension folder, restart server,
Then you can you its functions
This library provides you different function for:---
·         ssh2_connect --  Connect to an SSH server
·         ssh2_tunnel --  Open a tunnel through a remote server
·         ssh2_auth_password --  Authenticate over SSH using a plain password
·         ssh2_exec --  Execute a command on a remote server
·         ssh2_auth_pubkey_file --  Authenticate using a public key
·         ssh2_scp_send --  Send a file via SCP



Crontab functions

crontab creates or changes your crontab file. Your crontab file is a list of tasks that are run on a regular schedule. For example, you might set up your crontab file so that it runs a task every night or midnight, or once a week during low-use hours. This task could perform regular maintenance chores, for example, backing up files or getting rid of unnecessary work files.
Your crontab file is stored in the following directory:
$ROOTDIR/etc/scheduler/crontabs/user
where user is the local user name or the domain user name with a + in place of the \.
To set up a new crontab file, use
crontab file
If you omit the file argument, crontab takes input from the standard input.
Input consists of six fields, separated by blanks. The first five give a date and time in the following form:
  • A minute, expressed as a number from 0 through 59.
  • An hour, expressed as a number from 0 through 23.
  • A day of the month, expressed as a number from 1 through 31.
  • A month of the year, expressed as a number from 1 through 12.
  • A day of the week, expressed as a number from 0 through 6 (with 0 standing for Sunday).
Any of these fields may contain an asterisk * standing for all possible values. For example, if you have an * as the day of the month, the job runs every day of the month. A field can also contain a set of numbers separated by commas, or a range of numbers, with the first number followed by a minus sign - followed by the second number. If you give specific days for both day of the month and day of the week, the two are ORed together.
Here are some examples.
0 0 * * *          -- midnight every day
0 0 * * 1-5        -- midnight every weekday
0 0 1,15 * *       -- midnight on 1st and 15th
                      of month
0 0 1 * 5          -- midnight on 1st of month
                      and every Friday
The sixth field of a crontab entry is a string that your shell executes at the specified time.
If the string in your crontab entry contains percent characters %, they are interpreted as newline characters, splitting your string in several logical lines. You can include an actual % character in this string by escaping it with a backslash (\). The first logical line (up to the first unescaped %) is interpreted as the command you want to execute; subsequent logical lines are used as standard input to the command. If any real (not logical) line in the file is blank or begins with #, the shell ignores the line (treats it as a comment).
-e 
lets you edit your crontab file. crontab invokes an editor to edit the file. If you have an EDITOR environment variable defined, crontab assumes that the variable's value is the name of the editor you want to use. If you do not have EDITOR defined, crontab uses vi.
If you do not have a crontab file, crontab creates one.
-l 
displays your current crontab file on the standard output.
-r 
removes (deletes) your current crontab file and removes the scheduled tasks from the Windows Task Scheduler. When a crontab file is removed using this option, it cannot be rebuilt using the -u.
-s 
synchronizes the list of scheduled tasks in the Windows Task Scheduler with the contents of your crontab file. This ensures that the Window Task Scheduler has a correct list of scheduled tasks and that those tasks are run using the correct environment.
Using this option is necessary for any changes in the SCHEDULER_LOGFILE and SCHEDULER_MAILTO environment variables to be applied to existing tasks.
This option is also useful if crontab's update of the Windows Task Scheduler is interrupted and the tasks are not added. Because the crontab file still exists, you can use this option to ensure that all crontab entries are added.
-u 
rebuilds a deleted crontab file from the remaining entries in the Windows Task Scheduler. This option does not work if the crontab file was removed with the -r option.

Monday, 25 April 2011

Using google/ yahoo maps api

While exploring yahoo/google maps api, came across some useful links to integrated them to web applications. Also attached is sample application using google maps.

For google maps:--

For basic information and generation key:--



For creating markers at user defined address, you need google’s geocoding service as for locating address in google maps, you are always required to give latitude longitude:---

For detailing on opening information windows :--


For yahoo maps:--

For getting started and adding yahoo maps:---

Start guide:--

Creating facebook application

Overview – complaints
When you begin developing Facebook applications you will quickly discover it’s a painful process.
Documentation is generally out of date since the API changes so frequently, so you have no assurance of what you’re reading is still relevent.

Facebook Connect vs. Social Plugins

When integrating with Facebook you can either put components or widgets on your own site (e.g. the Like button) called Social Plugins, or have a Facebook application, which is fronted (proxied) by Facebook but ultimately served by your server called Facebook Connect.
The latter case is what we we’re developing and requires people accessing your site to install your application first. This then appears in their list of applications on their profile page.

FBML vs. iframes
You have two choices when developing a Facebook site, one is to develop in FBML, which is HTML with a few Facebook extensions; and the second is to develop an iframe which is served directly from your server (not intercepted by Facebook) and appears embedded inside the Facebook page.
Developing in FBML means Facebook hits your server with a request for a particular page, interprets all the FBML tags (e.g. ) and substitues them with proper HTML and Javascript, and serves them up to the client.
Developing an iframe application means you’re serving content directly to the client with no Facebook intervention. There is one important caveat to this which is using XFBML. This is a series of tags just like FBML, but instead of Facebook’s servers intercepting and replacing them with HTML before serving them to the client, a client-side Javascript library does this after they’ve been received on the browser.
So the process of an iframe with XFBML is this:
  1. The client browser accesses your application through a URL like http://app.facebook.com/your-app which includes an iframe in the middle.
  2. The browser requests this iframe which is linked to your site through whatever URL you’ve configured.
  3. Your server serves the HTML and XFBML document directly to the client, including a declaration for a Facebook javascript.
  4. The Facebook javascript then executes onces the page has loaded, reading all the tags and turning them into HTML, including hitting the Facebook server to pull down content.
The advantage of this is discussed here. The main deciding factor for us was speed: the little Facebook chat which appears on the bottom right of every Facebook page is large and slow to render. You can avoid the overhead of loading that with every click by running your site through an iframe, since the outer window is not reloaded each time.
The downside is the delay on the browser when the page loads. If you have Facebook XFBML tags on the page these will appear only after the Javascript has executed, called the Facebook server to receive the data and rendered them on the page.
So your users will see a delay before the comments box or like button appear, with the animated “loading” icon.
A consideration for Ruby on Rails developers opting for the FBML method (instead of iframe) is Facebook makes all requests to your server a POST.
This obviously breaks all your RESTful routes and means you’ll probably have to manually write all your routes for every action in your routes.rb file.
Regardless of whether you choose FBML or iframe, the Facebook API is available to you client or server side. On the server side we used the Facebooker gem which provides a convenient wrapper around the API, such as ensure_authenticated_to_facebook.
We tried to keep hits to facebook to a minimum since they add about an extra 400ms to the response time. You can also achieve this by querying the Facebook API client side.
An inconvenience with developing Facebook applications from behind a firewall in your office is you cannot test without deploying. And due to the numerous quirks there’s a lot of hit and miss style development: try something see if it works, nope, repeat until it works.
Having to do a deployment every 30 seconds makes this problem even more tedious until you give up and start developing on the server (yikes!).

Steps for getting started:--
1)      Create a facebook app via facebook developer
2)      Edit settings of app:-- fill canvas url, canvaspage name, site url, essentially
3)      Note api secret and api key
4)      Install facebooker as a gem or plugin
5)      If facebooker plugin not properly installed, download plugin from github and copy to rails app plugin folder and run rake task of setup facebooker
6)      Now you’ll have facebooker.yml in config folder, fill your api key and api secret
7)      Now we need to create a cross-domain receiver file for Facebook Connect to callback on. Luckily, facebooker can do that for us, but make sure you have configured your facebooker.yml file correctly, or the generator will bomb out:
script/generate xd_receiver
Issues Encountered:--
1)Invalid Argument  Given URL is not allowed by the Application configuration. Error coming while opening login window of facebook
Solution:-- Change siteurl value from localhost:3000/businesses to localhost:3000/
2)Loginerror.php after filling login credentials. 
Solution:- Site url value should not be blank, it should contain url of application 
3)Infilinte loop:- request going in infinite loop, from website controller.
Solution:-- comment out protect from forgery