Tuesday, January 19, 2010

Allow users to select Roles while Registration in Drupal

If you want to provide an option for the user to select roles in the registration form, use the module called user selectable roles. The module source url is
http://drupal.org/project/user_selectable_roles
After install it in your application, you should goto administer->user mangement-> user_select_roles
There you can set which roles are displayed in the registration form and other options to select multiple roles selection or single etc.

Restrict accessing your site for some users based on their IP Address

In .htaccess add below lines

Order allow, deny
Deny from 192.168.0.10
Deny from 1.2.3.4 5.6.7.8 127.0.0.1
Allow from all


It is allowed accessing for all except fom IPs 92.168.0.10,
127.0.0.1,127.0.0.2,127.0.0.3


--------------------------------------------------------------
OR if you want to access your site from your IP only add below lines in .htaccess file

Order deny, allow
Deny from all
Allow from 192.178.0.10


This will be usefull for your site administrators.
If you set this for site admin, then the administrator can access admin area from the mentioned IP only.


Run PHP Code in HTML files

If you want to run PHP Code in your static HTML pages, you need to create .htaccess file (if it is not already exists) in the directory of where all your html files exists and add the below lines of code

For web servers using PHP as apache module:

AddType application/x-httpd-php .html .htm

For web servers running PHP as CGI:


AddHandler application/x-httpd-php .html .htm

If your requirement is only for one page then use below code

AddType application/x-httpd-php .html

Thursday, January 7, 2010

Ruby on Rails Fat model and skinny controller

Ruby on Rails controller actions should be very clear and should not contain more than two instance variables in an action. So almost write everything in model as the methods and call them in controller actions. I write a code below for how to done it to get related galleris.
#app/model/gallery.rb
class Gallery < ActiveRecord::Base

def self.get_related(galname)
related = find(:all, :conditions => ['name like ?', '%'+galname+'%'])
end
end

#app/controllers/galleries_controller.rb
class GalleriesController < ApplicationController
def show
@gallery = Gallery.find(params[:id])
@related = Gallery.get_related(@gallery.name)
end
end

#app/views/galleris/show.rhtml

Related Galleries


<% @related.each do |relate|%>
<% if (relate.id!=@gallery.id)%>


<%= link_to( relate.name , { :action=>'show', :id=>relate.id}) %>


<% end %>
<% end %>

Ruby on Rails shareble content or menus processing

Store the common menus or links in some where in app/views folder with filename prefixing with _. Ex store the links in app/views/shared/_global_links.rhtml file and call it in app/views/layouts/application.rhtml file.

Ex: app/views/shared/_global_links.rhtml
<% if logged_in? %>
<%= current_user.login %> |
<%= link_to "Dashboard", root_url %> |
<%= link_to "My Account", profile_url(current_user) %> |
<% if admin? -%><%= link_to "Administration", admin_root_url %> | <% end -%>
<%= link_to "Log out", logout_url, :method => :delete %>
<% else %>
<%= link_to "Sign up", signup_url %> |
<%= link_to "Log in", login_url %>
<% end %>

#app/views/layouts/application.rhtml
-------------------------------------------------------
-------------------------------------------------------

<%= render :partial => 'shared/global_links' %>

-------------------------------------------------------
-------------------------------------------------------

Ruby on Rails Dynamic content blocks using contentfor and yield helpers

In app/views/layouts/application.rhtml design application layout and set some right block. The content in that rightcolumn is dynamically filled by the view
----------------------------------------------------------

<%= yield_or_default(yield(:sidebar)) %>

-----------------------------------------------------------

In app/views/users/index.rhtml you should set the content for rightcolumn for the users page like below
-----------------------------------------------------------
<% content_for :sidebar do -%>

Sidebar



<% end -%>
-----------------------------------------------------------

In In app/views/movies/index.rhtml you should set the content for rightcolumn for this movies page like below
-----------------------------------------------------------
<% content_for :sidebar do -%>
some movies related information you can place here
<% end -%>
-----------------------------------------------------------

Rails use :select for better performance

