Thursday, June 9, 2011

Create Web Service in Java Using Apache Axis2 and Eclipse

Web services are application components which communicate using open protocols. Using Web Services we can publish our application's functions to everyone. This tutorial provides step by step instructions to develop Web Services using Axis2 Web Services / SOAP / WSDL engine and Eclipse IDE. Let's start.

1. Setup the Development Environment


1.1. First you need to set up the development environment. Following things are needed if you want to create Web Services using Axis2 and Eclipse IDE.

Some Eclipse versions have compatibility issues with Axis2. This tutorial is tested with Apache Axis2 1.5.2, Eclipse Helios and Apache Tomcat 6.

1) Apache Axis2 Binary Distribution - Download
2) Apache Axis2 WAR Distribution - Download
3) Apache Tomcat - Download
4) Eclipse IDE – Download
5) Java installed in your Computer – Download

1.2. Then you have to set the environment variables for Java and Tomcat. There following variables should be added.
JAVA_HOME :- Set the value to jdk directory (e.g. C:\Program Files\Java\jdk1.6.0_21)
TOMCAT_HOME :- Set the value to top level directory of your Tomcat install (e.g. D:\programs\apache-tomcat-6.0.29)
PATH :- Set the value to bin directory of your jdk (e.g. C:\Program Files\Java\jdk1.6.0_21\bin)
1.3. Now you have to add runtime environment to eclipse. There go to Windows –-> Preferences and Select the Server --> Runtime Environments.


There select Apache Tomcat v6.0 and in the next window browse your Apache installation directory and click finish.


1.4. Then click on the Web Service –-> Axis2 Preferences and browse the top level directory of Apache Axis2 Binary Distribution.


2. Creating the Web Service Using Bottom-Up Approach


2.1 First create a new Dynamic Web Project (File --> New –-> Other…) and choose Web --> Dynamic Web Project.


2.2 Set Apache Tomcat as the Target Runtime and click Modify to install Axis2 Web Services project facet.


2.3 Select Axis2 Web Services


2.4 Click OK and then Next. There you can choose folders and click Finish when you are done.

3. Create Web Service Class


Now you can create a Java class that you would want to expose as a Web Service. I’m going to create new class called FirstWebService and create public method called addTwoNumbers which takes two integers as input and return the addition of them.

3.1 Right Click on MyFirstWebService in Project Explorer and select New –-> Class and give suitable package name and class name. I have given com.sencide as package name and FirstWebService as class name.

package com.sencide;
public class FirstWebService { 
 public int addTwoNumbers(int firstNumber, int secondNumber){
  return firstNumber + secondNumber;
 }
}
3.2 Then, select File --> New –-> Other and choose Web Service.


3.3 Select the FirstWebService class as service implementation and to make sure that the Configuration is setup correctly click on Server runtime.


3.4 There set the Web Service runtime as Axis2 (Default one is Axis) and click Ok.


3.5 Click Next and make sure Generate a default service.xml file is selected.


3.6 Click Next and Start the Server and after server is started you can Finish if you do not want to publish the Web service to a test UDDI repository.


You can go to http://localhost:8888/MyFirstWebService/services/listServices to see your running service which is deployed by Axis2. You can see the WSDL by clicking the link FirstWebService.


We have to use Eclipse every time when we want to run the service if we do not create .aar (Axis Archive) file and deploy it to the server. So let’s see how we can create it.

4. Create .aar (Axis Archive) file and Deploying Service


4.1 In your eclipse workspace and go to MyFirstWebService folder and there you can find our web service inside services folder. Go to that directory using command prompt and give following command. It will create the FirstWebService.aar file there.
jar cvf FirstWebService.aar com META-INF



4.2 Then copy the axis2.war file you can find inside the Apache Axis2 WAR Distribution (You downloaded this at the first step) to the webapps directory of Apache Tomcat. Now stop the Apache Tomcat server which is running on Eclipse IDE.


4.3 Using command prompt start the Apache Tomcat (Go to bin directory and run the file startup.bat). Now there will be new directory called axis2 inside the webapps directory. Now if you go to the http://localhost:8080/axis2/ you can see the home page of Axis2 Web Application.


4.4 Then click the link Administration and login using username : admin and password : axis2. There you can see upload service link on top left and there you can upload the created FirstWebService.aar file. This is equal to manually copping the FirstWebService.aar to webapps\axis2\WEB-INF\services directory.


4.5 Now when you list the services by going to http://localhost:8080/axis2/services/listServices you should be able to see our newly added service.


5. Creating a Web service client


5.1 Select File --> New --> Other… and choose Web Service Client


