Pages

Tuesday, May 8, 2012

Jquery is not defined

You might get this error while integrating jquery in your appplication.Scripts will not get invoked.

I have to include Datepicker for a field in a page.

var $j = jQuery.noConflict();
$j(document).ready(function($) {
});

Got the error "jQuery is not defined"

Just changed order of the script which i included in the application. The error got resolved :)-

<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" %>

<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js" %>

<%= stylesheet_link_tag "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css" %>

The order in which you load your scripts is important


Tuesday, May 31, 2011

Company and Jobs - LinkedIn API

Now we can get company & job information available in LinkedIn using its API.This might help to show up the company & job deatils in applications.View .

You can check the below URL's by using a simple java program

Links to get company information in combination with LinkedIn data
1. To get the company information by giving the company domainhttp://api.linkedin.com/v1/companies?email-domain=kyyba.com
Output :



586336
Kyyba Inc


2. To get the company information by giving the company id
http://api.linkedin.com/v1/companies/586336:(id,name,description,industry,logo-url)

output :



586336
KYYBA Inc
Kyyba, Inc. is a Global provider of strategic staffing and managed services for the Information Technology and Engineering Clients
Kyyba service lines provide customers the following services:
Product and Software Development Services
Engineering and Design Services
Staff Augmentation Services
Outsourcing Services

Staffing and Recruiting
http://media.linkedin.com/mpr/mpr/p/2/000/050/2e0/322206a.png


3. To get the companies around the given area [us:84] http://api.linkedin.com/v1/company-search:(companies,facets)?facet=location,us:84 Output :






1028
Oracle

.
.
.



location
Location


us:0
United States
596338
false

.
.
.





4. To get company in which the token is createdhttp://api.linkedin.com/v1/people/~/following/companies

Output :





96307
Vision Tech Solutions


5. To get company to follow by the current userhttp://api.linkedin.com/v1/people/~/suggestions/to-follow/companies
I didn’t get any output data .

Links to get LinkedIn's jobs by company, industry and more to display relevant jobs to the users.
1. To get some job information in LinkedIn for the user
http://api.linkedin.com/v1/people/~/suggestions/job-suggestions
Output :






1641017

1333802

1441
Google


5EyneQPD-C
David
S.
test at Test Advantage

This position is based in Bangalore, India.
The area: Google.com EngineeringGoogle.com Engineering makes Google's services fast and reliable for hundreds of millions of users. Described as "software engineering for adrenaline junkies", the team combines software development, networking, and systems administration expertise to build and run massively distributed, fault-tolerant software system

Bangalore

.
.

50


2. To get some job information exsisiting in given area [US:84]http://api.linkedin.com/v1/job-search:(jobs,facets)?facet=location,us:84
Output :






1653582

1231
Symantec

Best in Industry

YRNg4JA8HX
Shyam Sundar
V.
Principal Recruiter at Symantec

 Symantec R&amp;D in Pune has Senior Principal Software Engineer positions open. Interested and suitable candidates can apply. Role Details: Research and drive the adoption of new technologies to enhance existing product functionality • Provide technical vision and leadership necessary to grow the technical proficiency of the development teams• Mentor development teams in good architecture and des
Pune, Maharashtra

.
.

3. To get the particular job information by giving the JobId [jobid=1653560]
http://api.linkedin.com/v1/jobs/1452577:(id,company:(name),position:(title))
Output :




1653560

Tata Consultancy Services


Siebel Architect- Performance Management


4. To get some job bookmarcks
http://api.linkedin.com/v1/people/~/job-bookmarks

I didn’t get any output data .

Simple Java Program using LinkedIn API

The below program will helps you to fetch & view linkedIn data in a short time.

Follow this link to download the jars & to get token, secret to work with LinkedIn API

Simple Java Program. To get the LinkedIn details about the current user [Who created the token & secret key]


