LOAD IMAGES DYNAMICALLY INTO JASPER REPORTS

November 13, 2009

If you want to insert images from the file system (e.g. C:\images folder) into jasper reports at runtime, for example changing a logo depending on user selection or simply allowing the user to browse for his or her image to be displayed  in the report then here is a simple process of doing that.

Let start with the report design using ireport. In this instance the picture will be passed to the report as a parameter.

So let’s create a parameter in our report and call it “photo”

image

As shown in the picture above, the data type of our parameter should be “java.lang.Object”

After this, drag the image , from the tool bar, on to your report.Right click on the image and choose “Properties” from the menu

image

Under the image tab of the dialog box, make sure you select “java.awt.image” for the Image Expression Class. Once this is done, you are done with the report design

Lets go to netbeans , do some coding and connect our designed report to a java application.

First we need to declare a variable of type image,

Image photo;

Also we create a method , which on click of a button, loads a picture from the file system and initializes the “photo: variable.

JFileChooser fc = new JFileChooser();

private void getPicture() {

fc.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "gif", "bmp"));

if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {

fc.setCurrentDirectory(fc.getCurrentDirectory());

ImageIcon icon = new ImageIcon(fc.getSelectedFile().getAbsolutePath());

icon = new ImageIcon(icon.getImage().getScaledInstance(350, 350, Image.SCALE_DEFAULT));

photo = icon.getImage();

}

After getting our picture, create an instance of the Map class and pass our “variable” as a parameter.

Map<String, Object> param = new HashMap<String, Object>();

param.put("photo", photo); //the “photo” should be the same name as the parameter name in our report

We then create a method that passes our created parameter to the report and we are done. below is the method that does the job.

private void generateReports(String name, Map param) {

try {

String source = "C:/sabonay/jasperreports/" + name + ".jrxml";

if (new File(source).exists() == false) {

xputils.showMessage("Please  report Source does not exist");

return;

}

JasperReport jasperReport = JasperCompileManager.compileReport(source);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param, new JREmptyDataSource());

JasperViewer.viewReport(jasperPrint, false);

//the false parameter makes sure the application does not close on closing the report

} catch (Exception e) {

System.out.println("reports Error " + e.toString());

}}

Make sure to reference the necessary jasper jar files in your application


STRINGS IN JAVA

October 30, 2009

“Wow !!!! Now Thus Intereeessssting” That was how i exclaimed when i saw these interesting features of the STRING class in java. All this while when i wanted to convert a character array to a string , i had to go through a loop. For example

String password = “” ;
char[] pass = this.txtPassword.getPassword();
for (int i = 0; i < pass.length; i++) {
password = password + pass[i];
}

But this char[] pass can easily be converted to string by just a line of code:

char[] pass = this.txtPassword.getPassword();
String password=new String(pass);

Also another interesting feature of the string class is that you can easily get the string value out of a byte array and vice versa with so much ease. check this.

byte[] array=”sdfdfd”.getBytes();
String string=new String(array);

These are not all, there are more interesting features, exploree!!!!

Fellows, enjoy the weekend


FORM.SHOWDIALOG() IN JAVA

October 21, 2009

Have you wondered how to show a panel(form) as a dialog in java applications as done in .NET applications by using the form.showDialog() method?  For example, when a user selects “Add New” from a Customer combobox, the customer panel shows as a dialog for a new entry before the user can continue. If you have been searching for this, here is your stop.

We will be making use of one JDialog, and your FORMS(JPanels in this sense).

To implement this add a JDialog to your application. Declare a variable contentPane and add the constructor like the one specified below.

private Container contentPane = null;

public popupsjdialog(java.awt.Frame parent, JPanel panel, boolean modal) {
//super(parent, modal);
contentPane = this.getContentPane();
initComponents();
this.setSize(panel.getSize().width + 30, panel.getSize().width + 50);
panel.setLocation(10, 30);
contentPane.add(panel);
repaint();
this.setLocationRelativeTo(null);

}

Your are now done. Now to show any JPanel as a dialog add the following code to your event.

helpdetailpanel hd = new helpdetailpanel(helpContent);
hd.setSize(700, 700);
popupsjdialog d = new popupsjdialog(null, hd, true);
d.setVisible(true);

Helpdetailpanel is a Jpanel (form) you want to show as a dialog and the popupsjdialog is an instance of the Jdialog we created its constructot above.

Cheers !!!!!!!!!!!!!!!!!


DEPLOYING ASP.NET APPS USING IIS 7

October 10, 2009