If you want to retrieve some fields information from database, then it is better to use select in the find method.
Example use below
@movies = Movie.find(:all, :select => 'title, description')
instead of
@movies = Movie.find(:all)

It will get only the title and description and store into instance variable (hash) @movies.

Here you application load time will definetly decreased.

About Drupal Framework

Why Drupal? What's a Framework?

A brief history of web applications

I think about web technologies as a series of layers. At the bottom, you've got the computer hardware that hosts your site. At the top, you've got what you see in your web browser--a bunch of text, pictures, videos, and ways of interacting with that content. In the middle are all the bits and pieces that get put together to create what you see in your browser.

In the early days of the web, there were pretty much 3 layers between the hardware and your web pages: the operating system on the server, a program called a web server that sent the pages to your browser, and a collection of HTML files and images that contained the content.

Early on, web servers started handing off particular requests to other programs, which could generate HTML on the fly and do other actions. The earliest mechanism for this was called CGI (Common Gateway Interface), and it allowed programmers to process data sent by forms, store and retrieve data from databases. At this point we quickly got to the point where we had stacks of software that work together to make more dynamic web sites. One of the most popular stacks is called LAMP, for the Linux operating system, Apache Web server, MySQL database, and PHP (or Perl or Python) language. A programmer can write programs in PHP to interact with a database and give you pages that are not just static files stored on the server, but generated on the fly. These pieces were all in place and in fairly widespread use by 2000 or so. Programs written in PHP on the web have come to be called "Web Applications."

What's a web application?

Quite simply, a web application is just a program that runs on a web server that you access through a web browser. We've built web applications to manage client data for a legal association, manage photos, manage who on a team is going to come to each game, track time spent on tasks and projects, sell products through the web in both a wholesale/manufacturing environment and for retail, and many others. We've deployed web applications for managing the financial records for a business, manage contacts with clients, report on electricitly usage in a house, all kinds of things. Database applications can solve all kinds of business needs, in all kinds of ways. Web applications are simply database applications you can access with an Internet connection and your web browser.

Most web applications are built to solve one kind of problem, and solve it well. Often if you start with an application made for one purpose, it's very difficult to repurpose it for another. Content management systems are not usually interchangeable with contact management systems. If you deploy a system designed for making it easy to publish blog posts, you're not likely going to find it useful for selling products--you'll need a different system. A system built to manage games and sports teams is not likely going to work well for tracking recipes.

What's a Content Management System?

You'll hear them called a "CMS" for short. Content management systems are web applications that are built to manage content on a web site. Their job is to make it so that you can easily edit or add new content to your web site without needing special tools. There are hundreds of different CMSs out there, each with different strengths and weaknesses. We've worked extensively with Joomla, Word Press, MediaWiki, and several others, but Drupal is our core CMS these days--because it's flexible enough to do more than just manage content.

What's a Framework?

Let's peel back a layer and look at what's under the hood. A Content Management System is a particular kind of web application. A framework is a set of tools and a pre-defined architecture for building a web application. So you could quite easily build a content management system on top of a framework.

Have you heard of Ruby on Rails? Rails is a framework, written in the Ruby programming language. Other popular frameworks include Django, CakePHP, Symfony, and dozens of others.

Most frameworks provide a built-in architecture to rapidly develop a full-blown web application. They often tend to use a "Model-View-Controller" organization -- a common way of dividing up programming tasks into units that can be managed more effectively. The "Model" represents the various objects your application manipulates -- pages, customers, projects, addresses, whatever. The "View" is usually the layer that graphic designers work with, to provide a look-and-feel for the application. The "Controller" ties all the bits together, determines who can access what and how it all works. In grammar terms, elements of the model are nouns, the view is mostly adjectives, and controllers are the verbs.

Powerful stuff. Frameworks are great. Except there's one big problem with using a framework, when there's already a good application for you to use: you still have to build an application!

If you're building a web site to manage content, and you're starting with a framework like Rails, it's like building a car from a kit instead of buying one off the lot: you have to do a lot more work before you can start driving.

If you need an application to do something you can't do in an existing application, a framework may well be the way to go. But before doing that, first see if there's an application that does the job for you already. If there is, your first step becomes putting your data into the application, not building the application.