public static void main(String[] args) {

String linkedinKey = "C2E7PG.."; //Your LinkedIn key
String linkedinSecret = "9hyC6.. ";//Your LinkedIn Secret
OAuthConsumer consumer = new DefaultOAuthConsumer( linkedinKey,linkedinSecret);

OAuthProvider provider = new DefaultOAuthProvider("https://api.linkedin.com/uas/oauth/requestToken",
"https://api.linkedin.com/uas/oauth/accessToken",
"https://api.linkedin.com/uas/oauth/authorize");

System.out.println("Fetching request token from LinkedIn...");
String authUrl;
try {
authUrl = provider.retrieveRequestToken(consumer, OAuth.OUT_OF_BAND);
System.out.println("Check the below link and grant this app authorization -You will get Pin Number.Copy it\n" + authUrl );
System.out.println("Enter the PIN code and hit ENTER when you're done:");
} catch (OAuthMessageSignerException e1) {
e1.printStackTrace();
} catch (OAuthNotAuthorizedException e1) {
e1.printStackTrace();
} catch (OAuthExpectationFailedException e1) {
e1.printStackTrace();
} catch (OAuthCommunicationException e1) {
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String pin;
try {
pin = br.readLine();
System.out.println("Fetching access token from LinkedIn...");
provider.retrieveAccessToken(consumer, pin);
System.out.println("Access token: " + consumer.getToken());
System.out.println("Token secret: " + consumer.getTokenSecret());
URL url = new URL("http://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,headline)");

HttpURLConnection request = (HttpURLConnection) url.openConnection();
consumer.sign(request);
request.connect();
System.out.println("Sending request to LinkedIn...");
String responseBody = convertStreamToString(request.getInputStream());
System.out.println("Response: " + request.getResponseCode() + " "
+ request.getResponseMessage() + "\n" + responseBody);

} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}


Output

Fetching request token from LinkedIn...
Check the below link and grant this app authorization -You will get Pin Number.Copy it
https://api.linkedin.com/uas/oauth/authorize?oauth_token=dcb835667-a5d7-4e95-91f9-fde4b9b47e3a
Enter the PIN code and hit ENTER when you're done:
59278
Fetching access token from LinkedIn...
Access token: f0f94b3d-50b9-4549-bd96-5d1ea3ba7a9c
Token secret: f2b13c99-f206-4612-bf9e-2afc1387bc1a
Sending request to LinkedIn...
Response: 200 OK



GtYKzPiNkX
Sundari Shree
Gunasekaran
Software Engineer at Vision Tech Solutions


Note: By passing the different URL’s as parameter You can check all the available information in LinkedIn .

URL url = new URL("http://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,headline)");

This URL is to get about the people information.

Monday, April 11, 2011

GoogleMap - Latitude and Longitude

I have to display the map with respect to the place given.

In that tags the longitude and latitude of the location to be passed as parameters to get the exact location in Map.

I got many examples for displaying the Google map in different way & special effects. But not able to find how get the longitude and latitude of a location/place. At last found the way. Might help someone who searches like me.

Code: To get the Longitude & Latitude of the location

To have Google map in an application. We have to get a key from this link
http://code.google.com/apis/maps/signup.html



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


try {

String locationName="johannesburg"; \\Give any location\place name
String gmapKey="ABQIAAAAiqblAQNWNoua1VYnGtU1dBRdtL7gCpXlU8FuabFvwIMVSlhRL4gzsM_7WZ6hbScCw1YuLXHNjwA"; \\Give your google map key
URL url = new URL("http://maps.google.com/maps/geo?q="+locationName+"&output=csv&key="+gmapKey);
URLConnection urlConnection = url.openConnection();
BufferedReader in;
String inputLine;
String data =null;

in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = in.readLine()) != null){
data =inputLine;
System.out.println("Accuracy,Status,Latitude,Longitutude of " +locationName+" >> "+data);
}
in.close();

}
} catch (IOException e) {
e.printStackTrace();
}


output:

Accuracy,Status,Latitude,Longitutude of johannesburg >> 200,4,-26.2041028,28.0473051

Monday, February 21, 2011

Bitly using Mashape

Mashape is an API marketplace where service providers and individual developers can instantly make available an API.Its FREE to use.

Mashape can used in 2 ways

1. Making use of the featured API’s available in Mashape
2. To generate our own API using Mashape.We can upload our API in Mashape & push it into cloud.They are providing the infrastructure for generating the API.

I tried out the first way, which I need currently to work on
Check the featured services provided by Mashape -Explore.
They are in ready to use state.Avaiable in Ruby, Java, Python, PHP Obj-C, and JSON

I tried out with SimpleGeo and Bitly.

Steps to work on Bitly using Mashape :

Step1: SignIn Mashape.Get the API key.It's an automatically generated key which allows you to use the Mashape API from an application. [Ex:API key will be like this APP Key : sgFFDCfgEOKsLMsO9X7l75gCI]


Step2: Download the featured Bitly API from Mashape .
The Jar will contain Bitly component's Java client library will contain the following files:

- mashapeClient.jar - This file to be include in the project, that contains the core
functionalities of every Java client library and that is
immutable for every component.
- Bitly.java - The auto-generated *.java file for the component, that
declares a Bitly class.
- LICENSE - README

Step3 Download the following jars to work on all the above API's using Mashape.

- httpclient-4.0.jar
- httpcore-4.0-beta3.jar
- json-rpc-1.0.jar
- json-20080701.jar

