Monday, November 19, 2012

Query to get last run queries(Recently Executed) in SQL Server


SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC




Longest Running query:

DBCC FREEPROCCACHE

Run following query to find longest running query using T-SQL.

SELECT DISTINCT TOP 10
t.
TEXT QueryName,
s.execution_count AS ExecutionCount,
s.max_elapsed_time AS MaxElapsedTime,
ISNULL(s.total_elapsed_time / s.execution_count, 0) AS AvgElapsedTime,
s.creation_time AS LogCreatedOn,
ISNULL(s.execution_count / DATEDIFF(s, s.creation_time, GETDATE()), 0) AS FrequencyPerSec
FROM sys.dm_exec_query_stats s
CROSS APPLY sys.dm_exec_sql_text( s.sql_handle ) t
ORDER BY
s.max_elapsed_time DESC
GO


 

Sunday, October 7, 2012

anroid emulator and virtual device

An AVD is a device configuration for the Android emulator that allows you to model different configurations of Android-powered devices.

To configure AVD we follow( for eclipse): Window-->AVD Manager

Creating AVD using AVD Manager

An AVD consists of:

A hardware profile: Defines the hardware features of the virtual device. For example, you can define whether the device has a camera, whether it uses a physical QWERTY keyboard or a dialing pad, how much memory it has, and so on.
A mapping to a system image: You can define what version of the Android platform will run on the virtual device. You can choose a version of the standard Android platform or the system image packaged with an SDK add-on.
Other options: You can specify the emulator skin you want to use with the AVD, which lets you control the screen dimensions, appearance, and so on. You can also specify the emulated SD card to use with the AVD.
A dedicated storage area on your development machine: the device's user data (installed applications, settings, and so on) and emulated SD card are stored in this area.

we can create as many AVDs as we would like to test on. It is recommended that we test our applications on all API levels higher than the target API level for our application.


Configuration Inf to Create Galaxy_Nexus AVD:

  • Target: Google APIs - API Level 15
  • Skin: Built-in WXGA720
Selecting skin sets the following hardware parameters, leave them as-is:
  • Hardware Back/Home: no
  • Abstracted LCD density: 320
  • Keyboard lid support: no
  • Max VM application heap size: 48
  • Device ram size: 1024
Galaxy Nexus has no SD card, just internal memory. Distinction between internal and external storage is important and can affect apps. To simulate this:
  • add SD Card support=no parameter;
  • launch emulator with -partition-size 1024 for 1GB internal memory, or use some other means to increase amount of internal memory available;
If you're working on camera apps, you'll also want to set correct number of cameras, and correct resolution.


To run the Emulator we need to select the AVD from the list and click on the start button. After that unlock the AVD.

To run a project, opening the file in the eclipse. click on h run button form the toolbar. eclipse automatically install the application in the running emulator and will run it.

To get complete Info about Emulator and AVD(Anroid Virtual Device)
http://developer.android.com/tools/devices/emulator.html

From a web search I got teh following link containing the various AVD Configuration:
common Anroid Virtual device configuraiton

Saturday, October 6, 2012

steps of android apps development

After preparing the environment, i was thinking about the next to do. coding or any other remaining steps. Then from the website i found a workflow for andapps development. I am sharing this here:






Workflow Detail

environment for anroid application development

Its the time to Disco(!!) Anroid Development.

Like all, recently I have tried to fall myself on that trap. Collecting some advise from one of my friend iam starting to put my footprint on that arena. He suggested me to follow a website:
http://developer.android.com/training/index.html

My friend is reliable for taking suggestion as he has recently completed a short course training of developing anroid application. He also provided me the required environment for starting the work. But i am interested to create the environment on my own hand( so that i can know the building blocks for developer environment).



First Requirement:
Willingness of mine
Ambition to do Earn
A PC
Making Time
No Excuse

And others are:
Eclipse( I have downloaded the mobile developer version of Eclipse, JUNO)
Anroid SDK
ADT(Anroid Developer Tools) Plugins for Eclipse



Next starting to install the above software:

1. Installation of Eclipse is nothing but to unzip the downloaded eclipse file and keep it in a save place(!!).(Requested not to keep it in System Drive).

2. To install Anroid SDK, just follow:

Your download package is an executable file that starts an installer. The installer checks your machine for required tools, such as the proper Java SE Development Kit (JDK) and installs it if necessary. The installer then saves the Android SDK Tools into a default location (or you can specify the location).