Drupal as a Framework

Drupal is a fine content management system all on its own. But its true strength is that it's flexible enough to do many things beyond just managing content, while remaining modular enough to keep it simple.

Drupal provides quite a lot of base functionality that developers can leverage to rapidly develop all kinds of applications. The key things include:

  • A complete user authentication system, with plug-ins for OpenID, LDAP, and many other systems
  • A robust role-based authorization model
  • Any number of "Content Types" may be defined, using default handlers overridden where necessary, for storing content objects and relationships
  • A flexible taxonomy system that can be used to categorize and tag content
  • The "Forms API" to make it simple to create, validate, and process forms and uploaded files
  • Multiple theme engines with a clear override system for theming individual elements and pages
  • A sophisticated URL-parsing system to hook functionality to particular paths
  • An extensive hook system allowing you to completely change the behavior of the application at a fundamental level
  • Built-in caching, Javascript and CSS optimization, and cache-busting features for a nice mix of performance and development flexibility, and
  • Thousands of additional modules to make all sorts of changes to the system, including workflow rules, e-commerce, access control, automatic image processing and much more.

That's just a taste of what you can do with Drupal. There's a very definite learning curve before you'll know how to do all of this--which is why it's worth hiring a company like us to get you started. But there's a similar learning curve involved in using any framework effectively, too. The difference is, with Drupal you can start with a working site and easily add features as you go.

Why wouldn't you use Drupal?

There are a lot more specific applications that do particular things, and do them well. Want to manage your customer relationships? SugarCRM is a good place to start. Manage your business finances? LedgerSMB. Have a standalone desktop application you can use offline? Not Drupal. We've recently used LimeSurvey for a couple projects that used very sophisticated question formats, and it still met the need better than the Quiz module in Drupal.

If your needs are limited, and your site is meant to have a single function, you might be able to start more quickly and with less cost with a more specific solution. But if you need to build something custom, we're not seeing very many applications that can't be done well in Drupal. There are people in the Drupal community building clones of popular sites like Facebook, Twitter, Flickr, Basecamp, YouTube, and others, just to see how well Drupal can do the job. All can be done pretty quickly by a knowledgeble Drupal person, without much custom code.

The other place we've been working without Drupal is on web applications that have a huge amount of Javascript. Drupal is fine as a back end for a lot of different systems, though in some cases a simple framework storing resources managed from the browser may be a better way of supporting heavy Javascript-based applications. We're doing this for some charting/dashboard systems and a management application that puts a lot of functionality into a single browser window.

How do you choose?

Pick the best tool for the job, accounting for your priorities.

If there's already an application that does exactly what you need, use it.

If you need a custom web application, and need to manage users, objects, authentication/authorization, workflow, and other common features, consider using Drupal as a framework.


Wednesday, December 30, 2009

Installing RMagic in fedora

To install RMagic gem for graphic operations in fedora os follow the below instructions
open terminal by Application -> System Tools -> Terminal
login as root by giving command su
#su
#password: enter root password
goto ruby path
#cd usr/lib/ruby
issue the below command
[root@localhost ruby]
gem install rmagick --no-rdoc --no-ri
you should see the below message if successfully installed RMagic gem
Building native extensions. This could take a while...
Successfully installed rmagick-2.12.2
1 gem installed
To see the gem in your local gems list issue the below command
[root@localhost ruby]# gem list --local

*** LOCAL GEMS ***

actionmailer (2.3.4)
-------------------
-------------------
Rmagic(2.12.2)
------------------
etc.,

For Windows users
c:\> gem install rmagick-2.0.0-x86-mswin32.gem

Bydefault gem install will look for the particular gem name in rubyforge site.
You can also mention the path for git repository if the gem is available in github.

Thursday, December 24, 2009

Rails error: initialize_without_backlog': Address already in use - bind(2)

When try to start the webserver for the application some times this error may happen. This happen when you already run any application in the same port number. Make sure you are not running any other rails application with that same web server in the same system.

If you already start the server one one application, stop it for that application and run for the new application you want.

