Thursday, October 31, 2013

OnHover Dropdown menu in Bootstrap

Bootstrap DropDown menu works on mouse click event. It doesn't support on hover DropDown by default. But using following bootstrap plugin we can make it works for mouse hover event and it's so simple.

http://cameronspear.com/blog/bootstrap-dropdown-on-hover-plugin/



Download the plugin, include it in your project. We write data-toggle="dropdown" in the markup to make it a dropdown menu which works on click event. Instead of that one, write data-hover="dropdown" and you are done. Now both options will work on your project.

Tuesday, September 17, 2013

Uploading file using AJAX in Rails

Paperclip gem can be easily used in your rails application for uploading file. But to make it functional using ajax, we can use remotipart gem which works pretty smoothly with Paperclip gem. Just install the remotipart gem. Prepare your form using Paperclip for uploading file. Then add remote=>true in that form. And your form is ready to upload file using ajax. Implementation details can be found in the following links.

Thursday, September 12, 2013

Attachment in Rails using Paperclip gem

It always requires extra effort to setup your form for uploading files. Paperclip is a wonderful gem which can save your extra effort for that task. Just install the gem, add necessary fields in model including file field, and last of all add multipart => true in your form. Then your application is ready for uploading file. Most of the required options related to uploading file are available in this gem. You can find implementation details in following links.

Friday, August 30, 2013

Tagging in Rails

A very simple plugin to implement tagging feature in rails application is acts-as-taggable-on. Install the gem, specify the field in the model on which you want to put tags, add a tag field in the form, and you are ready to tag your model object. Implementation details can be found in following links.

https://github.com/mbleigh/acts-as-taggable-on

http://railscasts.com/episodes/382-tagging
http://alexmuraro.me/posts/acts-as-taggable-on-a-short-tutorial/

Popularity of this plugin can be found in The Ruby Toolbox -
https://www.ruby-toolbox.com/categories/rails_tagging

Limiting loop for array of objects in Rails


While fetching records from DB, we can definitely limit the number of records to fetch as following.
@post.comments.limit(10).each do |comment|
   comment.description
end
But in practical, sometimes we face that we have an array of objects fetched from DB and we want to access first or last few objects. Using following code we can easily solve it. 

Reading first 10 records -
@posts.first(10).each do |post|
   post.title
end
Reading last 10 records -
@posts.last(10).each do |post|
   post.title
end

Wednesday, August 7, 2013

Creating Page and Subpage in Wordpress

Creating Page

Step 1: Login as admin. It will show you admin dashboard (admin panel).


Step 2: Go to Pages link and press Add New link.


Step 3: Enter page Title that will be shown in your page as page title. For this example, you can give hello world. In the description box, write some text that you want to show in your page, for now you can write “hello world page crated successfully”.

Step 3: Click on the Publish button on right sidebar and your page is ready to view. If you do not want to show this page in your website then do not publish it, just save it as draft using Save Draft button on left top corner.


Step 4: Go to wordpress site from your browser and you will see hello world link in the manu bar. Click that link and it will show you the page that you have just created.


Creating Subpage

We want to create a page which will be a subpage of our previous hello world page. Follow the steps of creating page, go to the page creation form. On the right side, Parent option of Page Attributes is used to create subpages. Parent option shows all created pages. While creating page, you have to select a page here to make it parent of the creating page. In our case, we choose “Hello World” page so that it would be a subpage of our hello world page.


Give the page title and its content in the appropriate places and publish the page. If we visit the site, this subpage link will appear under hello world link and using that link we can browse that page.



Sunday, August 4, 2013

Installing and Running Wordpress using XAMPP

Few steps to install wordpress using XAMPP are as following:

Step 1: Create a database for wordpress without table. You will need database name, username, password, etc. later to setup and use wordpress.

Step 2: Download wordpress zip from its website - http://wordpress.org/download/.

Step 3: Extract zip and copy wordpress folder in your /xampp/htdocs folder.

Step 4: Rename file  wp-config-sample.php to wp-config.php under wordpress folder.

Step 5: Edit this config file to enter database information. Following information will be needed to modify in config file –
  • DB_NAME - your wordpress database name.
  • DB_USER – database username.
  • DB_PASSWORD – password for given database username.
  • DB_HOST – address of the database, for local pc it will be localhost or 127.0.0.1 .