Make a note of the name and location of the SDK directory on your system—you will need to refer to the SDK directory later, when setting up the ADT plugin and when using the SDK tools from the command line.

Once the tools are installed, the installer offers to start the Android SDK Manager. Start it and continue with the installation guide by clicking the Next link on the right.

3. Now When I am in need to make relation between Eclipse and installed SDK.
Running Eclipse. Follow the following steps:
Window-->Preferences
But here I don't find any link point for Anroid. (Eclipse is not worry about Anroid at all). So Now I need to inform Eclipse that there is something in world called Anroid.

4. Install ADT Pluging for eclipse.
At Eclipse. Help-->(at bottom)Install New Software




Install Window will come. After clicking on Add button we get the window "Add Repository". Here we need to provide Name of the plugin and at bottom input box we will have to provide the url of the plugin.(In some cases if https:// does not work then we can use just http://).For ADT, the url will be https://dl-ssl.google.com/android/eclipse/ The best thing if we have a previously downloaded zip file of the plugin. In that case we we will have to click on Archive. Its helpful if you are confused with your internet connectivity.

Proceed next. Then the dependency plugins will also be listed. We will confirm it by clicking on OK.


Aftre installing the ADT, we will abole to create a relation between Eclipse and Anroid. No, if we traverse the Preferennces from the Window Menu of Eclipse we will get the Anroid listed in that window with configuration of SDK location.

Sunday, September 30, 2012

to delete files in linux using command

Tip for File Deletion:

When we try to delete a large amount of file using single linux command, we get error as:

/bin/rm: Argument list too long.


The problem is that when you type something like “rm -rf *”, the “*” is replaced with a list of every matching file, like “rm -rf file1 file2 file3 file4″ and so on. There is a relatively small buffer of memory allocated to storing this list of arguments and if it is filled up, the shell will not execute the program.

To get around this problem, a lot of people will use the find command to find every file and pass them one-by-one to the “rm” command like this:

find . -type f -exec rm -v {} \;


The above command may take too long.

I stumbled upon a much faster way of deleting files – the “find” command has a “-delete” flag built right in! Here’s what I ended up using:

find . -type f -delete

Using this command file deleting rate may be reached at 2000 files/second – much faster!

You can also show the filenames as you’re deleting them:

find . -type d -print -delete

…or even show how many files will be deleted, then time how long it takes to delete them:

root@devel# ls -1 | wc -l && time find . -type f -delete

real 0m3.660s
user 0m0.036s
sys 0m0.552s

Thursday, September 6, 2012

bin\javaw.exe not found when trying to install Oracle 11g 32 bit in Windows 7

Nothing more to do...
Just follow this steps

1) install JRE-1.7.0

2) add these 2 lines at the file oraparam.ini

JRE_VERSION=1.7.0
JRE_LOCATION=C:\Program Files\Java\jre7

3) comments the line :
1) install JRE-1.7.0

2) add these 2 lines at the file oraparam.ini

JRE_VERSION=1.7.0
JRE_LOCATION=C:\Program Files\Java\jre7

3) comments the line : JRE_VERSION=1.4.2

Thursday, June 7, 2012

Query to get Table Info of SQL server

Query to get Table info from a SQL server database is as:


select COLUMN_NAME,DATA_TYPE, CHARACTER_MAXIMUM_LENGTH,
NUMERIC_PRECISION, DATETIME_PRECISION,
IS_NULLABLE
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='table_name'

Sunday, May 27, 2012

servlet to export information in excel file


We can use servlet to export information in excel format. The code for this purpose may be as below:


String folder = "/excels/";

Three parameters have been sent using request as per requirement.fileNameToShow contains the value for the name of the file to save in client side
String fileNameToShow=request.getParameter("fileName");
String dbName=request.getParameter("dbName");
String query=request.getParameter("query");
String file_name = folder;

System.out.println("Report Name: " + file_name);
try {


ServletOutputStream servletOutputStream = response.getOutputStream();
byte[] bytes = null;


try {
ExcelHelper exlHelper = new ExcelHelper();
bytes = exlHelper.createExcell(getServletConfig().getServletContext().getRealPath(file_name), query, dbName);
response.setHeader("Content-Disposition", "inline;filename="+fileNameToShow+".xls");
response.setContentType("application/vnd.ms-excel");
response.setContentLength(bytes.length);
servletOutputStream.write(bytes, 0, bytes.length);

servletOutputStream.flush();
servletOutputStream.close();
mailMessage = mailMessage + ". REPORT produced successfully";
} catch (Exception e) {
// display stack trace in the browser
logger.error(e);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
response.setContentType("text/plain");
response.getOutputStream().print("Could not display report temporarily...");
//response.getOutputStream().print(stringWriter.toString());
mailMessage = mailMessage + ".ERROR catched when creating report.";
}
} catch (Exception e) {
System.out.println(e.getMessage());
logger.error(e);
} finally {
logger.info(mailMessage);
}