Step4 Signup in Bitly & get the bitly-login and bitly-Api-key.

Step5 Code:

//Enter Mashape API key
Bitly bitly=new Bitly("sgFFDCfgEOKsLMsO9X7l75gCI ");

//Pass the url to be shortened, bitly-login and bitly-Api-key &it returens the JSONObject

JSONObject bitlyResponse = bitly.getShortenedUrl("http://sundarishree.blogspot.com/","shree","R_08de4b3475dd5655818230c15c4966471");


Advantage of this Mashape is no need to download the API jar from different sites. We can get in one point.

Monday, February 7, 2011

Session in PHP

This post might help the newbie to work on session in php.

1. Start up the session

session_start()
Function must appear before the html tag.Its initialize session data
Example :


.
.


2. Store a session variable
Example:

session_start();
$_SESSION['username']="Misty"; // store session data
?>

echo "Name =". $_SESSION['username']; //retrieve session data
?>


Where ever we try to access[Store or Retirve] the session variable the
session_start() function has to be called once before accessing the
session variable.

3. To delete the session data

The unset() function is used to free the specified session variable:
Example:

unset($_SESSION['username']);
?>


4. To destroy the session
We can completely destroy the session by calling the session_destroy()
function
Example:

session_destroy();
?>

session_destroy() will reset the session and We will lose all the stored session
data.

5. To check whether the session variable is null
Example:

is_null($_SESSION['username'])==true


6. Some of the Session Functions
session_cache_expire — Return current cache expire
session_cache_limiter — Get and/or set the current cache limiter
session_commit — Alias of session_write_close
session_decode — Decodes session data from a string

session_encode — Encodes the current session data as a string
session_get_cookie_params — Get the session cookie parameters
session_id — Get and/or set the current session id
session_is_registered — Find out whether a global variable is
registered in a session
session_module_name — Get and/or set the current session module
session_name — Get and/or set the current session name
session_regenerate_id — Update the current session id with a newly
generated one
session_register — Register one or more global variables with
the current session
session_save_path — Get and/or set the current session save path
session_set_cookie_params — Set the session cookie parameters
session_set_save_handler — Sets user-level session storage functions
session_unregister — Unregister a global variable from the
current session
session_write_close — Write session data and end session
7. To check the page expiry using session
Example:

session_start();
ini_set('display_errors', true);
ini_set('display_startup_errors', true);
error_reporting (E_ALL);
session_cache_expire( 20 );
$inactive =250;
if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){header("Location:login.php?errorMsg=Your session
has expired.Please login again.");
}
}
$_SESSION['start'] = time();
?>

This code has to placed in the pages in which we need to check for session
expiry [Session expires beyond 4 mins].


8. ERRORS -> While working on sessions in PHP you might
come across
the following errors. I got these 2 errors.

8.1 Warning: session_start() [function. session-start]: Node no
longer exists in C:\wamp\home.php on line 3

occurs if a object is taken from a xml file or format.

Cannot serialize object wrapping 3rd party library structs. Must serialize
the xml (to a string) and store that to session and reload the xml when
restoring from session
Example

session_start();
/*To get from the mail.xml */
$xml = simplexml_load_file("../mail.xml");
foreach($xml->children() as $child){
if($child->getName()=='servername'){
$servername=$child;
}else if($child->getName()=='dbname'){
$dbname=$child;
}else if ($child->getName()=='username'){
$username=$child;
}else if ($child->getName()=='password'){
$password=$child;
}else if ($child->getName()=='url'){
$url=$child;
}
}
$_SESSION['url']=(string)$Url; // Casting is required


8.2. The following error might occur when we try to re-direct the page from one
page to another.

Warning: Cannot modify header information – headers already
sent by (output
started /home/kvel/kyybaventures.com/laton_v/views/leftnav.php:28) in
/home/kvel/kyybaventures.com/laton_v/views/welcome.php on line 10


The problem is mainly due to the header start writing the output and again
trying to resent the header information. Normally when we use echo statement
before the header, this type of problem will come. It will not reflect in
the development environment and if try to deploy the code in the remote
server, this problem used to occur. Even if you remove the echo statement
and still the problem persist, follow the below solution.

To get rid of this error use these two lines

  

at the start of the php file and

 

at the bottom of the php file where you got the above error.

Wednesday, January 12, 2011

Searching for PAAS providers

In near future I think everything in the IT going to be virtual. Its going to play a main role in transforming IT infrastructure toward cloud computing.

In 2011 many more enterprises virtualized and get onto private cloud journey as next step.
Surely will be great competitions between the Cloud Service providers.