Good Luck -:)

Wednesday, December 23, 2009

Item Stock Availability check for oscommerce

Availability contribution allows you to set an unique message to
display on each product relating to the availability of the item.
Two messages can be set, one for in-stock and another for out of stock.
Includes convenient admin tool to add and modify the messages
menu on the product edit page. Allows you to include the actual
stock quantity in the message.

donwload this addon from below url
http://addons.oscommerce.com/info/4948

Userfull admin features in oscommerce

Here are few of the features available for the siteadmin in oscommerce.

Manage administrators
Manage Administrators including add new admin, or edit / delte admin information.

Manage customers
View and manage the customers registered to the site

Manage orders
Process and Manage orders made by customers

Categories, subcatagories and products
Managing all categories, subcategories and products in the site. Site admin can add/ edit or delete catgories, subcategories and products.

Product Attributes
Managing all product attributes like color, price etc.,

Product Reviews
View the statistics of each product reviewed by customer

Multilanguage
Site was entirely in multilanguage. Admin can manage the content for each locationization.

Reports
View the reports of products viewed, products purchased

Send Emails
Sending emails to customers

Monday, December 21, 2009

Best Employee Award



I got Best Employee of the year 2008 award on December 14th 2009. I had a warm hug with my CEO.

Wednesday, December 16, 2009

PHP sending emails with gmail smtp to prevent spam mails

1 Download PHPMailer from http://phpmailer.sourceforge.net
2 Extract to folder phpmailer
3 Create a file email.php
4 Paste this code and change the values in blue as you need (I modified the sample code given on the PHPMailer homepage)

require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
IsSMTP(); // send via SMTP
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "username@gmail.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$webmaster_email = "username@doamin.com"; //Reply to this email ID
$email="username@domain.com"; // Recipients email ID
$name="name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "Webmaster";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"Webmaster");
$mail->WordWrap = 50; // set word wrap
$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
$mail->IsHTML(true); // send as HTML
$mail->Subject = "This is the subject";
$mail->Body = "Hi,
This is the HTML BODY "
; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>

5 Open the file class.smtp.php in phpmailer directory
6 Paste this code
$host = "ssl://smtp.gmail.com";
$port = 465;
before the line 104 #connect to the smtp server
Hint: Search for #connect
7 Open this page in browser and it will send the email using GMail.

Hint: When you want to email the details from a form, set the variables using the form variables.
eg. $mail->Username=$_POST['email']

Thursday, November 26, 2009

Jquery datagrid for rails applications


With jquery grid plugin along with 2dcJqgrid Rails plugin are awesome for creating datagrids in rails applications which allows users to navigate, search, add/ edit / delete operation in one place.
See the sample screenshot above.

Rails Developement Standards

Application must be under version control. Use SVN
Never put log files or database.yml file into subversion.
Use either Postrgres, Oracle or Mysql for your db.
Session data should be stored in the database
Migrations should NOT contain any db specific SQL.
Use Rspec for testing. Rspec is available as plugin
Application must have Unit and Functional tests.
All application gems should be installed in RAILS_ROOT/vendor/gems folder
Always freeze rails, ( Fix For rails freeze gems )
If your application uses CAS authentication, use the ucb_rails_security plugin
Controller Methods should be no longer than 5-8 lines of code. If you find your self with really large controller methods you are probably violating the following standard.
Application domain logic should go into the model, NOT in the controller or view.
Try to limit each controller's actions to: index, new, create, edit, update, destroy. This is not always possible. However, if you notice that a given controller has more than 10 methods, it probably time to refactor.

Preventing open a new window for each folder in linux

1. Double-click on the "Computer" icon on your desktop.
2. Go to the "Edit" menu and choose "Preferences."
3. Click on the "Behavior" tab.
4. Put a check in the box marked "Always open in browser windows

Sending Tons of emails from your Ruby on Rails Application

