Jun 17, 2011

Add Syntax Highlighter To Blogger

We can use a syntax highlighter to display source code syntax in different colours. It will create a user friendly environment to read the source code.
I'm going to use google-code-prettify to do this task.

First thing you need to add a java script and a css to your blog. It should be placed after the <head> tag. To do this you must go to settings -> design -> edit html.
Press "Ctrl+f" and type " <head" , it will help to find the head tag. Then add the Javascripts and css like this.

<head>
<link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css' rel='stylesheet' type='text/css'/> 
<script src='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js' type='text/javascript'/>

Then you need to modify the "<body>" tag. It should be like this.

<body onload="prettyPrint()" ... >

Then you can write your code within <pre$gt;</pre$gt; or <code$gt; </code$gt;. But to add the colours you need to add the class as,

<pre class="prittyprint">
   <!-- Your code comes here. -->
</pre>

Note: - First use "Compose" to add the coding then go to "Edit HTML" to add the pre tag with class. There is an effect between <> and &lt;&gt; .

This is a sample java program.

class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

Jun 16, 2011

Visual Studio and C# (Some Useful Code Samples)

Creating MDI Forms (Multiple Document Interface).

Add 2 new Forms (Form1, Form2) to the solute on. Form1 will be the main frame and Form2 will be inside the first one. So in the first one we must make it as a MDIParent form. To do that, select the Form1 and go to its properties. In that list you will see a property called “IsMdiContainer”. Set it to TRUE. Now you will see that the form has been changed. Then go to the code behind of the Form1. In the constructor of the class, you should write this code in order to view the Form2 inside the Form1.

Note: - You can use a toolStrip instead of writing the code in the constructor.
public Form1()
{
        InitializeComponent(); // This is an auto generated code.
        // start of our code.
        Form2 fm = new Form2();
        Fm.MdiParent = this;
        Fm.Show();
        // end of our code.
}
These 3 lines of code will do the trick. Think if you need to open another form (Form3) by clicking a button in Form2, so you need to modify the 2nd line of this code to,
Fm.MdiParent = this.Parent;
This will set the MdiParent for Form3, by the parent of Form2. It means that it will use the Form1 as the parent of the Form3.



Connect your .NET Application to MySQL Database.

Most of the time .Net applications will use MSSQL database. But here is a sample code to connect your application to MySQL database.

First of all you need to install MySQL connecter for .NET environment. It can be freely download from this link. (For windows and MONO project.)

http://dev.mysql.com/downloads/connector/net/

Note: - Close Visual Studio before you start installing the connector.

I will not going to create a DbAccess class here, just simply tell how to use it.

First of all you need to add a reference called “MySql.Data” to your project. Then you need to add namespace,
Using MySql.Data; 
After that I will use a button click event to get data from the MySQL database.
private void button1_Click(object sender, EventArgs e)
{        
   string result = null;

   InitializeComponent();
   string ConString = "User Id=user;"+ 
                      "password=password;"+
                      "Persist Security Info=True;"+
                      "server=localhost;"+
                      "database=test";

   MySqlConnection conn = new MySqlConnection(ConString);

   MySqlCommand cmd = conn.CreateCommand();
   cmd.CommandText = "Select * from test";
   conn.Open();

   MySqlDataReader reader = cmd.ExecuteReader();
   while (reader.Read())
   {
      result += reader["name"].ToString() + " \n ";
   }
   conn.Close();
   MessageBox.Show(result);
}


Use configuration files in Visual Studio.

In the previous sample code I hard code the MySQL connection string. But that is not a good practice. Because some configurations like the password will rapidly change. So if we hard code these settings, we need to compile the application each and every time after changing the password. So to avoid that overhead we use a configuration file called “App.Conf”. You can add this file to your project by going to add new item.