Expecting your kind suggestion for moderation of the code.

Friday, May 25, 2012

to create excel file using java


Apache POI API has been used for this purpose. This is used for manipulating various microsoft files.

This is a function of a class which generate an excel file after executing query in the database. Executing query in the database is not concerned here. This code insists on the creating file using POI. The function return the file in byte array( i do it as one of my requirement).


public byte[] createExcell(String fileLoc, String query, String dbName) {
Comments:
fileLoc: provide the location where to keep the file after generation.
query: database query on which you want to create excel
dbname: if you work with multiple database in your project

try {
String file_name = fileLoc +"/"+ (new Date()).getTime() + ".xls";
FileOutputStream fileOut = new FileOutputStream(file_name);
File file = new File(file_name);
if (file.exists()) {
file.delete();
}
delete file if a file name generated before with same name.


HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("Candidate List");
byte[] bytes;

GatewayPersonalInfo gwPersonalInfo = new GatewayPersonalInfo();
List lstPerson;
lstPerson = gwPersonalInfo.getAllPersonalInfo(query, dbName);
Above three lines has been used to import data from databases in list.
HSSFRow rowNew;
HSSFCell cellA, cellB, cellC, cellD, cellE;
rowNew = worksheet.createRow(0);
cellA = rowNew.createCell(0);
cellA.setCellValue("Sl. No");
cellB = rowNew.createCell(1);
cellB.setCellValue("App Serial No");
cellC = rowNew.createCell(2);
cellC.setCellValue("Full name");
cellD = rowNew.createCell(3);
cellD.setCellValue("Contact No.");
cellE = rowNew.createCell(4);
cellE.setCellValue("Email ID");
Just to create header in the file
if (lstPerson != null) {
if (!lstPerson.isEmpty()) {
Iterator itr = lstPerson.iterator();
PersonalInfo person;
int rowno = 1;
while (itr.hasNext()) {

person = (PersonalInfo) itr.next();
rowNew = worksheet.createRow(rowno);
cellA = rowNew.createCell(0);
cellA.setCellValue(rowno);
cellB = rowNew.createCell(1);
cellB.setCellValue(person.getSerialNo());
cellC = rowNew.createCell(2);
cellC.setCellValue(person.getFullName());
cellD = rowNew.createCell(3);
cellD.setCellValue(person.getContactNo());
cellE = rowNew.createCell(4);
cellE.setCellValue(person.getEmail());
System.out.println(rowno + " row added.");
rowno = rowno + 1;
}
}
}
workbook.write(fileOut);

fileOut.flush();
fileOut.close();

FileInputStream fin = new FileInputStream(file);
bytes = new byte[(int) file.length()];
fin.read(bytes);
file.delete();
After taking in the byte array, file is being deleted. But it depends on your requirements. You can keep the file.
return bytes;

} catch (Exception ex) {
System.out.println(ex);
logger.error(ex);
} finally {
}
return null;
}
Kindly provide your suggestion for further modification.

Thursday, May 24, 2012

Servlet to export jasper report in excel

Its very important issue to export jasper report to excel format. This can be done through a servlet in JSP application. The servlet code may be as bellow:

In tis case I have used some code as part of many times edit. It can be summarize.


This servlet is able to handle different no. of parameters and different reports.

We just need to call this servlet as below:

link = "/JRExcelExport?rname=candidateList&pname=posiCode=" + posiCode + "@qValue1=" + qValue1 + "@qValue2=" + qValue2 ;
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(link);
dispatcher.forward(request, response);

The value of rname is the name of the report. And all the parameters would be attached after the pname

package dbbl.paul.recruitment.servlets;

import dbbl.paul.recruitment.dal.dbconnector.ConnectionHandler;
import java.io.*;
import java.sql.Connection;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.*;

import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import org.apache.log4j.Logger;