A correct way to send tons of massive emails from your website is queuing the emails and send them one by one. If you send all at once directly from your site some hosting servers may allows only some amount of emails per hour. Shared hosting servers allow you send only 25 emails from your site per hour. Fortunately there is one plugin available for Rails which can store the outgoing emails in database as a queue and send them eventually. That plugin is called ar_mailer you can install it and send tons of emails happlily. See the process of how to install and more at http://www.ameravant.com/posts/sending-tons-of-emails-in-ruby-on-rails-with-ar_mailer

Ruby on Rails Easy roles plugin

Easy roles is a plugin for Ruby on Rails which is very usefull for your site if it has lot of roles. So by using this plugin you can restrict the access to controllers based on the roles. Follow the below process to install it for your application.

cd yourappname

ruby script/plugin install git://github.com/platform45/easy_roles.git

Now the plugin is installed in your vendor/plugins folder

Below is the Basic Setup process you need to do after plugin installed successfully
Add the following to your enviroment.rb in the rails initializer block
config.gem 'easy_roles', :source => 'http://gemcutter.org'

Add a "roles" column to your users model, and set the default value to "--- []". Please note you can call this column anything you like, I like to use the name "roles" for meaning full.

For users table migration table add below
t.string :roles, :default => "--- []"

Then you need to add "easy_roles :column_name" and some logic to your model.


class User < ActiveRecord::Base

# Serialize roles as an array
serialize :roles, Array

# Create an empty roles array on create
before_validation_on_create :make_default_roles

# Convenience method, is user an admin?
def admin?
has_role?("admin")
end

# Checks to see if a user has requested role
def has_role?(role)
roles.include?(role)
end

# Add a role to a user
def add_role(role)
self.roles << role
end

# Remove a role from a user
def remove_role(role)
self.roles.delete(role)
end

# Clear all users roles
def clear_roles
self.roles = []
end

private
def make_default_roles
clear_roles if roles.nil?
end
end

And thats it.
The above model gives you the options like below in controllers
@user = User.first
@user.add_role 'admin'
@user.save!

@user.has_role? 'admin'
=> true

@user.admin?
=> true

@user.remove_role 'admin'
@user.save!

@user.admin?
=> false

Usage
Easy roles extends your model, and adds a few methods needed for basic role authorization.

adding a role to a user
add_role 'role'

removing a role from a user
remove_role 'role'

check to see if a user has a certain role
has_role? 'role'
# or
is_role? # role being anything you like, for example 'is_admin?' or 'is_awesome?'

== Examples

@user = User.first

@user.add_role 'admin'

@user.is_admin?
=> true

@user.has_role? 'admin'
=> true

@user.is_awesome?
=> false

@user.add_role 'awesome'

@user.is_awesome?
=> true

@user.remove_role 'admin'

@user.is_admin?
=> false

etc etc

== Protecting controllers

There are many ways to implement views for specific roles, so I did not specifically supply one. Here's an example on what you could do:

class ApplicationController < ActionController::Base

def admin_required
unless current_user && current_user.is_admin?
flash[:error] = "Sorry, you don't have access to that."
redirect_to root_url and return false
end
end

end

Then in your AdminsController or any controller that you only want admins to view:

class AdminsController < ApplicationController
before_filter :admin_required
end

class MarksController < ApplicationController
before_filter :admin_required, :only => :create, :update
end

check out more information at
http://blog.platform45.com/2009/10/05/howto-basic-roles-for-users for implementation

World's Famous IDE eclipse's support for PHP

Hi,
If you already installed eclipse in your system then you have to update it for php support. To do so follow the below steps
1. Open the eclipse IDE
2. Then goto menu Help -> Software updates
There you see Two main tabs Installed softwares and Available softwares. If phpeclipse is not there in installed softwares list then check in Available softwares list. If not avaliable there also Then click on Add site and enter below url.
http://update.phpeclipse.net/update/stable/1.2.x
Then that eclipse's update url is added to available softwares list. Check that module and click install. It will take few minutes and install phpeclipse and PDT (PHP Development Tools) to your existing eclipse IDE.
After installed successfully Goto menu Window -> open perspective
and select PHP to start working on PHP Projects.

The process is same to enable any other technologies support in eclipse for developing applications.

If you are not installed eclipse IDE in your system then you can directly install it from the official website http://www.eclipse.org/