5.2 Set he newly created Axis2 Web service (http://localhost:8080/axis2/services/FirstWebService?wsdl) as the Service definition. Then configure the Server runtime as previously and click finish.


5.3 This will generate two new classes called FirstWebServiceStub.java and FirstWebServiceCallbackHandler.java. Now we can create test class for client and use our web service. Create new class called TestClient.java and paste following code.
package com.sencide;

import java.rmi.RemoteException;
import com.sencide.FirstWebServiceStub.AddTwoNumbers;
import com.sencide.FirstWebServiceStub.AddTwoNumbersResponse;

public class TestClient {

 public static void main(String[] args) throws RemoteException {
  
  FirstWebServiceStub stub = new FirstWebServiceStub();
  AddTwoNumbers atn = new AddTwoNumbers();
  atn.setFirstNumber(5);
  atn.setSecondNumber(7);
  AddTwoNumbersResponse res = stub.addTwoNumbers(atn);
  System.out.println(res.get_return());
  
 }
}
Now you can run the above code as java application and you will get the output as 12 since we are adding 7 and 5.
Download the Eclipse project of the above example (Password:sara)
Your comments are welcome !

Sunday, March 20, 2011

Hibernate Tutorial for Beginners

Hibernate is an Object/ Relational Mapping solution for Java environments. It reduces the development cost by reducing paradigm mismatch between how data is represented in objects versus relational databases.

Hibernate takes care of the mapping from Java classes to database tables and provides data query and retrieval facilities. This tutorial is designed for the beginners of Hibernate and expects you to have some knowledge about Java and SQL. I’m going to use MySQL database and Eclipse IDE in this tutorial.

By following this tutorial you will get the knowledge of;

1. Setup the Development Environment for Hibernate
2. Create POJO Classes
3. Create Mapping Files
4. Hibernate Configuration
5. Create Startup Helper Class
6. Create Test Class to Load and Store Objects


Let's start.

1. Setup the Development Environment for Hibernate

First you need to set up the development environment. Following things are needed if you want to try Hibernate with MySQL using Eclipse IDE.

1. Hibernate distribution bundle – Download
2. MySQL installed in your Computer – Download
3. JDBC driver for MySQL – Download
4. slf4j logging backend – Download
5. Eclipse IDE – Download

1.1 Setup the Database

I'm going to use simple database named "userdata" which has two tables named "users" and "tasks". Figure 1 illustrates the structure of the database and there "id" column is the Primary Key of both tables and it is set to AUTO_INCREMENT.


1.2 Create New Project

In this tutorial I’m going to show how to Retrieve, Add, Delete and Update data in a MySQL database. There I’ll create simple Java Project and you can use this tutorial to create web applications too.

First create new project in Eclipse using appropriate name, I’ll give "MyFirstHibernateApp".


You need to manually account for all the needed dependencies, so let’s create new folder called "lib" inside the "MyFirstHibernateApp" by right clicking on it as shown in following Figure 3.


Now copy following files into that folder.
1. hibernate3.jar (Can be found in distribution bundle)
2. All artifacts in the lib/required directory in distribution bundle
3. All artifacts in the lib/jpa directory in distribution bundle
4. All files from either the lib/bytecode/cglib or lib/bytecode/javassist directory
5. One of the slf4j logging (I'll use slf4j-simple-1.6.1.jar found inside slf4j-1.6.1.zip)
6. mysql-connector-java-5.1.15-bin.jar (JDBC driver for MySQL )

Then you can configure the built path. To do that, right click on project "MyFirstHibernateApp" in Package Explorer and select Build Path --> Configure Build Path... Then go to Libraries tab and browse lib folder you created earlier. Then add external jars by selecting all jar files that you copied to lib folder in one of previous step. (Check Figure 4).


Now you will be able to see the referenced libraries as follow (Figure 5).


2. Create POJO Classes

Next, I'll create two classes that represent the user and task we want to store in the database. Those are simple JavaBean classes with some properties which uses standard JavaBean naming conventions for property getter and setter methods and private visibility for the fields.

To create new class right click on "MyFirstHibernateApp" and select New --> Class. Then give appropriate package name, I’ll give "com.hib" as figure 6. You can generate getter and setters easily by selecting variable declaration and selecting Source --> Generate Getters and Setters…


User Class
package com.hib;

public class User {
 private Integer id;
 private String firstName;
 private String lastName;
 
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
}
Task Class
package com.hib;

public class Task {

 private Integer id;
 private Integer userID;
 private String title;
 private String description;
 
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public Integer getUserID() {
  return userID;
 }
 public void setUserID(Integer userID) {
  this.userID = userID;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}
The id property holds a unique identifier value for a particular user and task. All persistent entity classes will need such an identifier property if you want to use the full feature set of Hibernate.

3. Create Mapping Files

Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.

Right click on the "src" folder and select New --> File and paste following code there. Save it as user.hbm.xml.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hib.User" table="users" >
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="firstName">
   <column name="first_name" />
  </property>
  <property name="lastName">
   <column name="last_name"/>
  </property>
 </class>
</hibernate-mapping>
Tasks.java should also have a mapping file, so create another file and paste following code. Save it as task.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hib.Task" table="tasks">
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="userID">
   <column name="user_id" />
  </property>  
  <property name="title">
   <column name="title" />
  </property>
  <property name="description">
   <column name="description"/>
  </property>
 </class>
</hibernate-mapping>
In the above mapping file you can see the mapping of the unique identifier property to the tables primary key. As we do not want to care about handling this identifier, we configure Hibernate's identifier generation strategy for a surrogate primary key column by giving class="native". If it is not AUTO_INCREMENT one we should use class="assign".

The id element is the declaration of the identifier property. The name="id" mapping attribute declares the name of the JavaBean property and tells Hibernate to use the getId() and setId() methods to access the property. The column attribute tells Hibernate which column of the "users" and "tasks" tables holds the primary key value. Similar to the id element, the name attribute of the property element tells Hibernate which getter and setter methods to use.

4. Hibernate Configuration

Now you have the persistent class and its mapping file in place. Let’s configure Hibernate.

Right click on the "src" folder and select New --> File and paste following code there. Save it as hibernate.cfg.xml. Here you have to give the username and password according to your MySQL account. In my case username is root and there is no password.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <!-- Database connection settings -->
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost/userdata</property>
  <property name="connection.username">root</property>
  <property name="connection.password"></property>
  
  <!-- JDBC connection pool (use the built-in) -->
  <property name="connection.pool_size">1</property>
  
  <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  
  <!-- Enable Hibernate's automatic session context management -->
  <property name="current_session_context_class">thread</property>

  <!-- Disable the second-level cache -->
  <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
  
  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>
  
  <!-- Drop and re-create the database schema on startup -->
  <property name="hbm2ddl.auto">update</property>
  
  <!-- Mapping files -->
  <mapping resource="user.hbm.xml"/>
  <mapping resource="task.hbm.xml"/>
  
 </session-factory>
</hibernate-configuration>
5. Create Startup Helper Class

You have to startup Hibernate by creating a global org.hibernate.SessionFactory object and storing it somewhere for easy access in your application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once. We will create a HibernateUtil helper class that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.

To create new class right click on "com.hib" package and select New --> Class and give Name as HibernateUtil.java and paste the following code in class file.
package com.hib;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 private static final SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory() {
  try {
   // Create the SessionFactory from hibernate.cfg.xml
   return new Configuration().configure().buildSessionFactory();
  }
  catch (Throwable ex) {
   // Make sure you log the exception, as it might be swallowed
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}
6. Create Test Class to Load and Store Objects

Now it’s time to do some real work using Hibernate. Following test class illustrate how we can Add, Retrieve, Update and Delete data in a MySQL database.

To create new class right click on "com.hib" package and select New --> Class and give Name as Test.java and paste the following code in class file.
package com.hib;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  Test tst = new Test();
  
  /**
   * adding records 
   */
  tst.addUser("Saranga", "Rath");
  tst.addUser("Isuru", "Sampath");
  tst.addUser("Saranga", "Jaya");
  tst.addUser("Prasanna", "Milinda");
  
  tst.addTask(1, "Call", "Call Pubudu at 5 PM");
  tst.addTask(1, "Shopping", "Buy some foods for Kity"); 
  tst.addTask(2, "Email", "Send birthday wish to Pubudu"); 
  tst.addTask(2, "SMS", "Send message to Dad"); 
  tst.addTask(2, "Office", "Give a call to Boss");
  
  /**
   *  retrieving data 
   */
  tst.getFullName("Saranga");
  
  /** 
   * full updating records 
   */
  User user = new User();
  user.setId(1);
  user.setFirstName("Saranga");
  user.setLastName("Rathnayake");
  tst.updateUser(user);
  
  /**
   * partial updating records 
   */
  tst.updateLastName(3, "Jayamaha");

  /** 
   * deleting records 
   */
  User user1 = new User();
  user1.setId(4);
  tst.deleteUser(user1);
 }

 private void addUser(String firstName, String lastName) {
  
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   
   User user = new User();
   
   user.setFirstName(firstName);
   user.setLastName(lastName);
   
   session.save(user);
   
   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  } 
 }

 private void addTask(int userID, String title, String description) {
  
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   
   Task task = new Task();
   
   task.setUserID(userID);
   task.setTitle(title);
   task.setDescription(description);
   
   session.save(task);
   
   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  } 
 }
 
 private void updateLastName(int id, String lastName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   String hqlUpdate = "update User u set u.lastName = :newLastName where u.id = :oldId";
   int updatedEntities = session.createQuery( hqlUpdate )
   .setString( "newLastName", lastName )
   .setInteger( "oldId", id )
   .executeUpdate();

   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
  
 }

 private void updateUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   
   session.update(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 } 

 private void getFullName(String firstName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   List<User> users = session.createQuery("from User as u where u.firstName = :firstName")
   .setString( "firstName", firstName )
   .list();
   for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
    User user = iter.next();
    System.out.println(user.getFirstName() +" " + user.getLastName());
   }
   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  } 
 } 
 
 private void deleteUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   
   session.delete(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 } 
}
If you have setup the database and followed the above steps correctly you should get following output.
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: select user0_.id as id0_, user0_.first_name as first2_0_, user0_.last_name as last3_0_ from users user0_ where user0_.first_name=?
Saranga Rath
Saranga Jaya
Hibernate: update users set first_name=?, last_name=? where id=?
Hibernate: update users set last_name=? where id=?
Hibernate: delete from users where id=?
Hibernate use Hibernate Query Language (HQL) which is powerful than SQL and fully object-oriented. You can get good knowledge about HQL by following HQL Documentation.