public class JRExcelExport extends HttpServlet {

final static Logger logger = Logger.getLogger(ReportManager.class);

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
logger.trace("Trying to Generate report:processRequest");

String mailMessage = "";
String folder = "/reports/";
JasperPrint jasperPrint = null;

String rpt_name = request.getParameter("rname");
String report_name = rpt_name + ".jasper";
String file_name = folder + report_name;

mailMessage = "RPTNAME=" + rpt_name;
System.out.println("Report Name: " + file_name);
try {
HashMap hm = new HashMap();
String param_name = request.getParameter("pname");
System.out.println(param_name);

if (param_name != null) {

if (!param_name.equals("")) {
String split_param[] = param_name.split("@");
String tmp_param[];
for (int i = 0; i < split_param.length; i++) { System.out.println(split_param); tmp_param = split_param[i].split("="); hm.put(tmp_param[0], tmp_param[1].replaceAll("NULL", "")); } } mailMessage = mailMessage + ". PARAMETERS collected successfully"; } ServletOutputStream servletOutputStream = response.getOutputStream(); File reportFile = new File(getServletConfig().getServletContext().getRealPath(file_name)); Connection con = null; try { con = ConnectionHandler.getConnection_OnlineJob(); jasperPrint = JasperFillManager.fillReport(reportFile.getPath(), hm, con); generateXLSOutput(rpt_name, jasperPrint, response); } catch (JRException e) { // display stack trace in the browser logger.error(e); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); e.printStackTrace(printWriter); response.setContentType("text/plain"); response.getOutputStream().print("Could not display report temporarily..."); //response.getOutputStream().print(stringWriter.toString()); mailMessage = mailMessage + ".ERROR catched when creating report."; } } catch (Exception e) { System.out.println(e.getMessage()); logger.error(e); } finally { logger.info(mailMessage); } } private void generateXLSOutput(String reportname, JasperPrint jasperPrint, HttpServletResponse resp) { String reportfilename = reportname + ".xls"; try { JExcelApiExporter exporterXLS = new JExcelApiExporter(); exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint); exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE); exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, resp.getOutputStream()); resp.setHeader("Content-Disposition", "inline;filename=" + reportfilename); resp.setContentType("application/vnd.ms-excel"); exporterXLS.exportReport(); } catch (Exception ex) { logger.trace(ex); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; }//
}

Wednesday, May 23, 2012

Starting of J2ME application


# J2ME
—Java 2 Platform, Micro Edition, is the Java platform meant to run on small devices. Currently, these devices are typically cell phones or PDAs, but J2ME is also used on other embedded systems. A configuration, a profile, and optional packages are what compose a J2ME platform.

# CLDC
—Connected Limited Device Configuration is a J2ME configuration that is currently most often used on mobile phones. It contains a run time environment and a core API that are appropriate for the limited processor speed and memory size of mobile devices.

# MIDP
—Mobile Information Device Profile is the set of APIs that provides higher-level functionality required by mobile applications, such as displayable components (“screens”) and network communication.

#MIDlet
—A class required by all MIDP applications. It acts as the interface between the application and the device on which it is running. A MIDlet is similar to a main class in a J2SE project.

# Preverification
—When building an application that runs with CLDC, all compiled classes must be preverified. Preverification is a process that adds annotations used by the CLDC JVM to a class file’s bytecode. The preverification process also ensures that the class contains only code that will run on its CLDC version.

# Device fragmentation
—Term used for the variations between mobile platforms that prevent a single application from automatically running optimally on all phones. These differences can be physical (screen size, screen color depth, available memory, and so on) or software related (available APIs, CLDC/MIDP version, and so on).

# Preprocessor
—Though preprocessor is not a J2ME-specific term, NetBeans Mobility Pack ships with a preprocessor that is used as part of its device fragmentation solution. The preprocessor is an Ant task that runs before files are compiled. It looks for special Java comment tags within the file and adds or removes line comments based on these tags.

# Obfuscation
process that makes class files difficult to reverse engineer. This is usually accomplished by, at least, replacing names of packages, classes, methods, and fields with short identifiers. This has the result of decreasing the size of your application and, therefore, is an important aspect of the mobile application build process.

more

Thursday, March 29, 2012

different scopes of managed bean in JSF

Managed beans can have different scopes. They are as:

1. Request
2. Session
3. Application
4. None

A scope of request means that the bean is only available in a single HTTP request. Managed beans can also have session scope, in which case they are available in a single user's HTTP session. A scope of application means that the bean is accessible to all users in the application, across user sessions. Managed beans can also have a scope of none, which means that the managed bean is not stored at any scope, but is created on demand as needed. Additionally, managed beans can have a scope of view, in which case the bean is available until the user navigates to another page. View scoped managed beans are available across Ajax requests.

Wednesday, March 28, 2012

PROJECT_STAGE in configuration file of JSF project

when we start a JSF project using netbeans, we get a skleton project containing two files at first.

a single facelet file called index.xhtml,
a web.xml configuration file


web.xml is the standard, optional(from version 3.0) configuration file needed for Java web.

If we observer we find that the NetBeans automatically sets the JSF project stage to Development, setting the project stage to development configures JSF to provide additional debugging help not present in other stages.

The following are the valid values for the javax.faces.PROJECT_STAGE context parameter for the faces servlet:

1.Development
2. Production
3.SystemTest
4.UnitTest

Development project stage adds additional debugging information to ease development. The Production project stage focuses on performance. The other two valid values for the project stage (SystemTest and UnitTest), allow us to implement our own custom behavior for these two phases.

The javax.faces.application.Application class has a getProjectStage() method that allows us to obtain the current project stage. Based on the value of this method, we can implement the code that will only be executed in the appropriate stage.

Wednesday, March 21, 2012

Line limit for Text Area

In a HTML page, text area is used to accept multiple line texts at once. But some times, we may need to fixed the no. of line in a text area of web page. There is not attribute available for this purpose. This will have to implemented using javascript. The required function to check the no. of line as well as the no. of characters in a text area may be as:

<script type="text/javascript">

var alert_title='Input Restriction';

function limitTextarea(textarea,maxLines,maxChar){
var lines=textarea.value.replace(/\r/g,'').split('\n'),
lines_removed,
char_removed,
i;
if(maxLines&&lines.length>maxLines){
//alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
//if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)textarea.value=lines.join('\n')
}

function watchTextarea(){
document.getElementById('resticted').onkeyup()
}

function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}
</script>

and the above function can be called as

</script>
</head>
<body>
<textarea onkeyup="limitTextarea(this,6,40)" style="width:400px;height:200px" wrap="off" id="resticted" onfocus="focus_watch=setInterval('watchTextarea()',250)" onblur="clearInterval(focus_watch)">some text</textarea>
</body>
</html>

why JSF?

Java Server Faces technology , developed by Java Community Process(JCP) ,simplifies the development of Java Based web applications.
Java Server Faces is a component oriented and event driven framework for web applications. JSF eases the development of GUI for web applications. JSF allows the programmers to work with extensible user interfaces like buttons, text boxes, check boxes etc... Programmer writes the code for particular event such as button clicked. This makes programming much easier and now the there is no need to write request and response processing logic.

Main feature of JSF is ease of use. Developing web applications is easier and faster than other frameworks like struts because JSF supports UI components and easy event handling.JSF is based on well established Model-View-Controller (MVC) design pattern. Applications developed using JSF frameworks are well designed and easy to maintain then any other applications developed in JSP and Servlets.

JSF includes mainly:
Set of APIs to represent and manage state of components that helps server side validation, event handling, page navigation, data conversion etc.
JSP custom tag library to create UI components in a view page.

The UI (user interface) created using JSF technology runs on server and output is shown to the client. Goal of JSF is to create web applications faster and easier. Developers can focus on UI components, events handling, backing beans and their interactions rather than request, response and markup. JSF hides complexities to enable developers to focus on their own specific work.

Monday, March 12, 2012

fonts problem in jasper report for pdf

when we export jaspert report to pdf format, we face problem with the font of the file. As, jasper report deal with its own true type font only for pdf. For this reason, we need to use the steps of font extension. This can be done following the steps below:

Ingredients: Jar file of jasperreports-fonts-v.v.v.(v stand for Version), true type fonts

1. Download the jasperreports-fonts-v.v.v(i.e jasperreports-fonts-4.0.1) jar file to modify according your requirements.
2.Right click on the jar file and select Extract to jasperreports-fonts-v.v.v.
3.At the root directory of the extracted folder, there is a properties file named: jasperreports_extension.properties

The file contains:
net.sf.jasperreports.extension.registry.factory.simple.font.families=net.sf.jasperreports.engine.fonts.SimpleFontExtensionsRegistryFactory
net.sf.jasperreports.extension.simple.font.families.dejavu=net/sf/jasperreports/fonts/fonts.xml

For the practise, here we will try to add the Times New Roman fonts to this jar. So, now we will have to add the following lines at the above file.
net.sf.jasperreports.extension.simple.font.families.timesnewroman=net/sf/jasperreports/fonts/fonts.xml

After adding we will get the file as:

net.sf.jasperreports.extension.registry.factory.simple.font.families=net.sf.jasperreports.engine.fonts.SimpleFontExtensionsRegistryFactory
net.sf.jasperreports.extension.simple.font.families.dejavu=net/sf/jasperreports/fonts/fonts.xml
net.sf.jasperreports.extension.simple.font.families.timesnewroman=net/sf/jasperreports/fonts/fonts.xml

4.Now, create the specific location to save the font collection. for this purpose, we create a directory in the location of ~/jasperreports-fonts-v.v.v\net\sf\jasperreports\fonts\. The name of the file will be timesnewroman for our case.

5. Now we need to add the collections of true type fonts at the above newly created location. Generally four files will be added as the representative of four categories: normal, bold, italic, bold italic.

6. Now its the time to modifying the fonts.xml file. We need to add the definition of the font to tis xml file. For our case, the definition will be as:

<fontFamily name="Times New Roman">
<normal>net/sf/jasperreports/fonts/timesnewroman/times.ttf</normal>
<bold>net/sf/jasperreports/fonts/timesnewroman/timesbd.ttf</bold>
<italic>net/sf/jasperreports/fonts/timesnewroman/timesi.ttf</italic>
<boldItalic>net/sf/jasperreports/fonts/timesnewroman/timesbi.ttf</boldItalic>
<pdfEncoding>Identity-H</pdfEncoding>
<pdfEmbedded>true</pdfEmbedded>
<exportFonts>
<export key="net.sf.jasperreports.html">'Times New Roman', Arial, Helvetica, sans-serif</export>
<export key="net.sf.jasperreports.xhtml">'Times New Roman', Arial, Helvetica, sans-serif</export>
</exportFonts>
<!--
<locales>
<locale>en_US</locale>
<locale>de_DE</locale>
</locales>
-->
</fontFamily>

7. after completion of customization, again we will make the jar from the raw files. Entering into the extracted folder, select all the files. right clcik and select the option Add to Archive. select the type to ZIP. At the end of the name, change the extension to .jar.

8. After that use this jar where you want.



--
For converting code to show on blog, i have used http://centricle.com/tools/html-entities/

Thursday, February 23, 2012

Setting Maximum no. of characters in jTextField for Swing Application

Sometimes we need to fixed the maximum size of a text field. For this purpose, we need to implement a document containing an overriding function of plain document.

public class MaxLengthTextDocument extends PlainDocument {

private int maxChars;

@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if(str != null && (getLength() + str.length() < getMaxChars())){ super.insertString(offs, str, a); } } /** * @return the maxChars */ public int getMaxChars() { return maxChars; } /** * @param maxChars the maxChars to set */ public void setMaxChars(int maxChars) { this.maxChars = maxChars; } }



after that we will have to set the following line after initComponents() of view file.


MaxLengthTextDocument maxLength = new MaxLengthTextDocument();
maxLength.setMaxChars(12);//50 is a maximum number of character
this.txtMobileNo.setDocument(maxLength);

Wednesday, February 22, 2012

Executing a JAR file using Windows Task Scheduler

Generally, when we click over a jar file , it executes. But if we are in need of executing a jar file using Windows Scheduler it invites some barriers(!).
We are not in need to do something incredible, just usingthe Windows Task Scheduler. . We need to customize the various prefrences for setting up the task in the windows scheduler.

Since a JAR file is not a Windows executable file, all you need to do is:

1. Type task in the run from the start menu(for windows 7).
2. from the action panel of the right side of the window, select Create task.
3. Filling all the parameters of General and Trigger panel, from the action panel
Set program or script to the location of java.exe from the specified location of the jre folder.
C:\Program Files\Java\jre6\bin\java.exe
Set add arguments option to something like the command line to execute the jar.
-jar D:\jarFileLocation\jarFile.jar




Thursday, February 2, 2012

MSDTC on server 'servername' is unavailable

MSDTC on server 'servername' is unavailable

By default, when a stand-alone instance of Microsoft SQL Server exists in a cluster environment, the SQL Server-based instance is set to start automatically. If the host node is rebooted, you may receive the following error message when you issue commands that are related to distributed transactions:

RESOLUTION
On the server where the trigger resides, you need to turn the MSDTC service on. You can this by clicking START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES. Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.

Friday, January 27, 2012

Rich Snippets to improve the display of search results

all most all the Internet user use the search engine to find out the link he/she needs so its an important issue to present a website attractively fro the first glance at the search results pages.
a web developer may control the view of a web page in the search results. If its not controlled by the web developer, then search engines use the default mechanism to show the info about the web page.
One of the mechanisms is Rich Snippets to present a website information in the search result.

The above screen shot is of a search result of a blog powered by blogger.com. Here the rich snippets is used by the blogger.
As the same way we are able to use rich snippets for our web site. Its nothing more than adding the tag to make it sensible to a search engine about the content of the site page to show on the search results.



An important link to a testing tools for Rich snippets of google web master.With rich snippets, webmasters with sites containing structured content such as review sites or business listings—can label their content to make it clear that each labeled piece of text represents a certain type of data: for example, a restaurant name, an address, or a rating.

This kind of markup is designed for sites containing specific types of structured data. Google currently supports the following information types: reviews, people profiles, products, business listings, recipes, and events.
Providing this information doesn't affect the appearance of your content on your own pages, but it does help Google better understand and present information from your page.

The properties supported by Google are based on a number of different formats. For more information, see the following articles:

* About microdata
* About microformats
* About RDFa

MicroData:

# information(specific type item)
# properties related to the item.
#Microdata uses simple html(i.e span, div) tags to assign brief and descriptive names to items and properties.

Exmaple of Microdata html marked up:
<div itemscope itemtype="http://data-vocabulary.org/Person">
My name is <span itemprop="name">Bob Smith</span>
but people call me <span itemprop="nickname">Smithy</span>.
Here is my home page:
<a href="http://www.example.com" itemprop="url">www.example.com</a>
I live in Albuquerque, NM and work as an <span itemprop="title">engineer</span>
at <span itemprop="affiliation">ACME Corp</span>.
</div>


Microformat:

Microformats are simple conventions (known as entities) used on web pages to describe a specific type of information —for example, a review, an event, a product, a business, or a person. Each entity has its own properties. For example, a Person has the properties name, address, job title, company, and email address.

In general, microformats use the class attribute in HTML tags (often span or div) to assign brief and descriptive names to entities and their properties. Here's an example of a short HTML with micro format showing basic contact information for Bob Smith.

<div class="vcard">
<img class="photo" src="www.example.com/bobsmith.jpg" />
<strong class="fn">Bob Smith</strong>
<span class="title">Senior editor</span> at <span class="org">ACME Reviews</span>
<span class="adr">
<span class="street-address">200 Main St</span>
<span class="locality">Desertville</span>, <span class="region">AZ</span>
<span class="postal-code">12345</span>
</span>
</div>

RDF
RDFa is a way to label content to describe a specific type of information, such as a restaurant review, an event, a person, or a product listing. These information types are called entities or items. Each entity has a number of properties. For example, a Person has the properties name, address, job title, company, and email address.

In general, RDFa uses simple attributes in XHTML tags (often span or div) to assign brief and descriptive names to entities and properties. Here's an example of a short HTML with RDF showing basic contact information for Bob Smith.

<div xmlns:v="http://rdf.data-vocabulary.org/#" typeof="v:Person">
My name is <span property="v:name">Bob Smith</span>,
but people call me <span property="v:nickname">Smithy</span>.
Here is my homepage:
<a href="http://www.example.com" rel="v:url">www.example.com</a>.
I live in Albuquerque, NM and work as an <span property="v:title">engineer</span>
at <span property="v:affiliation">ACME Corp</span>.
</div>


--
A shared markup vocabulary makes easier for webmasters to decide on a markup schema and get the maximum benefit for their efforts.So, in the spirit of sitemaps.org, search engines have come together to provide a shared collection of schemas that webmasters can use.


We can use the schema.org vocabulary, along with the microdata format, to add information to your HTML content. While the long term goal is to support a wider range of formats, the initial focus is on Microdata. This guide will help get us up to speed with microdata and schema.org, so that we can start adding markup to our web pages.

Thursday, January 26, 2012

To know the databse version in SQl Server

To know the version of the Database by query:


Select @@version as x


another query for a more specific results, we can execute

Select SERVERPROPERTY('productversion') As [Version],
SERVERPROPERTY('productlevel') As [Level],
SERVERPROPERTY('edition') As [Edition]

To save new line to vachar field of SQL Database Table

For various purposes we are in need to multi-line text in the database fields. It differs from OS to OS or databases to databases. Generally to save a multi-line text to a varchar field of a table in sql server database, we can use just two special characters:

char(13)+char(10)

This bondage of 13 years old boy and the 10 years old girl make a new position of the parent's line(Just love story to remember!!!!)



INSERT INTO [TestDB].[dbo].[testTable]
([TestID]
,[TestName]
)
VALUES
('ROW 2',
'Everybody should love his God'
+CHAR(13)+CHAR(10)+'No matter which one he believes'
+CHAR(13)+CHAR(10)+'God loves us so much.'
+CHAR(13)+CHAR(10)+'He is the almighty of this world')





If we execute the above query the table will accepts and holds the 2nd field with the 3 new line also. And the Select query with return them as intact.



Sunday, January 22, 2012

Performance issues for Web Development

Performance is the main concern to develop website or web application. Web developers may follow the following steps for that.
1. Make Fewer HTTP Requests
2. Use a Content Delivery Network
3. Add an Expires or a Cache-Control Header
4. Gzip Components
5. Put Stylesheets at the Top
6. Put Scripts at the Bottom
7. Avoid CSS Expressions
8. Make JavaScript and CSS External
9. Reduce DNS Lookups
10. Minify JavaScript and CSS
11. Avoid Redirects
12. Remove Duplicate Scripts
13. Configure ETags
14. Make Ajax Cacheable
15. Flush the Buffer Early
16. Use GET for AJAX Requests
17. Post-load Components
18. Preload Components
19. Reduce the Number of DOM Elements
20. Split Components Across Domains
21. Minimize the Number of iframes
22. No 404s
23. Reduce Cookie Size
24. Use Cookie-free Domains for Components
25. Minimize DOM Access
26. Develop Smart Event Handlers
27. Choose over @import
28. Avoid Filters
29. Optimize Images
30. Optimize CSS Sprites
31. Don’t Scale Images in HTML
32. Make favicon.ico Small and Cacheable
33. Keep Components under 25K
34. Pack Components into a Multipart Document
The items above has been reference from Yahoo’s Developer Nework. Full details on each of these items is available at:
http://developer.yahoo.com/performance/rules.html

Friday, January 6, 2012

Copy table to a different database on a different SQL Server

Easily information from t table to another table can be copied. If these tables are from two different database on the same server it also be possible to perform query using the following:



INSERT INTO bar.tblFoobar( *fieldlist* )
SELECT *fieldlist* FROM foo.tblFoobar



or

SELECT *
INTO DestinationDB.MyDestinationTable
FROM SourceDB.MySourceTable



The problem arise when we want to copy information from he table of one database to that of another database. And in sqo server this can be performed by a technique known as linked server.
------------------------


Yes. add a linked server entry, and use select into using the four part db object naming convention.

select * into targetTable from [sourceserver].[sourcedatabase].[dbo].[sourceTable]




................
We can add a linked server entry following the below information


1. Click Start, click All Programs, click Microsoft SQL Server 2005 and then click SQL Server Management Studio.


2.In the Connect to Server dialog box, specify the name of the appropriate SQL Server, and then click Connect.


3. In SQL Server Management Studio, double-click Server Objects, right-click Linked Servers, and then click New Linked Server.


4. In the New Linked Server dialog box, on the General page, in Linked server, enter the full network name of the SQL Serveryou want to link to.

5.This procedure often refers to the server you are linking to as the remote server. This is for convenience only, to indicate the relationship of the linked (“remote”) server to the local server. Do not confuse this usage with the obsolete remote server functionality in SQL Server.



Under Server type, click SQL Server.

6. In the left pane of the New Linked Server dialog, under Select a page, choose Security.


7.You will need to map a local server login to a remote server login. On the right side of the Security page, click the Add button.


8. Under Local Login, select a local login account to connect to the remote server. Check Impersonate if the local login also exists on the remote server. Alternatively, if the local login will be mapped to a remote SQL Server login you must supply the Remote User name and Remote Password for the remote server login.

To use impersonation, your SQL Server configuration and login accounts must meet the requirements for delegation. For more information about impersonation and delegation, see http://go.microsoft.com/fwlink/?LinkID=132854.



9. In the left pane of the New Linked Server dialog, under Select a page, choose Server Options. Set the Rpc and Rpc Out parameters to True, and then click OK.