This is an XML file. So to add the MySQL connection string data, you need to modify this XML file into something like this.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>  
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="MySQLConStr" 
             connectionString="User Id=user; 
                               password=password; 
                               Persist Security Info=True; 
                               server=localhost; 
                               database=test"
             providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
</configuration>

Then go to your C# code and modify the connection string to something like this. To do this you may need to add a namespace,
using System.Configuration;

string ConString = ConfigurationManager.ConnectionStrings["MySQLConStr"].ToString();
Note: - Give the same name to both <add name="" ... > and ConnectionString[""].

May 28, 2011

Form validation - Javascript client side programming

When we are developing a web based software we must think about 2 things. One is server side and the other is client side. In the server side it will host the logic of the software and maybe the data storage. But all user interactions will be happen in the client side. If a user need to input some values, (maybe filling a form) each submit will send a http message to the server. Then according to the message it will give the response (maybe storing values in a database).

So why form validation? Forms are the main method that used to get inputs from a user. Users can input what ever he/she wants. So we can not think that a user will only fill the form according to the requirement or he/she may miss an important field. If something happens like this, it will harm the software. So to avoid such a thing we use validation.

To do the validation we get user input and check whether user inputs are according to the needs of the software. As an example, if the software need an 3 digit number, in the validation process it will check if the user had input a 3 digit number or something else. If the validation pass (user had input exactly a 3 digit number) software will continue its process(maybe storing in a database). But if the validation process fails (user had input something else), software will stop its process and it must request to re-enter the information correctly. So this request will cost some extra http requests. More http requests will cost more network usage and more network traffic. If the user enter wrong information for several times this will be worse.

To avoid this overhead we must move the validation part to the client side. From this approach we will only get valid information from the client side. So it will reduce unnecessary http requests. We can use Javascript, a client side programing language to do this.

<form action="process.php" method="POST">
<input type="text" name="myinput" id="myinput"  maxlength="5" >
<input type="submit" value="Submit" onClick="return validate()" />
</form>


<script type="text/javascript">
function validate()
{
var ret=true;
var input=document.getElementById("myinput").value;
if( input==null || input=="" )
{
  alert("Field is empty.");
  ret=false;
}
return ret;
}
</script>

This is a basic validation form. In this forms input field you can see something like " maxlength="5" ". It is a attribute in input tag. It can limit the number of input characters to 5. Then in the other input field (Submit button) you can see something like " onClick="return validate()" ". This is the most important part of the form. When a user click the submit button, it will trigger the "onClick" event. According to this form onClick event will call a function called " validate() ". This function will return true or false. So after user click the submit button it will be like onClick="return true" or onClick="return false". If the onClick event returns true, form will send the http request to the server. If the onClick event returns false, it will not send a http request and we can inform about the error by giving a popup like in this code.

Note:-
Although this reduce unnecessary http requests, it will add some extra code in to the html page. And also you must validate the inputs in the server side again though you validate it in the client side. There are ways to hack this client side validation process easily.

Jan 5, 2011

vaadin clojure app (coding onlly)

This is a simple app which get two numeric values and give its sum as a message.

(ns myapp.core
 (import (com.vaadin.ui Layout)))

(defn getSum [tf1 tf2]
(let [a  (Double/parseDouble (. (. tf1 getValue) toString))
      b  (Double/parseDouble (. (. tf2 getValue) toString))
      c (+ a b)]
      (. c toString))
)

(defn main [args]
  (proxy [com.vaadin.Application] []
    (init []
      (let [app this
            l1  (new com.vaadin.ui.Label "My Application")
            tf1 (new com.vaadin.ui.TextField "Input value one :")
            tf2 (new com.vaadin.ui.TextField "Input value two :")]
        (.setMainWindow this
          (doto (new com.vaadin.ui.Window "Welcome to myapp")
            (.addComponent l1)
            (.addComponent tf1)
            (.addComponent tf2)
            (.addComponent
              (doto (new com.vaadin.ui.Button "Click Me")
                (.addListener (proxy [com.vaadin.ui.Button$ClickListener] []
                   (buttonClick [event]
                       (. (. app (getMainWindow)) (showNotification "The Sum is :" (getSum tf1 tf2)  )))))))
           ))))))