We too trying to get into cloud service .As a first step our team is searching for PAAS providers which suits to develop our social media based application. We are trying for a provider which supports java.

Did some analysis on Bungee connect, Joyent & WSO2.

Regarding,
Bungee Connect – They have given as they collects no fees during the entire development process developers can freely access, develop, test, and even conduct on-line focus groups and beta programs for Bungee-powered applications.
After surfing a day, we felt this is best for us. Tried to work with beta .They have not yet released their beta work.
Might be in near future they might release the beta but we can’t wait for it.

Joyent -Fully java script based application can be build. Mainly games are developed using joyent.Having big clients. We can use any sort of editors.Price differs based on the platform .Starting from 1/4GB Standard platform $25 /month to 32GB- $4000/ month. Not having clear view for making the development environment.
Also don’t know whether it suits to build our application.

WSO2 –Specified they offer a complete lean enterprise middleware platform, available as open source.Provided all sorts of download for services like mashups,data service,gadges etc.,.Provided many video files ,tutorials to work WSO2 services.

When we go through the video, tutorial & definifiton it seems like “Spoon
Feeding”.But when tried practically something is missing. Some notch in the flow of integration.
There comes the check they have kept all sort of pricing in the name of support.Showing the great business.

We are trying this as a first application in cloud so we are not ready to afford much on this trial.

Still searching is not completed.

Sunday, January 2, 2011

About CLOUD COMPUTING from a Tenderfoot

I can't say its an IN and OUT about CLOUD COMPUTING.This post might give a light idea for you before start flying into CLOUD.

Cloud computing is making a new trend and revolution for the next generation IT engineers.So many views and definitions are there on internet.This one gives a simple understanding definition for cloud computing

"A pool of abstracted, highly scalable, and managed compute infrastructure capable of hosting end-customer applications and billed by consumption"

Already We are using some kind of cloud ser­vice, such as Web email (Gmail, Yahoo! Mail or Hot­mail),online data stor­age (IDrive, Mozy) or online soft­ware.

Cloud Environment is divided in three segment
SAAS
PAAS
IAAS


SAAS - Software As A Service

Provides software applications to end users without requiring the end user to run the application on their own computer.
Increasingly popular with Small and medium enterprises(SMEs).
No hardware or software to manage .
Service delivered through browser.

Examples of SAAS

CRM
ERP
Project Management
Banking
Spreadsheet