You have finished developing your ASP.net application using VS 2005 in Windows Vista environment and you need to deploy, just go ahead and deploy in the vista environment, you do not have to look for Windows XP before you can do this. Here are few steps to follow to deploy your application using IIS 7 .

  1. First make sure all the components of the IIS server is installed on your system. To do this, Go to Start > Control Panel >Programs and Features and the click on the “Turn Windows features on or off” on the left task pane of the window as shown below.

  2. On the windows feature dialog box that pops up, make sure the Internet Information Service node and all its child nodes are checked as shown below or else get your original Windows Vista CD, check all the nodes and install these features.

  3. To access the IIS Manager after the installation, Go to Start>Control Panel>Administrative Tools >Internet Information Services (IIS) Manager or go to run (Window Key + R) and enter “inetmgr” and you will get an interface like the one below.

  4. Now we are good to go on and deploy our ASP.Net Web Application. Navigate to the Default Web Site Node, then right click on it and choose “Add Application” from the context menu. A dialog box will pop up as shown below. The alias is the name of your website, for example if you enter Ghana, or accra , or kumasi, when accessing your website from your local computer, you will be typing “localhost/Ghana, or localhost/accra, or localhost/Kumasi”

    Click on the “Physical path:” button to browse for the website folder of your application and click on the “OK” button.

  5. A new node with the name you entered in the alias textbox will appear under the “Default Web Site” node. Select the node, and make sure your connection string, default documents are set to the required values. The picture below clarify these

  6. After making the required changes, you are done. Make sure your IIS server is running (you can check this by clicking on the “Default Web Site” node and on the right task pane, under manage web site, make sure the “star” link is disabled else click on it to start the server). Go to your browser and enter your URL, in this case “http://localhost/ghana” or right click your application from IIS GUI and select browse.

EXPORTING THE CONTENT OF A DATASOURCE INTO EXCEL

October 4, 2009

Hi fellows, this post is about exporting the content of your data source (dataset, data table, data grid) into MS-Excel using VB.NET. All you need to is to read the data from your data source into a 2-dimensional array and then send the content straight to excel. With this you don’t have to be adding rows to excel one after the other.

Let’s start, we have a data table called “dsstudents” with 5 columns “IndexNo, Name, Year Group, Program, Gender”. We then declare a variable Private Students(,) As String as our 2-dimensional array. We are then ready to go (code). Note that we are using late binding to the excel objects here, thus we are not referencing the excel object at the design time but it’s done in runtime.

Below are two methods that will get the job done. Cheers!!!!

Private Sub readContent()

If Me.dsStudent.Rows.Count > 0 Then
ReDim Me.courses(Me.dsStudent.Rows.Count + 2, 7)

For i As Integer = 0 To
Me.dsStudent.Rows.Count – 1

’setting the column headers for each column

students(0, 0) = “Index No”

students(0, 1) = “Students’ Name”

students(0, 5) = “Year group”

students(0, 6) = “Program Name”

students(0, 11) = “Student Gender”

‘getting the actual content from our datasource

students(i + 2, 0) = Me.dsStudent.Rows(i)(0).ToString

students(i + 2, 1) = Me.dsStudent.Rows(i)(1).ToString

students(i + 2, 3) = Me.dsStudent.Rows(i)(2).ToString

students(i + 2, 4) = Me.dsStudent.Rows(i)(3).ToString

students(i + 2, 5) = Me.dsStudent.Rows(i)(4).ToString

Next

createExcel()

End If

End Sub

The implementation of the createExcel() method

Private Sub createExcel()

Dim oExcel As Object

Dim oBook As Object

Dim oSheet As Object

‘Start a new workbook in Excel.

oExcel = CreateObject(“Excel.Application”)

oBook = oExcel.Workbooks.Add

‘Add headers to the worksheet on row 1.

oSheet = oBook.Worksheets(1)

oSheet.Range(“c1″).Value = “EXPORTING DATASOURCE CONTENT INTO EXCEL”

‘Sending the data to Excel by specifying where to start from (cell) and the rows and ‘columns need.

oSheet.Range(“B8″).Resize(Me.dsStudent.Rows.Count + 2, 7).Value = Me.setudent

oExcel.visible = True

oSheet = Nothing

oBook = Nothing

oExcel.quit()

oExcel = Nothing

GC.Collect()

End Sub


GENERATING RANDOM NUMBERS IN JAVA

September 27, 2009

Hi Fellows, in my previous post (GENERATING UNIQUE RANDOM STRING AND ITS APPLICATION) , I blogged about generating random numbers in VB.net.

Below is its version in JAVA. Enjoy !!!

