Wednesday, 20 February 2013

Pagination and Sorting in a Grails Application








Here is a new and very refreshing Technology called Groovy on Grails. Groovy is the language that is used and Grails is the framework for use in developing Web Based Applications widely.

Normally Web development companies prefer using more of PHP rather than other languages. But in case of Grails and Groovy there is use of Java and best part about it is that, the application is continuously running and objects are maintained from the time the application was first launched on the Web Server, unlike PHP where objects are created only when there is a request to the Server made and on getting a successfull response the object dies off. 

While querying to the database, either GORM or HQL queries are used. In GORM we first create a criteria, which does a ‘select *’on the table, and then narrow the criteria using where clause.

Example of a GORM queries:
def c = Customer.createCriteria()
def result = c.list{
projections{
groupProperty(‘date’)
groupProperty('place')
sum('total','total')
maxResults(10)
}
and{
eq(district,’North’)
       }
}

The result of this query i.e. the list is passed to the view, where the values are displayed accordingly.
The problem with this approach is that, when you use projections, you cannot use the params returned by the view for pagination and sorting. In case of simple GORM queries that do not use projections, params can be used. Also, if the ‘sortableColumn’ property of GRAILS tables is used, then the additional params (if any) need to be specified in the tag.

To make pagination and sorting work we can use HQL queries. Similar to the above query, an HQL query can be written as:

def result  = Customer.executeQuery("select c.date, c.place, sum(c.total) from Customer as c"+
" where c.district = :dist group by g.date, g.place order by g.$params.sort $params.order",
   [dist : district, params.max : 10, offset : params.offset])

Here, dist is used as a named parameter. Named parameters do not work for ‘order by’. In that case, we directly use the param value prefixed with ‘$’ symbol.

Another thing that needs to be taken care of here is that, when the page is loaded without passing the pagination, sort, order and offset parameters, the param values will be set to null. Hence before executing the query, the params should be checked for null values. If null, they should be set to a default value.

Setting Date in Labels in Java Swings Application




Recently I had a difficulty in setting the Date Labels using the Date Functions in Java Swings application that I was working on. The reason being that there are two variants of the Date Functions:-


  • java.sql.Date 
  • java.util.Date. 


If we use java.util.Date then java.sql.Date function was not accessible and java.sql.Date was required for setting the date using Prepared Statements.

I managed to rectify it by type-casting the two functions. Below are a set of ways in which the Date functions
can be used:

JAVA.UTIL.DATE


  • Setting the Date in a JLabel in string format


import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Calendar;

JLabel date= new JLabel("DATE:");

final JLabel dateTime = new JLabel();

dateTime.setText(Demo.timenow()); // Demo is the name of the jframe

public static String timeNow() {

Calendar cal = Calendar.getInstance();

String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";

SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);

return sdf.format(cal.getTime());

}


JAVA.SQL.DATE


  • Printing the date in string format


import java.sql.Date;

import java.text.SimpleDateFormat;

public class Dates {

private static SimpleDateFormat df = new SimpleDateFormat("MMMM yyyy");

public static void main(String[] args){

Date oneDate = new Date(new java.util.Date().getTime());

System.out.println(df.format(oneDate));

}


  • Returing the date in DATE format


import java.sql.Date;

private static java.sql.Date getCurrentDate() {

java.util.Date today = new java.util.Date();

return new java.sql.Date(today.getTime());


  • Setting date value as timestamp using prepared staments


import java.sql.Date;

java.util.Date today2 = new java.util.Date();

java.sql.Timestamp timestamp = new java.sql.Timestamp(today2.getTime());

prepst.setTimestamp(2, timestamp);



  • Setting date value through Hibernate


import java.sql.Date;

String date2= dateTime.getText(); // set date to a string which is fetched from a JLabel dateTime

java.util.Date date = new SimpleDateFormat("dd-mm-yyyy HH:mm:ss").parse(date2); /*changing
date format*/

bill.setDate(date);

The are more tutorials and tips coming up in java. These are some basic tips and techniques that are used while coding for swings applications. Some common bugs that would be encountered and rectified easily.


Text-box Auto-completion in c#.net using Ajax.


Have you encountered or wondered how to get the effect you get while searching for a profile on the Facebook page on the Search Tab or how to get the Google auto-completion of characters and sentences with a long list of options to choose from? 

Here is one of the ways you can achieve it in ASP.net and AJAX. This code uses .Net framework and c# along with the ever cool AJAX functionality to achieve the same in a few lines of code. Follow the steps below to get the similar effect for people trying to achieve the above.



  • Drag and drop Auto-complete extender on page.
  • Write Text-box id as target id in auto-complete extender.


Here is an example:

In .aspx page write following code:


<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc2:AutoCompleteExtender ID="TextBox2_AutoCompleteExtender" runat="server"
DelimiterCharacters="" Enabled="True" ServiceMethod="GetCompletionList"
CompletionListCssClass="autocomplete" TargetControlID="TextBox1" UseContextKey="True"
MinimumPrefixLength="1">

In .cs page write the below code

public static string[] GetCompletionList(string prefixText, int count, string
contextKey)
{

MySqlConnection cn = new MySqlConnection("server=localhost; database=demo;
user id=root; password=");

DataSet ds = new DataSet();
DataTable dt = new DataTable();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
//Query
cmd.CommandText = "select name from table where name like @myParameter";
cmd.Parameters.AddWithValue("@myParameter", prefixText + "%");

try
{

cn.Open();
cmd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);

}
catch
{
}
finally
{
cn.Close();
}
if (ds != null)
{
dt = ds.Tables[0];
}

//Then return List of string(txtItems) as result
List<string> txtItems = new List<string>();
String dbValues;

foreach (DataRow row in dt.Rows)

{

//String From DataBase(dbValues)
dbValues = row["name"].ToString();
txtItems.Add(dbValues);

}

return txtItems.ToArray();

}

Its as simple as that!