I have included the source files of this tutorial with the database. You can download it from here (Password : sara).

Monday, August 23, 2010

Top 15 HTML Best Practices

If you are a beginner to web development you have finally come to the correct place. This tutorial discuss the best practices you should follow to write clean, cross browser compatible and W3C validated XHTML and CSS codes. Here 15 tips are discussed and let’s see them one by one.

01. Keep Your Markup in Lower Case

Keep the markup lower-cased is an industry standard practice that you can follow easily. Capitalize markup will not affect how your web pages are rendered, but it will significantly reduce the readability of your markup.

02. Identify and Declare the Relevant DockType

The first thing in an HTML document is the DocType declaration, it is not an HTML tag. It gives an idea to the web browser about what version of the markup language the page is written in. As a best practice you can use XHTML 1.0 Strict, since it checks whether the markup is well-formed XML. Hear is an example.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
 <head>
  <title>My Title</title>
 </head>
 <body>
  .
  .
 </body>
</html>
If you are interested check the other recommended list of Doctype Declarations.

03. Never Use Inline Styles and Inline JavaScript

Always use external CSS files. You will feel easy to use inline styles, but it will cause more problems. Add styles once the page has been completely coded.

Instead of;
<div>
 <a href="#" style="font-size:14px;" onclick="myFunction()" >My Link</a>