private String generateRandom(Integer key) {

StringBuffer randomString = new StringBuffer();

String letters = “abcdefghijklmnopqrstuvwxyz“;

String numbers = “0123456789“;

char[] numbersArray = numbers.toCharArray();

char[] lettersArray = letters.toCharArray();

Integer arrIndex = -1;

 

for (int i = 0; i <= key; i++) {

//generate any random number from 1 -100, if them number is even,

//pick a letter randomly else pick a number

int rnd = new Random().nextInt(100);

if (rnd % 2 == 0) {

arrIndex = new Random().nextInt(24);

randomString.append(lettersArray[arrIndex]);

} else {

arrIndex = new Random().nextInt(10);

randomString.append(numbersArray[arrIndex]);

}

}

return randomString.toString();

}

Below is a sample generated strings when application is run.


GENERATING UNIQUE RANDOM STRING AND ITS APPLICATION

September 11, 2009

Generating random numbers can be sometimes frustrating, especially when you want them to be unique.

Example in this instance is when you give users unique usernames when they register with you websites.

Below is a simple function to generate random numbers. To make these generated random strings unique (for the purpose of your application you can add the row index, when inserting it into a database, to make it unique. In this case you will be generating always unique random variables)

Function Generate() As String
‘key_chars, is the length of random numbers u want to generate

Dim i_key As Integer

Dim RandomNo As Single
Dim arrIndex As Int16

Dim sb As New StringBuilder

Dim RandomLetter As String

lstLetters = “abcdefghijklmnopqrstuvwxyz”

lstNumber = “0123456789″

LettersArray = Me.Key_Letters.ToCharArray

NumbersArray = Me.lstNumber.ToCharArray


For i_key = 1 To Key_Chars

Randomize()

RandomNo = Rnd()

arrIndex = -1 ‘the number 101 was randomly chosen

If (CType(Random1 * 101, Integer)) Mod 2 = 0 Then

‘if the number generated from the if condition is even get a letter else get a number

‘ generate a random number from the letters array


Do While arrIndex < 0

arrIndex = Convert.ToInt16(LettersArray.GetUpperBound(0) * RandomNo)

Loop

RandomLetter = LettersArray(arrIndex)

sb.Append(RandomLetter)

Else

Do
While arrIndex < 0

arrIndex = Convert.ToInt16(NumbersArray.GetUpperBound(0) * RandomNo)

Loop

RandomLetter = NumbersArray(arrIndex)

sb.Append(RandomLetter)

EndIf

Next

Return sb.ToString

End Function


How to Encrypt Strings in .NET –The easiest way

September 8, 2009

Whatever application you develop been it for the national security or for a one-man provision kiosk, some data should be encrypted. Things like database configuration variables, user login passwords and some application settings. In this article we will go through two methods of encrypting your variable with a basic knowledge in computing. The first been saving your records in bytes and the other in scrambled strings

Saving as bytes

Public Shared Function encrypt(ByVal password As String) As Byte()

Dim byteValue() As Byte = Encoding.UTF8.GetBytes(password)

Return byteValue

End Function

 

Public Shared Function decrypt(ByVal pass As Byte()) As String 

Dim password As String = Encoding.UTF8.GetString(pass)

Return password

End Function

 

For example, to encrypt your password fields, in the database design make the data type of the field and image. Then in your code write the simple methods below. You are done. At least you have encrypted the field to some extent; no one can easily get the password by easily checking from the backed

Encrypting Strings

In cases where you want to save your password as strings, or saving some application settings in the “My Settings” one simple way is by encrypting the string by adding a chosen value to each character in the string to change its meaning. Check the methods below

    Private Const code As Integer = 5

    Private Function StrEncrypt(ByVal str As String) As String

        Dim scrambled As String = “”

        Dim letters() As Char = str.ToCharArray

        For i As Integer = 0 To letters.Length – 1

            scrambled = scrambled + ChrW(AscW(letters(i)) + code)

        Next

        Return scrambled

    End Function

 

    Private Function StrDencrypt(ByVal str As String) As String

        Dim unscrambled As String = “”

        Dim letters() As Char = str.ToCharArray

        For i As Integer = 0 To letters.Length – 1

            unscrambled = unscrambled + ChrW(AscW(letters(i)) – code)

        Next

        Return unscrambled

    End Function

Check the picture below ,when the runnibg the application

encrpt


READING SYSTEM PROPERTIES USING VB.NET

August 30, 2009

Hi fellows, this is a simple way of retrieving system properties through your vb.net application. For example how to know the system owner, the operating system version, the processor information, etc

Below is the code which is handled by a form_load event

Don’t forget this import; Imports Microsoft.Win32