Step 6: From your browser go to wordpress (http://localhost/wordpress). It will ask you to give some information to setup wordpress. Give necessary information and submit. After configuring wordpress it will redirect you to a page showing success message and you are ready to use wordpress.

For installation details, you may visit wordpress official installation guide here - http://codex.wordpress.org/Installing_WordPress

Sunday, September 19, 2010

Reading excel file in java with JXL api

We can use JXL api to read/write/edit an excel file. Here in this article we are going to see how to read an excel file using this api.

First of all you have to download the api and add the path of jxl.jar into the system classpath .

Then the simple following code will read all the cell values from the excel file and will print into the console.

import java.io.*;
import java.util.Scanner;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcel {
    // method that read the excel file and print all it's cell values
    public void readFile(File file) {
        try {
            Workbook wb = Workbook.getWorkbook(file);    // get the excel work book
            // from book you can select sheet and work on it
            // here we are taking the first sheet for our example 
            Sheet sheet = wb.getSheet(0);                
            
            // travel all cells in the selected sheet
            for(int i=0; i < sheet.getRows(); i++) {
                for(int j=0; j < sheet.getColumns(); j++) {
                    Cell cell = sheet.getCell(j, i);                        // get a particular cell
                    System.out.print(cell.getContents() + "\t");    // print cell content
                }
                System.out.println();
            }
        } catch (BiffException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        // read the file path that you want to read from console
        Scanner in = new Scanner(System.in);
        String file = in.nextLine();
        
        // initiate the ReadExcel class and call the method to read the file
        ReadExcel re = new ReadExcel();
        re.readFile(new File(file));
    }

}


If you need more information regarding this you may visit this link - http://www.vogella.de/articles/JavaExcel/article.html

Monday, August 23, 2010

Setup google analytics to observe your blogger(blogspot) blog

You may want to view the statistics of your blog and there are many providers from which you can see it. But if you are using blogger(blogspot) then you can follow this link to setup google analytics for your blog and see its statistics. I am using it for my blog too and its pretty cool and interesting.

Finding time difference in Ruby

Finding time difference between two dates or times is very simple in ruby. It is just like doing arithmetic subtraction. We can do it for different formats in the following way:

Date
d1 = Date.parse("2010-08-23")
d2 = Date.parse("2010-08-24")
day_diff = (d2 - d1).to_i     # returns number of days

DateTime
dt1 = DateTime.strptime("2009/04/16 19:52:30", "%Y/%m/%d %H:%M:%S").to_time
dt2 = DateTime.strptime("2009/04/17 19:52:30", "%Y/%m/%d %H:%M:%S").to_time
time_diff = dt2-dt1    # returns time difference in seconds

Time
t1 = Time.parse("2010-08-24 01:20:00")
 t2 = Time.parse("2010-08-24 05:20:00")
time_diff =  t2-t1        # returns time difference in seconds

Friday, August 20, 2010

Using MS Access in Rails application

There is no default support to use MS Access database with our Rails applications. Among many solutions while googling, I have found 2 solutions which can be easily used and managed in our projects. These solutions can be found in the following links –
  1. http://blog.behindlogic.com/2007/07/msaccess-for-rails-heres-your-rough.htm
  2. http://rubyonwindows.blogspot.com/2007/06/using-ruby-ado-to-work-with-ms-access.html

Solution one is more preferable than the second one. Using this solution we can do same operations that we do using ActiveRecord.
If you could not use the solution one for your expected result then you can use second solution. But this solution is not that much intuitive. Using this solution, if you want to any operation then you will need to write SQL yourself.

Thursday, October 30, 2008

Make Activemessaging Working on Rails 2.1.0

Few days ago we had updated the application on which project currently I am working to make it compatible with rails 2.1.0. Previously we were using rails 1.2.5. In our application we have mail sending module for which we are using activemessaging plugin. It was working fine on previous version. But, unfortunately on new version it was not working. We thought that we made some mistake while updating to the new version. The problem was the poller was not starting and it was showing the following message when we were trying to run the poller-

Dispatch exception: undefined method `prepare_application' for #Dispatcher:0xb6d9ffec>
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/support.rb:8:in `prepare_application_for_dispatch'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/gateway.rb:189:in `prepare_application'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/gateway.rb:199:in `dispatch'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/gateway.rb:197:in `synchronize'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/gateway.rb:197:in `dispatch'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/gateway.rb:93:in `stop'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/gateway.rb:90:in `start'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/gateway.rb:90:in `stop'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/gateway.rb:80:in `each'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/gateway.rb:80:in `stop'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging/gateway.rb:67:in `start'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/lib/activemessaging.rb:108:in `start'
/mnt/app/releases/20081017130017/vendor/plugins/activemessaging/poller.rb:14
/var/lib/gems/1.8/gems/daemons-1.0.10/lib/daemons/application.rb:176:in `load'
/var/lib/gems/1.8/gems/daemons-1.0.10/lib/daemons/application.rb:176:in `start_load'
/var/lib/gems/1.8/gems/daemons-1.0.10/lib/daemons/application.rb:253:in `start'
/var/lib/gems/1.8/gems/daemons-1.0.10/lib/daemons/controller.rb:72:in `run'
/var/lib/gems/1.8/gems/daemons-1.0.10/lib/daemons.rb:139:in `run'
/var/lib/gems/1.8/gems/daemons-1.0.10/lib/daemons/cmdline.rb:105:in `call'
/var/lib/gems/1.8/gems/daemons-1.0.10/lib/daemons/cmdline.rb:105:in `catch_exceptions'
/var/lib/gems/1.8/gems/daemons-1.0.10/lib/daemons.rb:138:in `run'
script/poller:21


After googling I found that the plugin has a problem to work with rails 2.1.0. http://groups.google.com/group/activemessaging-discuss/browse_thread/thread/41989b6599146ba4- - in this site you will find the details. After replacing the content of vendor/activemessaginglib/activemessaging/support.rb with the following code the poller was working fine -

require 'dispatcher' unless defined?(::Dispatcher)
::Dispatcher.class_eval do
def self.prepare_application_for_dispatch
new(STDOUT).reload_application
end

def self.reset_application_after_dispatch
new(STDOUT).cleanup_application
end
end

It is really bad if someone needs to do such things to make the plugins working while updating any project to any newer rails version.

Tuesday, September 30, 2008

Reading attributes value of an Xml node

It is common to read the attribute of an xml node while trying to read xml files. Lets we have an xml like below -


We can write the following code to read the value of the attribute “id” of the first customer –

// Load the xml file
XmlDocument doc = new XmlDocument();
doc.LoadXml(Resources.XMLFile);

// Read the first customer element
XmlNode customer = doc.DocumentElement.SelectSingleNode("customer");

// Initialize the reader using the customer node
// from where need to read attributes
XmlNodeReader reader = new XmlNodeReader(customer);
reader.Read();

// Read the attribute named - "id"
string id = reader.GetAttribute("id");
Console.WriteLine(id);

The output of this program is "123". I find it helpful during working one of my project and I think it will also help you. You can also read this value very easily if you use LINQ in C# 3.0.

Saturday, July 12, 2008

Exporting and Importing to CSV File in Rails

CSV file format is very popular when we want to give option to export or import tabular data in our application. Rails has a very good support to do this. In this post I will discuss both exporting and importing to CSV file in Rails application.

For our export and import purpose, we will use a table named USERS which is like below:


Import From CSV:

Import information from any comma separated CSV file is so simple in Rails. Here, we want to import user information to insert users in our USERS table and the information into CSV file is like below:



To import this we need a view from where we can submit our CSV file through a multipart form. Here is a simple form view:


<% form_tag url_for(:controller => "export_import", :action => "import_user_from_csv"), {:multipart => true} do -%>

<%= file_field_tag :csv_file -%>

<%= submit_tag 'Import' -%>

<% end -%>


After submitting this form it will goes to the specified action(in our case it will goes to controller: “ExportImportController” and action: “import_user_from_csv” ) from where we will actually import the necessary information from the file uploaded. The code of the action is like below:


require "csv"
class ExportImportController < style="font-style: italic;">
def index

end

def import_user_from_csv
# parse the csv file using ruby "csv"-librarty
parsed_file = CSV::Reader.parse(params[:csv_file])

# print all rows of the csv file into the log file
parsed_file.each do |row|
logger.info "Information From CSV >> Id : #{row[0].inspect} Name: #{row[1].inspect} Email: #{row[2].inspect}"
end


redirect_to :action => :index
end
end


Here one important thing is that, we are using require "csv" which library provides us option to parse csv file.

I am not showing how to insert this information into Database. Because, once we have all information on our hand, we can play with it in any way we want. I am just giving an idea. Place the following code into the loop(parsed_file.each do |row|):


if(User.exists?(row[0]))
User.update(row[0], {:name => row[1], :email => row[2]})
else
User.create(:name => row[1], :email => row[2])
end


Above line will insert information into USERS table. But, we can not use it directly in our application as we need to handle all kind of exceptions.


Export to CSV:

There is a FasterCSV ruby library which provides easy way to export our information to CSV file. To use it you can install gems using “gem install fastercsv” or download it from http://fastercsv.rubyforge.org/ and extract it to RAILS_HOME/vendor/plugins/fastercsv.


Suppose we want to export all users of USERS table to CSV file. FasterCSV provides a output stream in which we can insert arrays as rows(one array one row) to CSV file using “<<”. Once we have the streaming data we can send it to the browser.


Following code can be used to export all users to "users.csv":


class ExportImportController < ApplicationController
def export_users
# get all users from user table
users = User.find(:all)

# generate the streaming data
csv_string = FasterCSV.generate do |csv|
csv << ["Id", "Name", "Email Address"]
users.each do |user|
csv << [user.id, user.name, user.email] end
end

# send csv file(users.csv) to browser
send_data(csv_string, :type => 'text/csv; charset=utf-8; header=present', :filename => "users.csv")
end
end