</div>
Use;
<div id="myID" >
 <a href="#" id="someLink">My Link</a>
</div>
In your external CSS file you can add styles to that element.
#myID a{
 font-size:14px;
}
You can move the JavaScript code to an external JS file and use a framework like jQuery to add the "click" method.
$('# someLink').click(function() {  
 alert('Hellow !');  
});
04. Use Reserved Characters

For example, you cannot use the greater than (>) or less than (<) signs within your text because the browser could mistake them for markup. You must use &gt; and &lt; for reprecent those characters. As an example,
It is true that 5 &gt; 3 &amp; 1 &lt; 2
Will render as;
It is true that 5 > 3 & 1 < 2
You can use the HTML ISO-8859-1 Reference to see the list of special characters.

05. Link all External CSS Files Inside the Head Tag

The HTML specification recommends that external CSS files should be linked within the document HEAD tag. The advantage is that your page's load time will be reduced.
<head>  
 .
 .
 <link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />  
 <link href="css/layout.css" rel="stylesheet" type="text/css" media="screen" />  
</head>  
06. Place JavaScript Files Just Before the Closing BODY Tag

The Yahoo! Exceptional Performance team recommend placing scripts at the bottom of your page because when loading a script, the browser can’t continue on until the entire file has been loaded.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
 <head>
  <title>My Title</title>
 </head>
 <body>
   .
   .
   <p>This is a sample paragraphe</p>  
  </div><!--end of footer-->
  <script type="text/javascript" src="js/jquery.js"></script>  
  <script type="text/javascript" src="js/nav_menu.js"></script>  
 </body>  
</html>  
07. Close Your Tags and Make Them Nested Properly
You should always close your tags in the reverse order from the way they open. Otherwise it will cause validation problems.