Try

            Dim info As String = “”

            Dim oReg As RegistryKey

            oReg = Registry.LocalMachine.OpenSubKey(“SOFTWARE\Microsoft\Windows NT\CurrentVersion”)

            info = info & ” OS Version:  ” & oReg.GetValue(“CSDVersion”, “DEFAULT-VALUE”).ToString & vbCrLf

            info = info & ” System User:  ” & oReg.GetValue(“RegisteredOwner”, “DEFAULT-VALUE”).ToString & vbCrLf

 

            Dim Str As String = “Hardware\DESCRIPTION\System\CentralProcessor”

            Dim Stride As String = “Identifier”

            Dim strspeed As String = “~MHz”

            Dim strvendor As String = “VendorIdentifier”

            info = info & ” Processor Speed:  ” & Registry.LocalMachine.OpenSubKey(Str.ToString).GetValue(strspeed.ToString) & ” MHz” & vbCrLf

 

            info = info & ” Processor Vendor:  ” & Registry.LocalMachine.OpenSubKey(Str.ToString).GetValue(strvendor.ToString) & vbCrLf

            info = info & ” Processor Identifier:  ” & Registry.LocalMachine.OpenSubKey(Str.ToString).GetValue(Stride.ToString) & vbCrLf

            oReg.Close()

            Me.Label1.Text = info

        Catch ex As Exception

        End Try

 

Below is a picture after runing the application

sys info


READING EXCEL FILES IN JAVA APPLICATIONS

August 22, 2009

 Have you wondered about how to read excel files(.xls,xlsx), in Java Applications without using any API, then here is your stop. With this you can read excel 2003 and also 2007.We will be going through simple steps in reading the content of excel files and populating it into a Jtable. We will be working in the Microsoft Windows environment.

First, you have to create a datasource pointing to where your excel file is located. To do this, Go to Control panel ——— >   Administrative Tools ———- > Data Sources (ODBC). Below is an interface you are likely to see.

datasource face

Select the “User DSN” tab and click on the add button and select the driver “Microsoft Excel Driver (.xls,xlsx)” . You will be presented with the interface below, enter the name of the data source (Note, this is the name you will reference from you Java Application) and click on the “Select Workbook” button to select the excel file you want to read. You are now done with setting up the datasource.

choose driverselect workbook

Let’s now go to our Jave IDE (Netbeans) and do some small coding.  We will be using the JDBC-ODBC driver for reading our data. You don’t need to add the driver to your application as Windows OS comes with the Driver already installed.

We are creating a simple application where the user enters the datasource name and the sheet name, then on click of a button the data if populated into a JTable

 

We do this by creating a method

private void GetData(String excelDSN, String sheetname) {

        Connection connection = null;

        Statement st;

        ResultSet rsltSet;

        ResultSetMetaData rsltSetMetaData;

        String excelURL = “jdbc:odbc:” + excelDSN;

        String query = “Select * from [" + sheetname + "$]“;

 

        try {

            Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

            connection = DriverManager.getConnection(excelURL);

            //System.out.println(“ReadExcel connection = ” + connection);

            st = connection.createStatement();

            //System.out.println(“ReadExcel connection.createStatement() = ” + st);

            rsltSet = st.executeQuery(query);

            //System.out.println(“ReadExcel rsltSet = ” + rsltSet);

            rsltSetMetaData = rsltSet.getMetaData();

            

          //creating a datamodel for our JTable

            DefaultTableModel aModel = new DefaultTableModel() {

                @Override

                //setting the JTable uneditalble

                public boolean isCellEditable(int row, int column) {

                    return false;

                }

            };

            //adding the excel column names to the JTable

            Object[] tableColumnNames = new Object[rsltSetMetaData.getColumnCount()];

            for (int i = 1; i <= rsltSetMetaData.getColumnCount(); i++) {

                tableColumnNames[i-1] = rsltSetMetaData.getColumnName(i);

            }

            aModel.setColumnIdentifiers(tableColumnNames);

            //adding the rows to the JTable

            Object[] objects = new Object[rsltSetMetaData.getColumnCount()];

            while (rsltSet.next()) {

                for (int i = 1; i <= rsltSetMetaData.getColumnCount(); i++) {

                    objects[i-1] = rsltSet.getObject(i);

                }

                aModel.addRow(objects);

            }

            // setting the table model of the jtable

            this.jTable1.setModel(aModel);

        } catch (Exception ex) {

            JOptionPane.showMessageDialog(null, ex.toString()  );

        }

    }

Note , In reading records from excel, the index starts from one not zero(0). Once you starting getting this exception “[Microsoft][ODBC Driver Manager] Invalid descriptor index.” Get the index , its 1 not zero

Sample interface of the Application

the app