PAAS - Platform As A Service
Is an environment for running custom applications that provides operating-system level services for accessing the hosting and hardware resources needed in a cloud.
Some PaaS have their own dedicated SaaS architecture (For example : Salesforce's Force.com).
Most platforms anyway allow the consumer to choose their own SaaS tools.

Example of PAAS

Google App Engine
Mosso (Hosting cloud service)
AWS: S3(A Ruby Library for Amazon's Simple Storage Service's (S3) REST API)

IAAS - Infrastructure as a service
Is a form of hosting.
It includes network access, routing services and storage.
The IaaS providers will usualy provides the hardware and administrative services needed to store applications and a platform for running applications.


The cloud has become


1.our enter­tain­ment net­work we are spend­ing hun­dreds of mil­lions of hours on sites like YouTube , Flickr and so on.

2.our social net­work Face­book,Bebo, hi5 ,MySpace and sim­i­lar sites now claim hun­dreds of mil­lions of mem­bers.

3.our work­bench we man­age projects in Base­camp, share large files with Pando,tweak pho­tos in online photo edi­tors like Adobe Pho­to­shop Express and Pic­nik.

4.our devel­op­ment net­work open source pro­gram­mers trade code on sites like SourceForge.net and Drupal.org.

Still not started to fly in CLOUD.While I do,surely i will post the next.

Tuesday, September 7, 2010

Create Android Applications in Eclipse

Small intro about Android
Android is one of the most useful, innovative mobile platform.

Android 2.2. Codenamed Froyo (for frozen yogurt), this is the seventh update to the Android platform brings some great new functionality to users (things like making your handset a portable hotspot and support for Adobe Flash within the browser)
, along with new tools for developers.

To know more about Android check out this links

www.android.com/
http://android-developers.blogspot.com

Steps to set the environment for creating Android applications with Eclipse

It is based on Eclipse 3.5 & above, Java 1.6 and Android 2.2 (Froyo).

Step- 1 Install Eclipse Galileo (3.5)

Step- 2 Download the Android SDK from the Android homepage under Android SDK download .The download contains a zip file which you can extract to any place in your file system.
e.g. place it under "c:\android-sdk-windows"

Step-3 Open the Help -> Install new software .To install all available plugins for the Android Development Tools (ADT) from the URL https://dl-ssl.google.com/android/eclipse/

Step-3.1 Add the Name as Android & Location of the site as https://dl-ssl.google.com/android/eclipse/

Step-3.2 Select the packages & click Next

Step-3.3 Select the agree option & click finish

Step-4 To Configure in Eclipse - Open the Preferences dialog via Windows -> Preferences.Select Android and maintain the installation path of the Android SDK.



Step-4.1 Select now Window -> Android SDK and AVD Manager from the menu.


Step-4.2 Select the following available packages and select the latest version of the SDK.

-Documentation for Android SDK,API8 ,revision 1

-SDK Platform Android2.2,API8,revision 2

-Samples for SDK API8 ,revision 1h

Step-4.3 Press "Install selected" and confirm the license for all package.Installation will be started.After the installation restart Eclipse.

Step-5 We need to define a device which can be used for emulation.Select now Window -> Android SDK and AVD Manager from the menu -> Select Virtual Devices .Press "New" and maintain the following.



Step-5.1 Press "Create AVD".This will create the device. To test if you setup is correct, select your device and press "Start".


Step-5.2Device is ready .

Now the environment is ready for developing android application.

Thursday, August 26, 2010

Shortening URL in Java using Bitly

Bitly
Shortening any url in Java using bitly API .
We need to get API key first using bit.ly account

In two ways we can do
1. By calling the bit.ly's REST API.
2. By using bitly core methods.

1. By calling the bit.ly's REST API

We need the following jars to work on

bitlyj-2[1].0.0
commons-httpclient-3.1
commons-codec-1.2
logging-1.0.4

Code to shorten the url

HttpClient httpclient = new HttpClient();
HttpMethod method = new GetMethod("http://api.bit.ly/shorten");
NameValuePair[] valuePair=new NameValuePair[]{new NameValuePair("longUrl","http://www.sundarishree.blogspot.com/"),
new NameValuePair("version","2.0.1"),
new NameValuePair("login","YourUsername"),
new NameValuePair("apiKey","YourApikey"),
new NameValuePair("format","xml"),
new NameValuePair("history","1")
};
method.setQueryString(valuePair);
try {
httpclient.executeMethod(method);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseXml =null;
try {
responseXml = method.getResponseBodyAsString();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(responseXml);


When the above code is excuted we will get the output in following XML format


<bitly>
<errorCode>0</errorCode>
<errorMessage></errorMessage>
<results>
<nodeKeyVal>
<shortKeywordUrl></shortKeywordUrl>
<hash>bzXiN2</hash>
<userHash>ceCaRl</userHash>
<nodeKey><![CDATA[http://www.sundarishree.blogspot.com/]]></nodeKey>
<shortUrl>http://bit.ly/ceCaRl</shortUrl>
<shortCNAMEUrl>http://bit.ly/ceCaRl</shortCNAMEUrl>
</nodeKeyVal>
</results>
<statusCode>OK</statusCode>
</bitly>


Code to get the short url from XML output

if(responseXml != null) {
// parse the XML
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
StringReader st = new StringReader(responseXml);
Document d = null;
String retVal=null;
try {
d = db.parse(new InputSource(st));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
NodeList nl = d.getElementsByTagName("shortUrl");
if(nl != null) {
Node n = nl.item(0);
retVal = n.getTextContent();
System.out.println("Short URL >> "+retVal);
}
}


We can get the output as Short URL >>http://bit.ly/ceCaRl

2. By using bitly core methods

bitlyj-2[1].0.0 and commons-httpclient-3.1 jars are enough to use bitly core methods

Code to shorten the url


While importing Bitly mention as static

import static com.rosaloves.bitlyj.Bitly.*;
....
Provider bitly = Bitly.as("YourUserName", "YourApiKey");
ShortenedUrl info =bitly.call(shorten("http://www.visiontss.com/"));
System.out.println("Shorten URL "+info.getShortUrl());

output : Shorten URL http://bit.ly/ahyvK0

Bulk Methods
Some bitly methods support multiple arguments.info and clicks for example can take an arbitrary number of hash
or shortUrl arguments. You can do this in bitlyj just like you'd expect:

for(UrlInfo info1 : bitly.call(info("http://bit.ly/ceCaRl","http://bit.ly/ahyvK0"))) {
System.out.println("Created by :"
+info1.getCreatedBy());
System.out.println("ShortUrl :"
+info1.getUrl());
System.out.println("Title of the page :"
+info1.getTitle());
}

output :
Created by :sundarishree
ShortUrl :Url [shortBase=http://bit.ly/, globalHash=7haiBr, longUrl=, shortUrl=http://bit.ly/ahyvK0, userHash=ahyvK0]
Title of the page :Vision Tech Solutions - Software Product Development Company
Created by :sundarishree
ShortUrl :Url [shortBase=http://bit.ly/, globalHash=bzXiN2, longUrl=, shortUrl=http://bit.ly/ceCaRl, userHash=ceCaRl]
Title of the page :TECH.BLOG

You can know more in QuickStart

Wednesday, August 11, 2010

A Comfortable Online HTML Editor

A powerful Web-based WYSIWYG HTML editor that is designed for easy integration into our custom web applications


We can use this link for designing blog content HTML editor

Friday, August 6, 2010

rake aborted! Mysql::Error



When i tried to setup and migrate some objects in the MySQL DB
with Ruby on Rails.
  While executing the command  rake db:migrate ,i got the following error:
error:
       rake aborted!
       Mysql::Error: query: not connected: CREATE TABLE `schema_migrations` (`version`varchar(255) NOT NULL) ENGINE=InnoDB
(See full trace by running task with --trace)
Using rake db:create database succesfully created.
Solution to get rid of this issue
  Step -1 To get rid of the issue copy the libmySQL.dll
  Step -2 Paste it in C:\Ruby\bin of yours

Rails Application with MySQL DB

Follow the following step to work on rails application with mysql.





1:Our system should have the ruby installed .If not install the ruby from here
2: Start a Command prompt with Ruby C:\Ruby\bin
3:Enter the following command to install the special version of MySQL bindings.
      gem install mysql
You should expect a similar output like this:
  Successfully installed mysql-2.8.1.1-x86-mingw32
  1 gem installed
4:Enter the following command to install rails
     gem install rails
This is going to take a bit, since Rails and it’s dependencies takes around 2MB or so, and need to be downloaded and
installed.
Once done, expect see at the screen something like this:
  Successfully installed activSupport-2.3.2
  Successfully installed activerecord-2.3.2
  Successfully installed actionpack-2.3.2
  Successfully installed actionmailer-2.3.2
  Successfully installed activeresource-2.3.2
  Successfully installed rails-2.3.2
  6 gems installed
5:Copy the libmySQL.dll file from here
and paste it in your c:\ruby\bin location.
6:Create a rails application with mysql .Create a new Folder RailsPrg in C:

In Command prompt switch to C:\RailsPrg>
Let’s name our application appInMySQL
      rails appInMySQL --database=mysql
The --database option indicates to Rails that we want to use
MySQL instead of the default database adapter (SQLite3).
Rails will output a lot of lines when creating your application
structure, just an excerpt of what to see:
  ...
   create config/database.yml
   create config/routes.rb
   create config/locales/en.yml
   create config/initializers/backtrace_silencers.rb
   create config/initializers/inflections.rb
   create config/initializers/mime_types.rb
   create config/initializers/new_rails_defaults.rb
   create config/initializers/session_store.rb
   create config/environment.rb
   ...
7:Now Rails have configured for us the name of the database we want to use, and you can verify it in appInMySQL\config\database.yml
In that database.yml file modify as you need in the development phase
development:
   adapter: mysql
   encoding: utf8
   reconnect: false
   database: testMySql
   pool: 5
   username: username
   password: password
   host: hostname
8:In command prompt switch to C:\RailsPrg\appInMySQL> type the command
      rake db:create
Just that, simple db:create is going to connect to our MySQL server, and create the database for us.
9:Let’s verify that everything is in place, using the following command:


     ruby script\about
We can see the something like this as result:
About your application's environment
  Ruby version 1.9.1 (i386-mingw32)
  RubyGems version 1.3.4
  Rack version 1.0 bundled
  Rails version 2.3.2
  Active Record version 2.3.2
  Action Pack version 2.3.2
  Active Resource version 2.3.2
  Action Mailer version 2.3.2
  Active Support version 2.3.2
  Application root C:\RailsPrg\appInMySQL
  Environment development
  Database adapter mysql
  Database schema version 0
10:Now we can start generating the table for our application
Command to create a table & generate the pages for performing operation like inserting, deleting & modifying
Table name is cart
    ruby script\generate scaffold cart cartId:integer productInCart:string
Enter the migrate command
    rake db:migrate
11:Command to start the server ruby script\server
12:Execute http://localhost:3000/carts/ =>You can see the application page & can refine further the application

Friday, July 16, 2010

Google Map in Rails

To have google map in an application.First we have to get a key from this link
http://code.google.com/apis/maps/signup.html
Signing up a key for http://yourdomain.com is usually the best practice, as it will work for all sub domains and directories.

Steps to include Google Map in an application

1. Generate an application geomap with latitude:decimal ,longitude:decimal,location
name:string and place description:string using scaffold.

2. We have to show this data in the map.Map we will get from the google server.

3. Download the file at http://tinyurl.com/hfrailsmap .Its a partial file save it as _map.html.erb and place in the app/views/geomaps/ like app/views/geomaps/_map.html.erb

4. We have the update the google_key in the _map.html.erb file with the key we got from google api link.

5. Copy the generated code from the show.html.erb & paste in new file called
show_map.html.erb.place it in app/view/geomaps/show_map.html.erb

6. In the app\controllers\geomaps_controller.rb place the following code

def show_map
@geomap=Geomap.find(params[:id])
end


7. Include the following code in the route.rb located in config folder.
map.connect 'geomaps/map/:id',:action=>'show_map',:controller=>'geomaps'


8. Place a test.xml data file in the public folder.This to check the map with static data.
 <data>
  <description>Vision Tech Solutions Description: Vision Tech Solutions is a Software Product and Outsourced Software Product Development firm, dedicated to provide custom made software services to customer's need of any size within global reach.</description>
  <latitude>10.784745 </latitude>
  <longitude>78.689575 </longitude>
  <title>Vision Tech Solutions</title>
 </data>


9. We have to now include the _map.html.erb partial code in the display page show_map.html.erb
<%=render(:partial=>'map',:local=>{:data=>'test.xml'}) %>

We need to pass a local variable called data containing the path to
the map data /test.xml

10. Check the display of map in http://yourdomain:3000/geomaps/map/1

Thursday, July 15, 2010

Ruby On Rails for Beginners

Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern.
Rails is a collection ruby script. It’s better to have basic idea of ruby language before entering into Rails.
Rails has the following things

1. An Application framework /Action Pack that will help us to
generate data-driven, interactive pages.
2. Rails comes with one build in WebServer -We can run the web
application
3. Database-Rails creates application that are configured to
work with an integrated SQLite3 database
4. Active Record-Rails provides for object-relational mapping
library. This makes the database like a collection of Ruby objects.
5. Rails also provide the collection of tool scripts that helps
to manage the application.

Principle in Rails: Don’t Repeat Yourself
[If we tell Rails something once,its not required to say it again]

Install Ruby on Rails or RoR version2.1 & SQLite3 for database
http://www.rubyonrails.org/down

Getting started with Application

I - Steps to create a new application in Rails
1. At a Command Prompt –type >rails Application name
  Ex: C:\ >rails MyApp

A New Folder names MyApp will be created with basic structure of the
application.
The basic Structure has the following folders &files
App,Config,Db,Doc,Lib,Log,Public,Script, test, tmp, vendor ,Rake files & readme
file

2.In that command prompt change into MyApp folder C:\MyApp>.
Type ruby script/server –To run the web server.

  Ex: C:\MyApp>ruby script/server

3.Check this link http://localhost:3000/ to
confirm whether the webserver running Rails starts its webserver on port 3000 by default.

II -Start developing the Application

CRUD operation
CRUD operation/ Scaffolding –Basic operation of an application
Create,Read,Update & Delete.
Type scaffold command _Will generate the code for doing CRUD
operation in a database and also in the presentation layer .

 Ex: C:\MyApp\>ruby script/generate scaffold employee employee_name:string
address:text

Creates employee.rb file in models & create_employees.rb
file in Db -migrate

[Note: We have to give the db name in singular form like
Employee,Shop..etc., and the table name will be in plural like
employees,Shops..etc.,]

To create the Tables in the database

We have to run the migration script using another rails tool called Rake.This
migration ruby script is generated by the scaffolding.

Type rake db:migrate at the command prompt –Which runs the
migration code& creates the table.[Db files are location the db folder]

  Ex:C:\MyApp\>rake db:migrate

 Run the employees.rb file in Db –migrate & create the table.

Go for link http://localhost:3000/employees In a couple of minutes we
can enter few records & perform the CRUD operations.


In app folder we will have Model, Controller & View folders .

To changes the display of the page

We can make the changes in the labels by changing the four .html.erb files in
the views folder.

To append a column after creating the Table.
Rails understand the migration Add..To..=>Add particular column
to a particular table.
Ex:If we want to include Phone Number column in employees table.

  C:\MyApp\>ruby script/generate migration
AddPhoneToEmployees phone:string
Rails write the migration code.

After this command we have to give Rake db:migrate to make the
reflection of new column in the table.
Go for link http://localhost:3000/employees to conifrm the addition of
one more column in the table.
We can check the changes whenever we update the code.No need for publish & deploy
operations.

Without Scaffolding
We are in some time need of writing the code by our self for some application.Instead of having the same basic CRUD functions.We might be in need of genearating our own models & controllers

Command to create own model
 ruby script/generate model table name in singular form column name:type

>  rake db:migrate

This command will create magic columns
 Id – Generated Primary Key.
 Created_at and updated_at – record when data is entered or updated

Command to create own controller
> ruby script/generate controller
A Controller file will be created in the controller folder.

III- Routes
Route tells Tails where the web pages are located.
Routes are defined in a ruby program in config/routes.rb

By default this two line swill be the routes.rb

  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'

We can specify our own routes.
 Ex:map.connect '/employees/:id',:controller=>'employees',:action=>'show'

The controller by using the finder method in the model sends the employees to the view

employees_controller.rb file

 Class employeesController < ApplicationController
  Def show
    @employee=Employee.find(params[:id])
   end
 end


Rails Layout
Super-template exists in Rails is called Layout. one Single
template that will control how a group of other templates will look.
We have to place the html.erb file in the app/views/layouts.

To Add the style-sheet in the
Style sheet, images & javascripts will resides in the public folder.Which has all the static files.
Include the following code in the head tag of the html template.
   <%=stylesheet_link_tag 'style sheet name(css)'>


Redirect
A redirect tells the browser to go to a different URL for output.
  redirect_to "/---/# {---}"
# -symbol and {} inserts the value of the variable into a string.
Ex: While creating a new sample .We have to redirect to the currently
created sample.

 def create
  @sample = Sample.new(params[:sample])
  @sample.save
  redirect_to "/samples/#{@sample.id}"
 end


Restricting access to a function
Rails will use special kind of web security called HTTP Authenticating .This type of security will pops up a dialog box and asks for a username and password when someone tries to enter a secure area of a website.
In the controller we have to specify the following code to make the filtration before doing security applied functions.

before_filter :function name to be called before executing particular function,;only=>[:security applied operation name]

function name to be called before particular operations

 def functionname
  authenticate_or_request_with_http_basic("The name of the secured area of the website-domain") do |username,password|
    username == "username "&& password =="password"
   end
 end

Ex:

 class SampleController <ApplicationController before_filter   check_logged_in,:only=>[:edit]
  def check_logged_in
    authenticate_or_request_with_http_basic("Samples") do |username,password|
   username == 'admin' && password =="XY2HYS8"
  end
  end
 end

Thursday, July 8, 2010

Execute RUBY program on Command Prompt

Ruby is an object-oriented interpreted scripting language.

Download Ruby -One-Click Installer (old) - ruby186-27_rc2.exe

Know about Ruby by having a look at the below links
http://www.ruby-lang.org/en/about/
http://www.techotopia.com/index.php/What_is_Ruby%3F

Simple steps for executing a tiny ruby program in command prompt.

1. Write a simple program & save the file as “welcome.rb”
Code: puts "Welcome ==> RUBY !"

2. Set Ruby on Path as follows :
C:\ruby\prg>set path=%path%;c:\ruby\bin

3.To excute the program give the filename with .rb extension suffix to the word ruby
C:\ruby\prg>ruby welcome.rb

4.Add .rb to the PATHEXT environment variable as follows:
C:\ruby\prg>set PATHEXT=.rb;%PATHEXT%

5.Once the above settings are configured simply run the program by typing the filename at the command prompt (the .rb filename extension is not required):
C:\ruby\prg> welcome

Command Prompt code

Wednesday, July 7, 2010

PostGres Vs MySQL Database

 

PROPERTY

POSTGRES

MYSQL

License

BSD

GPL or Commercial

OS Support

Windows, Unix, Linux,       Mac OS.

Windows, Unix, Linux,       Mac OS, Symbiyan.

Fundamental Futures

ACID, Referential Integrity, Transactions, Unicode, Interface – GUI & SQL

ACID, Referential Integrity, Transactions, Unicode, Interface – GUI & SQL

Max DB Size

Unlimited

Unlimited

Max Table Size

32 TB

256 TB

Max Row Size

1.6 TB

64 KB

Max Columns per row

250 – 1600 Depending on type

4096

Max BLOB Size

2 GB

4 GB

Max Char Size

1 GB

64 KB

Max Number Size

Unlimited

64 bits

Min Date Value

-4713

1000

Max Date Value

5874897

9999

Max Column Name

63

64

Database Capability

Union, Inner join, Intersect, Except, Inner join, Outer join, Inner Selects, Merge join, Windowing Functions, Common Table Expressions.

Union, Inner join, Outer join, Inner Selects, Merge Joins.

Objects

Data Domain, Cursor, Trigger, Function, Procedure, External Routine.

Cursor, Trigger, Function, Procedure, External Routine.