jump to navigation

Fetching Cotacts from Gmail, Yahoo and Hotmail September 26, 2008

Posted by Puneet Pandey in Uncategorized.
Tags: , , , , , ,
66 comments

Hello Guys,

This is another post by me, hope this post will help you, if you are stuck in fetching or grab contacts from Yahoo, Gmail and Hotmail. This is possible using gem ‘contacts’.

So here I am posting my code, I know there are lot of things and code available for this, but this is the exact code which I am using.

If you are running an application or want to create a new go ahead, I am writing a new application here but you can add it in your existing code as well.

open your command or console prompt and go into your application directory, here I am creating new:

rails contact

this will create a particular set of files and directories in your application. Now go into your directory, before start working any further be sure that you have installed ‘contacts’ gem with the latest version i.e 1.0.13, to install ‘contacts’ type :

for linux users : sudo gem install contacts

for windows : gem install contacts

if already have but older version update it : sudo gem update contacts

Now open your environemnt.rb file and below this line write

Rails::Initializer.run do |config|

end

require ‘contacts’

be sure to restart your server.

Now open the controllers folder and create this method in any controller if you have or where you want to display this. In my case I am writing this in my account_controller.rb

def invite_friends
#@user = User.find(params[:id])
end

def import
@users = User.find(params[:id])
begin
@sites = {“gmail”  => Contacts::Gmail, “yahoo” => Contacts::Yahoo, “hotmail” => Contacts::Hotmail}
@contacts = @sites[params[:from]].new(params[:login], params[:password]).contacts
@users , @no_users = [], []
@contacts.each do |contact|
#if u = User.find(:first , :conditions => @users.email = ‘#{contact[1]}’ , :include =>[:user])
if u = User.find(:first , :conditions => “email = ‘#{contact[1]}’” )
@users << u
else
@no_users << {:name => contact[0] , :email => contact[1]}
end
end
respond_to do |format|
format.html {render :template => ’shared/_contact_list’, :layout => false}
format.xml {render :x ml => @contacts.to_xml}
end
end

before creating this two method, just be sure that you are giving the user id from invite_friends method to import method.

Open up your invite_friends.html.erb and paste this code :

<% form_tag :action => ‘import’, :id => @user do %>

<select name=”from” id=”from”>
<option value=”">Select Id</option>
<option value=”gmail”>Gmail</option>
<option value=”yahoo”>Yahoo</option>
<option value=”hotmail”>Hotmail</option>
</select>

<BR />
<p>Please Enter Your Email Address Below : <BR />
<input type=”text” name=”login”></p>
<p>Enter Your Password :<BR />
<input type=”password” name=”password”></p>

<p><h4>Note : we are not going to save your Password anywhere </h4></p>
<p><%= submit_tag ‘Find My Friends’ %>

<% end %>

Now start your server, open up firefox and type the address (in my case it is) : http://localhost:3000/account/invite_friends

Select any service like Yahoo, Hotmail or Gmail give the corresponding username and Password and hit submit.

You will get an error message that missing template, to remove that create a folder ’shared’ in /app/views/ and create a new file name ‘_contact_list.html.erb’ and paste the below code :

<% for i in @contacts %>
<input type=”checkbox” name=”email[]” id=”email_<%= i %>” value=”<%= i %>” /><%= i %><br>
<% end %>

this will help you to take further actions on fetched email addresses, that’s it. You have done..

If you are facing any problems, leave a comment, I will get back in touch with you, and if your code works, don’t forget to leave a comment.

Thanks to ‘contacts’ and thanks to you all also.

Ruby on Rails Auto Select June 1, 2008

Posted by Puneet Pandey in Ruby On Rails.
Tags: , , , ,
12 comments

Hello Guys,

Once Again I m back with My another Useful Article for You. In this Article I will describe you, how to auto select more than two select box. So, are U Ready??

Here is the Task that U have to achieve :-
You have three Select Boxes one for States, second for city and third for college.

What You want to Do :-
You want that if Some one selects State for Example :- Karnataka, the next drop down will automatically show u the lists of cities that comes Under Karnataka, Furthermore if you select Say Bangalore, the third drop down will show You the lists of colleges that comes under that city.

In short:-
STATE -> CITY -> COLLEGE
KARNATAKA -> BANGALORE -> IIT,Bangalore

Ruby on Rails with Ajax makes it very easy to achieve, It’s a 5 Step Process, Let’s See How
Step 1: create a new application, I am naming my application here ’sample’
Go to konsole/command Prompt:
:    rails sample
This will create particular set of directories and files. Go into that Application
:    cd /sample
Make a Model ‘State’
:    ruby script/generate model State
This will create some files into your application, now open your migration file in your editor
i.e    fever/db/migrate/001_create_states.rb
Type
:    t.column :state, :string
and then save it.
open the model i.e state.rb in some editor
i.e    fever/app/model/state.rb
Type
:    has_many :cities
save this also, now Run
:    rake db:migrate
This will migrate your states table in your database. To save your time I am generating scaffold here, go to konsole/command prompt and type
:    ruby script/generate scaffold State
Note: this will create controller named states_controller.rb in your app/controllers directory.
Your first step is done, now we will proceed on 2nd step.

Step 2: create another model with the name city, for that type :
:    ruby script/generate model City
This will create some files into your application, now open your second migration file in your editor
i.e    fever/db/migrate/002_create_cities.rb
Type
:    t.column :city, :string
t.column :state_id, :integer
save it.
open the model i.e city.rb in some editor
i.e    fever/app/model/city.rb
Type
:    belongs_to :state
has_many :colleges
save this and run
:    rake db:migrate
This will migrate your cities table in your database. Create scaffold of this, Type
:    ruby script/generate scaffold City
Note: this will create another controller named cities_controller.rb in your app/controllers directory.
Your Second step is done, now we will proceed on 3rd step.

Step 3: Create third model with the name college, for that type :
:    ruby script/generate model College
This will create some files into your application, now open your Third migration file in your editor
i.e    fever/db/migrate/003_create_colleges.rb
Type
:    t.column :college, :string
t.column :city_id, :integer
save it.
open the model i.e college.rb in some editor
i.e    fever/app/model/college.rb
Type
:    belongs_to :city
save this and run
:    rake db:migrate
This will migrate your colleges table in your database. Create scaffold of this, Type
:    ruby script/generate scaffold College
Note: this will create another controller named colleges_controller.rb in your app/controllers directory.
You have done with your 3rd Step. Now we will move onto our fourth step

Step4: Create a Third Model with name = User, where we will display all the action, for that type :
:    ruby script/generate model User
This will create some files into your application, now open your Fourth migration file in your editor
i.e    fever/db/migrate/004_create_users.rb
Type
:    t.column :firstname, :string
t.column :lastname, :integer
save it(I think two fields are more than enough to solve my purpose here).
Create a scaffold of this model
:    ruby script/generate scaffold User

Note: that’s it. You have done with your basics steps, now we will use Ajax here, but before that I want you to insert some values of states, cities and colleges manually, be sure that you are giving right ’state_id’, and ‘city_id’ in your corresponding ‘cities’ and ‘colleges’ tables

Step 5: Open app/views/users/new.rhtml
and type below line between your head section
:    <HEAD>
<%= javascript_include_tag “prototype” %>
</HEAD>
Open app/views/users/_form.rhtml, and type the below code after your firstname and lastname fields
:    <p>State <br />
<% @states = State.find(:all) %>
<select name=”state_id” id=”state_id”>
<option value=”">Select City</option>
<% @states.each do |state| %>
<option value=”<%= state.id %>”>
<%= state.state %>
</option>
<% end %>
</select>
</p>

<p>City
<div id=”city_id_container”>
<select name=”city_id” disabled=”disabled”>
<option value=”">No City</option>
</select>
</div>

<%= observe_field(“state_id”, :frequency => 0.25, :update => “city_id_container”, :url => { :action => :add_link_city }, :with => “’state_id=’+value”) %>
</p>
Now open your users controller i.e app/controllers/users_controller.rb, and write the code as shown below
: def add_link_city
@cities = City.find_all_by_state_id(params["state_id"])
end

Now create a new file in app/views/users/add_link_city.rhtml, and add the code as shown
: <HTML>
<HEAD>
<%= javascript_include_tag “prototype” %>
</HEAD>

<BODY>
<p>    <% @html = “<select id=’city_id’ name=’city_id’>” %>
<%= @html += “<option value=”>No City</option>” %>
<% @cities.each do |@cities| %>
<%= @html = “<option value=’#{@cities.id}’>#{@cities.city}</option>” %>
<% end %>
<%= @html = “</select>” %>
</p>

<p>College
<div id=”college_id_container”>
<select name=”college_id” disabled=”disabled”>
<option value=”">No College</option>
</select>
</div>

<%= observe_field(“city_id”, :frequency => 0.25, :update => “college_id_container”, :url => { :action => :add_link_college }, :with => “‘city_id=’+value”) %></p>
</BODY>
</HTML>

Go back again in your app/controllers/users_controller.rb, and add the method as shown below
: def add_link_college
@colleges = College.find_all_by_city_id(params["city_id"])
#@cities = City.find(:first, :conditions => ["city = ?", params[:city_id]])
end

Now create a new file in app/views/users/add_link_college and add the following code

: <HTML>
<HEAD>
<%= javascript_include_tag “prototype” %>
</HEAD>

<BODY>
<p>    <% @html = “<select id=’college_id’ name=’college_id’>” %>
<%= @html += “<option value=”>No College</option>” %>
<% @colleges.each do |@colleges| %>
<%= @html = “<option value=’#{@colleges.id}’>#{@colleges.college}    </option>” %>
<% end %>
<%= @html = “</select>” %>
</p>

<p> If Your College is not on the List, Please Click <%= link_to     “Here”, :controller => ‘colleges’, :action => ‘new’, :id =>
@colleges.city_id %> here to Add Your College</p>

<p>Course
<div id=”course_id_container”>
<select name=”course_id” disabled=”disabled”>
<option value=”">No Course</option>
</select>
</div>
<%= observe_field(“college_id”, :frequency => 0.25, :update =>
“course_id_container”, :url => { :action => :add_link_course },
:with => “‘college_id=’+value”) %></p>

</BODY>
</HTML>

That’s It, You have done. Now you can check this in Your Browser. Type in Your url, http://localhost:3000/users/new, and see the magick.

Waiting for Your Valuable Responses.

Ruby on Rails for Beginners: How to Create Scaffold In Rails February 27, 2008

Posted by Puneet Pandey in Ruby On Rails.
Tags: , , , , , ,
1 comment so far

Hello Guys this is My First, Post On Rails, Here I will Describe You how to create Scaffold on Rails. For those who are Unfamiliar with the Concept of Scaffold, Let me tell You A short Discussion about Scaffolding, Scaffolding is a basic Skeleton of your Application

For Example, if You want your HTML page will consist of Fist Name , Last Name, Email, Password, Address Etc. Scaffolding in rails will do that for you in few seconds, You don’t need to write Code for that.

Now, Let me Describe you, how scaffolding works..

Fist of all Check Your Rails Version, if You are Using Rails Version Greater than 1.2.5 you can’t create scaffolding in that, for that You Must have rails version 1.2.5

You can also take run two versions of rails at the same time.

To install rails Version 1.2.5 on your machine, type in the Konsole/Command Window :

for linux users : sudo gem install rails v=1.2.5
for windows users : gem install rails v=1.2.5

Now check your rails Version by Typing :

for both Linux/Windows User :rails -v

if your Konsole/Command Window shows this :
rails(2.0.2, 1.2.5)
means you have both rails version installed in your machine

in case if it shows this :
rails 1.2.5
you can install another version of rails by using following command :

for linux users : sudo gem install rails v=2.0.2
for windows users : gem install rails v=2.0.2

For those who are Installing rails first time on their machine, I recommand you to use both version of rails, to save extra work.

Now we have done with rails, the second step is to make an Application :
if you wish you can create you own folder where you can keep your all rails application

for me, I am Keeping all my rails applications on a Rails_Application folder

Now go to Konsole/command window..

Go to the directory where u want to keep your all rails application

(From here both Linux/Windows user follow these steps :)
(this is my Directory)puneet@puneet-laptop:/home/windows1/Rails_Application$ rails sample

This Will create the following directories in sample folder
create
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments
create config/initializers
create db
create doc
create lib
create lib/tasks
create log
create public/images
create public/javascripts
create public/stylesheets
create script/performance
create script/process
create test/fixtures
create test/functional
create test/integration
create test/mocks/development
create test/mocks/test
create test/unit
create vendor
create vendor/plugins
create tmp/sessions
create tmp/sockets
create tmp/cache
create tmp/pids
create Rakefile
create README
create app/controllers/application.rb
create app/helpers/application_helper.rb
create test/test_helper.rb
create config/database.yml
create config/routes.rb
create public/.htaccess
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/boot.rb
create config/environment.rb
create config/environments/production.rb
create config/environments/development.rb
create config/environments/test.rb
create script/about
create script/console
create script/destroy
create script/generate
create script/performance/benchmarker
create script/performance/profiler
create script/performance/request
create script/process/reaper
create script/process/spawner
create script/process/inspector
create script/runner
create script/server
create script/plugin
create public/dispatch.rb
create public/dispatch.cgi
create public/dispatch.fcgi
create public/404.html
create public/422.html
create public/500.html
create public/index.html
create public/favicon.ico
create public/robots.txt
create public/images/rails.png
create public/javascripts/prototype.js
create public/javascripts/effects.js
create public/javascripts/dragdrop.js
create public/javascripts/controls.js
create public/javascripts/application.js
create doc/README_FOR_APP
create log/server.log
create log/production.log
create log/development.log
create log/test.log
puneet@puneet-laptop:/home/windows1/Rails_Application$

Now go into your sample project by typing :
puneet@puneet-laptop:/home/windows1/Rails_Application$cd sample

puneet@puneet-laptop:/home/windows1/Rails_Application/sample$

Now go into your database, here i m using MySql Database, and Create a new schema, named sample_development

You can also create a schema through konsole/command window by typing :
(for both Linux/Windows user) :
puneet@puneet-laptop:/home/windows1/Rails_Application/sample$mysqladmin -u root create sample_development

this will create a new schema on your mysql database

Now the Important thing :

for those users who are using both rails version i.e(1.2.5, 2.0.2),
go to: sample/config/database.yml… and open that file

You will find the code like this :

# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000

# Warning: The database defined as ‘test’ will be erased and
# re-generated from your development database when you run ‘rake’.
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
timeout: 5000

production:
adapter: sqlite3
database: db/production.sqlite3
timeout: 5000

Now follow the steps as I am doing, because this is the configuration code for mysql that support rails version 2.0.2 only, and you will not be able to create scaffold.

Follow this (for both Linux/Windows User) :

development:
adapter: mysql
database: sample_development
username: root(your mysql user name)
password: (Your Mysql Password)
socket: /var/run/mysqld/mysqld.sock

test:
adapter: mysql
database: sample_test
username: root(your mysql user name)
password: (Your Mysql Password)
socket: /var/run/mysqld/mysqld.sock

production:
adapter: mysql
database: sample_production
username: root(your mysql user name)
password: (Your Mysql Password)
socket: /var/run/mysqld/mysqld.sock

Now go into you sample/config/environment.rb and open it :

You Will See the following line of code written there :

RAILS_GEM_VERSION = ‘2.0.2′ unless defined? RAILS_GEM_VERSION

Replace this line with this:

RAILS_GEM_VERSION = ‘1.2.5′ unless defined? RAILS_GEM_VERSION

and at the bottom of the environemt.rb file which you have replaced the following code is also written:

config.action_controller.session = {
:session_key => ‘_myapp_session’,
:secret => ‘f088b01f77b99701afe5fb198ed40320c31df263a4d5885f9747f426a8b1d61170ffc3d69cfc617d3c637449b1bdf9ebcf0284e396ec22c84b99f2288f4b18c4′
}

Comment All this, or you can also remove those lines, but I recommend you to comment this. That’s all in environment.rb

Now go to app/contollers/application.rb and open it, you will find the code like this:

class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time

# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you’re not using the cookie session store
protect_from_forgery # :secret => ‘91fa0a704e62068793680a6a0b37d7cf’
end

Comment these two lines
#helper :all # include all helpers, all the time
#protect_from_forgery # :secret => ‘91fa0a704e62068793680a6a0b37d7cf’

To create a Scaffold, You Need to create a Model, Only After that you can create scaffold, there are some more way, but I am describing you the easiest way to do this.

Go into you command/konsole window, then go to your application directory:

puneet@puneet-laptop:/home/windows1/Rails_Application/sample$
and then type:

ruby script/generate model User

this will create following files:
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/user.rb
create test/unit/user_test.rb
create test/fixtures/users.yml
create db/migrate
create db/migrate/001_create_users.rb

Now Open sample/db/001_create_users.rb, and add the following code:

class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.column :firstname, :string
t.column :lastname, :string
t.column :email, :string
t.column :password, :string
t.column :dob, :date
t.column :profile, :text
end
end

def self.down
drop_table :users
end
end

Note: before migrating your tables into your database, be sure that your database must contain a schema called sample_development.

If this schema doesn’t exist you can create manually on ur Mysql Server, or you can create manually by running this command:

mysqladmin -u root create sample_development

Now go into your rails application directory, through konsole/command window and type this:

puneet@puneet-laptop:/home/windows1/Rails_Application/sample$ rake db:migrate

this command will migrate your following columns into your database, the o/p will look like this:
(in /home/windows1/Rails_Application/sample)
== CreateUsers: migrating =====================================================
– create_table(:users)
-> 0.0320s
== CreateUsers: migrated (0.0325s) ============================================

Now the Magic Comes, Type
puneet@puneet-laptop:/home/windows1/Rails_Application/sample$ ruby script/generate scaffold User

You Will See the following directories and files will create:

exists app/controllers/
exists app/helpers/
create app/views/users
exists app/views/layouts/
exists test/functional/
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
identical app/models/user.rb
identical test/unit/user_test.rb
identical test/fixtures/users.yml
create app/views/users/_form.rhtml
create app/views/users/list.rhtml
create app/views/users/show.rhtml
create app/views/users/new.rhtml
create app/views/users/edit.rhtml
create app/controllers/users_controller.rb
create test/functional/users_controller_test.rb
create app/helpers/users_helper.rb
create app/views/layouts/users.rhtml
create public/stylesheets/scaffold.css

That’s it, You have done it, Open your favourite browser, but don’t forget to start your mongrel/WeBrick Server by typing

sudo script/server

in the url type: http://localhost:3000/users/new

and see the rails magick.. isn’t it great!! the fields will also saved on each crate button.

Note: what is the problem in creating scaffold with rails v=2.0.2,

Solution: Each time when you type ruby script/generate scaffold User, All the files will be created, but the controller will not create, So Nothing will Work without a Controller. That’s why I write this post

Validates Username and Passowrd with PHP January 24, 2008

Posted by Puneet Pandey in PHP.
Tags: , , , ,
8 comments

Hi Guys, Here I m Writing the code, How to Validates user name and password with the database…

If the username and Password matches with the database values we need to assign a session to that user..

for that here we are giving a simple session to a user.

<?PHP

session_start();

$server = “localhost”; //In case if u have some other write it here
$username = “Your Server Login Username”;
$password = “Your Server Login Password”;
$db_name = “Your Database Name”;

$db = mysql_connect($server, $username, $password) or die(“Connection to database failed, perhaps the service is down !!”);
mysql_select_db($db_name) or die(“Database name not available !!”);

Those Query Will Connect You with your Database…. Now I m Writing the Query..

$login = mysql_query(“select * from table_name where (username = ‘” . $_POST['username'] . “‘) and (password = ‘” . md5($_POST['password']) . “‘)”,$db);

Tip: here my table contains only Two Field user name and password, if ur table contains more that two fields you can also use *. There is no such issue of using (*) Specifically. (*) will select all the values from the database, where as I can also write

$login = mysql_query(“SELECT username, password FROM table_name WHERE (username = ‘” . $_POST['username'] . “‘) and (password = ‘” . md5($_POST['password']) . “‘)”,$db);

Note: Here first username you are watching is the name of the column in your database and the value $_POST['username'] is the value which we are getting from the form in the previous page. Similarly for password also.

Note2: md5($_POST['password']) is the Password which is stored in the database in the form encrypted value, so that no one can see what the password is!!

$rowcount = mysql_num_rows($login);
if ($rowcount == 1) {
$_SESSION['username'] = $_POST['username'];
header(“Location: welcomehome.php”);
}
else
{
header(“Location: login.php”);
}
?>

Note: here we are giving username and password to a variable called $rowcount.

Next if the user name and password matches with the database we are assigning user a session. and If user name and password doesn’t matches with the database we are redirecting the user back to the login page, else we will redirect the user to its home page.

Hello world! October 17, 2007

Posted by Puneet Pandey in PHP.
1 comment so far

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!