To get the real output you need to view the previous post.

Jan 4, 2011

Writin a Vaadin app using Clojure

First of all you need Clojure with leiningen environment. Vaadin jar file.

Setup the leiningen environment and create a new project.
lein new myapp

Then change the directry to myapp and there you can see some flies. Edit the file src/myapp/core.clj file to your vaadin app. After editing it will be like this.

(ns myapp.core)

(defn main [args]
  (proxy [com.vaadin.Application] []
    (init []
      (let [app this]
        (.setMainWindow this
          (doto (new com.vaadin.ui.Window "Test application")
            (.addComponent
              (new com.vaadin.ui.Label "Hello Vaadin/LISP user!"))
            (.addComponent
              (doto (new com.vaadin.ui.Button "button")
                (.addListener (proxy [com.vaadin.ui.Button$ClickListener] []
                                (buttonClick [event] (. (. app (getMainWindow)) (showNotification "test")))))))))))))

Note the (ns **** ).

Then edit the project.clj file.

(defproject myapp "1.0.0-SNAPSHOT"
  :description "FIXME: write"
  :dependencies [[org.clojure/clojure "1.2.0"]
                 [org.clojure/clojure-contrib "1.2.0"]
                 [com.vaadin/vaadin "6.4.8"]]
  :dev-dependencies [[uk.org.alienscience/leiningen-war "0.0.1"]]
  :aot [myapp.core])

In this you can see there is a   :dev-dependencies [[uk.org.alienscience/leiningen-war "0.0.1"]] and   :aot [myapp.core]. First one is a plugin which can createa WAR file. The second one is to create the servlet class from the clojure file.

Now we need to write the web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
        <display-name>testVaadin</display-name>
        <context-param>
                <description>Vaadin production mode</description>
                <param-name>productionMode</param-name>
                <param-value>false</param-value>
        </context-param>
        <servlet>
                <servlet-name>Lisp</servlet-name>
                <servlet-class>org.thilina.Servlet</servlet-class>
                <init-param>
                        <param-name>script-name</param-name>
                        <param-value>myapp.core</param-value>
                </init-param>
                <init-param>
                        <param-name>package-name</param-name>
                        <param-value>myapp.core</param-value>
                </init-param>
                <init-param>
                        <param-name>function-name</param-name>
                        <param-value>main</param-value>
                </init-param>
        </servlet>
        <servlet-mapping>
                <servlet-name>Lisp</servlet-name>
                <url-pattern>/*</url-pattern>
        </servlet-mapping>
</web-app>

Vaadin http handling is little bit different so we neet to some additional task. You need to compile above java code and place those classes in the class directory.

package org.thilina;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import clojure.lang.RT;
import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.AbstractApplicationServlet;

public class Servlet extends AbstractApplicationServlet {

 @Override
 protected Class<? extends Application> getApplicationClass()
   throws ClassNotFoundException {
  return Application.class;
 }

 @Override
 protected Application getNewApplication(HttpServletRequest request) throws ServletException {
  try { //load script, with name provided as a servlet's parameter
   RT.load(getServletConfig().getInitParameter("script-name"), true);

   //run Lisp function
   return (Application)RT.var(getServletConfig().getInitParameter("package-name"),
                 getServletConfig().getInitParameter("function-name")).invoke(new String[0]);
  }
  catch (Exception e) {
   throw new ServletException(e);
  }
 }
}

You need clojure.jar and vaadin.jar in order to compile this java file.

Now you can compile the project and get a WAR file.
lein deps
lein compile
lein uberwar

Then put this *.war file to tomcat/webapps directory.


References :-

https://github.com/technomancy/leiningen
http://dev.vaadin.com/wiki/Articles/ClojureScripting