Instard of;
<li>another text
<li><b>text goes hete</li></b>
Use;
<ul>  
 <li><b>text goes hete</b></li>
 <li>another text</li>
</ul>
08. Use FireBug


Firebug is the best free and open source plug-in you can use when creating websites. It integrates with Firefox and it allows the debugging, editing, and monitoring of any website's CSS, HTML, DOM, and JavaScript, and provides other Web development tools. Download Firebug

09. Use Separate CSS for IE

We all know that Internet Explorer is a real headache when it comes to web development. Lot of people complain "My site looks great in Firefox, but looks messed up in IE"

There is a simple way to get around most problems. You can create a conditional statement in your HTML to import a style sheet just for IE. This CSS file override the statements in the main CSS file just for IE. Hear are some few examples. Keep in mind to link those style sheets after the main CSS (style.css).
<head>
 <title>Sencide | We Care Your Satisfaction</title>
 <link type="text/css" rel="stylesheet" href="css/style.css" media="screen" />
 <!--[if lte IE 6]>
  <link rel="stylesheet" href="css/ie6.css" type="text/css" media="screen" />
 <![endif]-->
 <!--[if IE 7]>
  <link rel="stylesheet" href="css/ie7.css" type="text/css" media="screen" />
 <![endif]-->
 <!--[if gt IE 7]>
  <link rel="stylesheet" href="css/ie8.css" type="text/css" media="screen" />
 <![endif]-->
</head>
The first statement says "if the browser is later than or equal to IE6 than apply style sheet ie6.css".

10. Use a CSS Reset

All browsers have presentation defaults for line heights, margins and font sizes of headings, and so on, but the problem is no browsers have the same defaults. That is why we have to reset all the values in the beginning. There I always use Eric Meyer’s CSS Reset file.
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
 margin: 0;
 padding: 0;
 border: 0;
 outline: 0;
 font-size: 100%;
 vertical-align: baseline;
 background: transparent;
}
body {
 line-height: 1;
}
ol, ul {
 list-style: none;
}
blockquote, q {
 quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
 content: '';
 content: none;
}

/* remember to define focus styles! */
:focus {
 outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
 text-decoration: none;
}
del {
 text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */
table {
 border-collapse: collapse;
 border-spacing: 0;
}

In the bigining of your main CSS file you can import this reset.css file like this.
@import url('reset.css');
11. Never Scale Images in HTML

Don't use a bigger image by setting the width and height in HTML. If you use;
<img src="logo.jpg" alt="Logo" width="75" height="75" />
then your image (logo.jpg) should be 75px*75px rather than a scaled down 300px*300px image.

12. Always Set "Alt" Attribute to Images

It’s very important to put alt attributes within image tags for accessibility and validation reasons. Another thing is you must avoid empty Image src attributes which cripple your servers by sending a large amount of unexpected traffic.

Instard of;
<img src="logo.jpg" />
<img src="" />
Use;
<img src="logo.jpg" alt="Logo" />
<img src="path_to_your_image.jpg" alt="Image Caption" />
13. Use Small Image for Backgrounds

If you are not using Web Safe Colors for your site background, I strongly recommend to use 5px * 5px small piece of image as background color. Otherwise there will be a difference between images and background as shown in the picture. This mainly occurs in MACs due to super high gamma output comparable to LCDs.

Instard of;
div.content_wrapper{
 float:left;
 width:600px;
 background-color:#2B2A26;
}
Use;
div.content_wrapper{
 float:left;
 width:600px;
 background : #2B2A26 url(../images/bg.jpg) repeat;
}
14. Validate Continuously


One can ask "My site looks good and works fine, why should I validate?". There are lot of advantages you can get if you validate your pages. Search engines cannot properly index your site if there are serious HTML errors. Well written HTML will render better and faster than HTML with errors.

You can download the Web Developer Toolbar and use the "Validate HTML" and "Validate CSS" options continuously or you can use W3C Markup Validation Service

15. Compress CSS and JavaScript Files

By compressing your CSS and JavaScript files, you can reduce the size and that will improve page load times. You can do this using following services after the development of your site.

JavaScript Compression Services : JSCompress, JavaScript Compressor
CSS Compression Services: CSS Optimiser, CSS Compressor

Thursday, August 19, 2010

Welcome

Welcome to the Sencide Blog

Sencide was founded in May 2009 as a Sri Lankan software Development Company recognized for innovation, customized and cost effective solutions. We believe in small teams, solid development and great design using standards.

Related Posts Plugin for WordPress, Blogger...