By admin on Thursday, 24 of January , 2008 at 2:19 pm
This snippet is from a servlet which acts as a generic form posting utility used throughout some of my sites. Irrelevant of the dressing of the JSP, it can be presenting the user a form for any number of reasons, but in each case when submitted the form contents will be emailed to my site admins. The initial problem I encountered whilst writing was that when you iterate the submitted request parameters, the order they come out will be at random. So you can either parse the request query itself OR give your form fields names which when alphabetically sorted will make sense. The latter is the quickest method.. Anyway here is the servlet, It uses collections to first construct a List, which you can then use Collections to sort, and finally use Collections again to create a new Enumeration of the sorted list. Enough babble heres the code :
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
StringBuffer sb = new StringBuffer();
sb.append("The following information was posted via the website;\n\n");
// Sort the list
List paramList = Collections.list(request.getParameterNames());
Collections.sort(paramList);
Enumeration sortedList = Collections.enumeration(paramList);
// iterate the list and append to a StringBuffer
for (Enumeration e = sortedList; e.hasMoreElements();) {
String paramName = (String) e.nextElement();
String[] values = request.getParameterValues(paramName);
sb.append(paramName + " = " + values[0] + "\n");
sb.append("\n");
}
// Email admin the sorted form contents
Utils.Send_SMTP("mailer@dbws.net", Utils.adminEmails, "Website Form Submission", sb.toString());
request.getRequestDispatcher("thankyou.jsp").forward(request, response);
}
Share and Enjoy:
These icons link to social bookmarking sites where readers can share and discover new web pages.
Category: Software Development
By admin on Friday, 7 of December , 2007 at 10:30 am
The Compact framework gives you a button control, but with no image or picture option. It also gives you a PictureBox control which of course you can assign an onclick event to, but there is no border or any control over the appearance when it is clicked on. So this article describes how to create a custom usercontrol with additional appearance options that can be set at design time such as a Label, a Border and font specifics. I will also add code so the user can see an obvious ‘click’ taking place. I will post a link to the entire source code and test application at the end of this article.
I am using Visual Studio 2005, with Compact Framework 2 SDK. I will target the Pocket PC 2003 platform but this will run on Windows Mobile 5 and 6 with no change to code.
First of all we must setup the development environment.
Start by creating a new project (see figure1).

(figure 1)
You now have your blank canvas to begin creating your control but first we should change the name of the control to something more meaningful.
In the Solution explorer right click the UserControl1.cs and choose rename, I have renamed my control to PictureButtonControl.cs. You will be prompted whether you wish to rename all references to UserControl1, click Yes.
One particular feature I have liked about Visual Studio, from the early days is the ability to add multiple project types to a solution and the way the projects are aware of each other. Because of this we can add a new Device Application project which will allow us to test the control as we develop it.
So lets add the Test project now, again in Solution explorer right click the solution and click Add, then “New Project…”. In the dialog that appears choose Device Application and give it a meaningful name (see figure2).

(figure 2)
Your solution explorer should now show both the UserControl project and the Testing Project(see figure3).

(figure 3)
Now we can begin to add some functionality to our control.
Lets start by adding the most important component of this control which is the PictureBox. Reselect our user control and drag a PictureBox control over to the empty control in the designer. Alternatively double click the PictureBox control and it will also be added to our control.
I’m going to apply a slight amount of padding around the picturebox control by setting its location property to 3,3. I have set the size property to 80, 70. To apply equal padding on the right side of our control I have set the width of our control to 86. (figure 4).

(figure 4)
Next we need to provide a method of getting a picture into our control for whoever will be using our control in a design environment. To do this we create a public property within our control which when set will in turn set the property of the private PictureBox control.
Begin by bring up the code for our PictureButtonControl.cs class. Not much to see at the moment.
namespace PictureButton {
public partial class PictureButtonControl : UserControl
{
public PictureButtonControl()
{
InitializeComponent();
}
}
}
After the constructor enter the following code;
public Image ButtonImage{
get
{
return pictureBox1.Image;
}
set
{
pictureBox1.Image = value;
this.Refresh();
}
}
This code declares a new property ButtonImage which will appear in the properties inspector at design time and acts as a proxy between our control and the underlying PictureBox within our control.
We can test this functionality immediately by first building the solution and then moving to our test application, so first press F6 to build the solution and then double click Form1.cs in the solution explorer. You should see an empty PDA image waiting for us to design our test app.
More importantly if you scan the toolbox you should now see our new custom control(see figure 5);

(figure 5)
Double click our control in the toolbox to place an instance on the test application form(figure 6). The control should now appear in our test form and if you look at the properties window, you will see our custom property – ButtonImage.

(figure 6)
Select the ButtonImage property, and click the … button to select an image from your computer that you would like to use on the button, choose a small picture.
Once selected you should see the image you chose appear in the PictureBox of our control(figure 7).

(figure 7)
We should think about sizing issues here since at the moment our user control may and will be resized by users as they design their forms, so we should capture that resize event and resize our picture box accordingly. So switching back to our control design and selecting our control we can look at the events listed in the properties window and create a ‘resize’ event. This will automatically create the stub below for you.
private void PictureButtonControl_Resize(object sender, EventArgs e)
Edit the code so it reads as below, this will adjust the size of the picturebox keeping the 3 pixel padding to the size of the user control;
private void PictureButtonControl_Resize(object sender, EventArgs e){ pictureBox1.Width = this.Width - 6; pictureBox1.Height = this.Height -6;}
Lets quickly test the behavior. First remove the instance of the existing control we have on our test application form and rebuild the solution pressing F6. Recreate an instance of the control on the form and try resizing the control, you should see the picturebox resizing with our control.
We need to see how that works when we have an image, so using the properties window, select the ButtonImage and load an image into the control and retry the resizing.
Notice how the image itself does not resize even though our control is resizing correctly, this means we should also expose the SizeMode property of the PictureBox by creating a new custom property. Switching back to the PictureButtonControl class I will add a new property called SizeMode.
Add the following code to your user control class.
// SizeMode - Defines Picturebox image sizing strategy.
public System.Windows.Forms.PictureBoxSizeMode SizeMode
{
get
{
return pictureBox1.SizeMode;
}
set
{
pictureBox1.SizeMode = value;
this.Refresh();
}
}
This will give us a new property called SizeMode in our usercontrol which behaves exactly the same as if we are editing the SizeMode property of the PictureBox directly.
You can try testing this yourself, make sure you first remove the control from the test application form before rebuilding the solution.
I want to know think about having a label option, so that we can give the user the opportunity to include a label as well as set its various cosmetic properties such as font and colour. Begin by resizing the user control design so we have space at the bottom, the size in my example is now 86, 100. Next add a label to the control and position it at the space we created. I have set the anchor to Bottom, Left, Right, and set the TextAlign property to TopCenter.
I will add a set of properties using the same technique as before for Font, Forecolor, and Text.
We will also need to adjust our resizing event, so that it takes into account the label height when resizing the PictureBox.
The entire code for my user control class is now;
using System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing;using System.Data;using System.Text;using System.Windows.Forms;
namespace PictureButton{ public partial class PictureButtonControl : UserControl { public PictureButtonControl() { InitializeComponent(); } // PictureBox properties // ButtonImage - Specifys image to be displayed public Image ButtonImage { get { return pictureBox1.Image; } set { pictureBox1.Image = value; this.Refresh(); } } // SizeMode - Defines Picturebox image sizing strategy.
public System.Windows.Forms.PictureBoxSizeMode SizeMode { get { return pictureBox1.SizeMode; } set { pictureBox1.SizeMode = value; this.Refresh(); } }
// Label Properties // Text - Defines text to show on label public String LabelText { get { return label1.Text; } set { label1.Text = value; this.Refresh(); } }
// Font - Defines label font public Font LabelFont { get { return label1.Font; } set { label1.Font = value; this.Refresh(); } }
// ForeColor - Defines label forecolor public Color LabelForeColor { get { return label1.ForeColor; }
set { label1.ForeColor = value; this.Refresh(); } }
private void PictureButtonControl_Resize(object sender, EventArgs e) { pictureBox1.Width = this.Width - 6; pictureBox1.Height = this.Height - (label1.Height + 6); } }}
Now I have an image that resizes accordingly, and a customisable label it would be a good idea to give our control a test, so again remove the existing control from the test app form, rebuild the solution and add our control. Now you will be able to change the label as well as add an image and resize the control to best display the image.
Figure 8 shows the current control in our designer, and figure 9 shows the same control running within our test app on the emulator.

(figure

(figure 9)
The next stage is to add visual indication to show that the button has been clicked, a common approach is to supply an additional image that should be shown in place of our standard image when the button is clicked. Without going into image editing a quick way to produce an appropriate image is to create a grey scaled version of the original.
Again we will need to add a new property called ButtonImageClick along with a private variable to hold the reference to the image.
Create
private Image _ButtonImageClick;
private Image _ButtonImage; // Used for temp holder of main image
and
// MouseDown event for our control
private void PictureButtonControl_MouseDown(object sender, MouseEventArgs e)
{
if (_ButtonImageClick != null)
{
_ButtonImage = pictureBox1.Image;
pictureBox1.Image = _ButtonImageClick;
Refresh();
}
}
// MouseUp event for our control
private void PictureButtonControl_MouseUp(object sender, MouseEventArgs e)
{
if (_ButtonImage != null)
{
pictureBox1.Image = _ButtonImage;
Refresh();
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
this.OnMouseDown(e);
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
this.OnMouseUp(e);
}
private void pictureBox1_Click(object sender, EventArgs e) { this.OnClick(e); }
This will allow us to specify an image that should be display when the user clicks a button, however it does not perform and swapping of images. We have to also capture the mouse down events for the PictureBox and call the MouseDown/Up event of our control.
Test the control again now, loading both images and you should have a functional custom control that redraws accordingly when clicked.
By now you can see how easy it is to add custom properties to the control and alter the behaviour accordingly, from here it is really up to you how far you want to carry on customising the control.
Other options you can quickly add now are options like whether to change the border state when pressed, or change the background colour of the control, or the color of the label. You could also extract the mouseDown event code and place it in its own method that we can call from the Key Down event as well as the Mouse Down Event. A consideration might be to show an indication when the control has focus, and again when the control loses focus, this may be a border or a background colour change.
A future task is to draw the original image in grey at runtime on a click event, so the user who is designing with our control does not have to perform the additional step of creating a greyscale image themselves. I would also like to discover a better way of passing the events from the PictureBox up to our usercontrol, otherwise there will be a growing amount of code capturing all the events. This could really get messy if you had to create a usercnotrol that contains many controls, then you’d have to capture and pass up the chain lots of events. I’m sure there must be a way to state that I only want our control to register events and none of the controls within our control.
Well thats about the end of this article, I hope someone out there finds it useful.
Download Entire Source Code & Test Application Solution (75k)
Share and Enjoy:
These icons link to social bookmarking sites where readers can share and discover new web pages.
Category: Software Development
By admin on Wednesday, 23 of May , 2007 at 7:59 am
I have discovered an issue relevant to Premium edition upwards. One of my SB apps uses the Win API call FindWindow to check if an instance of the application is already running. The FindWindow call takes two parameters a 'class' and the window caption you are looking for.
If you're not sure of the class you can send a 0 in the class parameter (There is also a slight change in the REGISTER definition).
Anyway the problem I ran into was when I exited my application and ran it a second time, It would act as if there is an instance already running and not allow itself to run. Killing the NTVDM would make no difference.
So I wrote a little app to go through an enumeration of the available windows in the system and sure enough there was a window there with the same caption as my applications, Even though my app is no longer running and NTVDM was killed.
The thing I noted was the windows class name was "ThumbnailClass" - Which I'm pretty sure is to do with Vista's "Desktop Window Manager" fancy effects it uses for task switching. It shows you a thumbnail image of your application while you switch tasks. Now why this would still be present when my application is no longer running is beyond me, perhaps its a synchronisation problem between the Win16 layer windows enumeration and the Desktop Window Manager. However the problem is existant on the Business edition and I presume the Premium edition as the fancy Aero effects dont come with the Basic edition.
So the solution I used was to find the class of the Superbase application window and also use that in my call to FindWindow.
So if you're checking for a class name the REGISTER definition will be:
REGISTER "USER","FindWindow","HCC"
if you dont know the class name and will pass a 0 instead it will be:
REGISTER "USER","FindWindow","HJC"
And to get the handle of a window of a SB Application by its caption the call will be:
hwnd% = CALL ("FindWindow","SBV3DATACLASS",caption$)
Share and Enjoy:
These icons link to social bookmarking sites where readers can share and discover new web pages.
Category: Software Development
By admin on Friday, 18 of May , 2007 at 6:21 pm
Posting XML from Visual Basic 6 is pretty straightforward. One would think. But like many development tasks which you'd expect to take an hour or two, this one turned into a couple of days.
First of all, How are you going to get the XML across the wire ? To answer this the easiest method I discovered was to use the MSXML object, since I have already been using it to create my XML document.
But then which version is best ? There are 6 to choose from ! To answer that I would ask you if plan on distributing your application and dont mind also taking care to include the MSXML msi installer with your deployment. For my purposes I want to make the deployment as easy as possibly. You can pretty much rely on MSXML v3 being present on a target machine. If you dont mind deploying an MSXML msi, then go for version 6. So I went with version 3.
So far so good, I created my VB code to use MSXML3 to create the document and perform a HTTP post to my servlet which read it in without difficulty.
However the document being sent was 20k in length. That size might not be of significance to you but for me, this action maybe repeated up to 30 times, from many different machines so optimising bandwidth use was also a priority.
The immediate solution is to compress the data. Searching the web there are many compression components available for VB. However I dont want to pay for something and really just need to zip the data so I can unzip it from my servlet. I used the ZLIB library from http://www.zlib.net/. Very easy to use, simply reference zlib.dll from your project and you can either compress a string or a byte array which suits us perfectly.
Using ZLIB I took the original XML Documents xml source and first converted it to a byte array. Then using the compressData method from the ZLIB library, compressed the data. This took my 15k document down to 2k.
So now I've got the compressed data, I can just post this ? No. It must be encoded first. Without going into why data crossing across the internet must be converted to 7 bit ASCII for succesful transmission, just accept that it does.
What encoding method should we use ? I repeatedly was having problems at this stage. You can specify that a XML node is intended to contain encoded binary by setting its data type to binary.base64. I had problems here because even though I did this, I was trying to insert a string representation of the compressed data into the nodes content. This would raise an error from MSXML. You HAVE to insert a byte array.
These problems led me to trying various other base64 encoding solutions, each giving different results !
So my working solution was to create a New XML Document containing a single element (I called it Data). The data type definition for data is set to binary.base64. As soon as I insert my compressed byte array into the "Data" node, it is automatically encoded to base64 so it can be transmitted successfully.
But not quite. I was still having issues.. When my servlet decodes, then decompress the data… Its all in unicode ! So I was unable to recreate an XML document on the servlet side.
It turned out the routine I used to convert the XML data as a String to a Byte array is creating unicode bytes.. Luckily I found an alternative routine which gives the option to use ASCII/Unicode.
Once that was sorted everything works great.. & Also across HTTPS. So my XML transmission is fast and secure.
Source code examples on request.
Share and Enjoy:
These icons link to social bookmarking sites where readers can share and discover new web pages.
Category: Software Development
By admin on Wednesday, 28 of February , 2007 at 6:55 pm
A task arose recently from one my clients requesting me to help process some binary files they had. They needed me to create a new file based on their input file with where all occurrences of a specific byte get replaced with a different specific byte. No problem I thought, but deciding which method to use to perform the reading and replacing of the values proved to be not immediately obvious.
There are a several approaches to reading and writing files, as well as several approaches to the replacing of values, in fact Java almost always offers a multitude of solutions to a problem.
So i decided to embark upon a little experiment to see what I could find to be the most efficient method.
Firstly I decided to create my own test data. To do so I just simply created a file containing many random bytes. I chose a random number between 0 and 32 as that most closely matched my original client requirement. CreateTest.java will create a 10mb file.
I wrote 4 little tests during the experiment, trying String replacement, byte comparison and replacement and buffered readers/writers. The result surprised me.
Method1.
My first method I decided to read in the data into a 4k buffer using a FileInputStream. I then create a new String object based upon the bytes read and replace the old value with the new value using String.replace(). Then the bytes from the String are written to a FileOutputStream.
Method 2
The second method I simply wondered if I could save any processing time by doing all the functions of Method1 for comparison and replacing on as little code lines as possible, as I expected this did not make any real difference.
Method 3
For method 3 I used the same method of reading the file by reading into a buffer using FileInputStream but rather than use the String replace function, I first compare the bytes and then write either the old or the new value into a second buffer. The result of this change was encouraging, the time taken to process the file was about 20-40% the time it took using the String object.
Method 4
Feeling encouraged by the results in method 3, I thought now if I use the Buffered Input & Output Stream objects java gives us, then I was sure to reap extra benefits, But the time taken rose dramatically.
Timing Results.
To come up with these results, I ran the classes from the command prompt 10 times each and recorded the average time taken.
Method1 : 500 ms
Method2 : 700 ms
Method3 : 150 ms
Method4 : 2800 ms
I wondered if I could tweak the buffer size in Method 3 to see what difference that makes when processing the files, To be honest I don’t know why I picked 4kb in the first place, it just happens to be habit when defining buffer sizes.
I tried 1k, 16k, 32k, 100k, and 512k.
With a 1k buffer the average time was 280 ms.
A 16k buffer gave me an average of 90 ms.
A 32k buffer gave me an average of 78 ms.
A 100k buffer averages out at 125 ms.
And the 512k buffer was back to roughly 200ms.
So using a 32k buffer gave me the best results.
Conclusion.
I was a little surprised that the time taken rose so dramatically when using the buffered reader and writer object. I must admit my understanding of the buffering objects is not at an expert level but I did expect to see improvement, else why use them if controlling the buffer myself proves to be so much more efficient.
Below you will find all the code used in these tests:
/*
* CreateTest.java
*
* Created on 04 February 2007, 11:19
*
* Purpose: To create a binary test file used in file processing tests.
*/
import java.io.FileOutputStream;
import java.util.Random;
/**
*
* @author DAVE
*/
public class CreateTest {
static final long fileSize = 10 * 1024 * 1024; // Lets make it 10mb
static final String outFile = "testfile.dat";
private static Random rn = new Random();
/** Creates a new instance of CreateTest */
public CreateTest() {
}
public static void main(String[] args) throws Exception{
// Open file for output
FileOutputStream out = new FileOutputStream(outFile);
for (int i = 0; i < fileSize; i++) {
// Get Random int between 0 & 32
int idx = rand(0,32);
out.write(idx);
}
out.close();
System.out.println("testfile.dat created.");
}
// get Random number
private static int rand(int lo, int hi) {
int n = hi - lo + 1;
int i = rn.nextInt() % n;
if (i < 0)
i = -i;
return lo + i;
}
}
/*
* Method1.java
*
* Created on 02 February 2007, 17:49
*
* Process binary file, byte by byte performing a replace
* using Strings & replace() function.
*
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
public class Method1 {
public Method1() {
}
public static void main(String[] args) throws Exception{
Date startTime = new Date();
Date endTime;
String inFile = "testfile.dat";
String outFile = "outputfile.dat";
char oldValue = 0×00;
char newValue = 0xFF;
final int bufferSize = 4 * 1024; // 4kb buffer
byte[] buffer = new byte[bufferSize];
FileInputStream in = new FileInputStream(inFile);
FileOutputStream out = new FileOutputStream(outFile);
String s = null;
int read = in.read(buffer);
while (read >= 0) {
if (read > 0) {
s = new String(buffer);
if (s.length() != read) {
s = s.substring(0,read);
}
s = s.replace(oldValue,newValue);
out.write(s.getBytes());
}
read = in.read(buffer);
}
out.close();
in.close();
endTime = new Date();
System.out.println(" Method 1 - time taken (ms) : "+(endTime.getTime() - startTime.getTime()));
}
}
/*
* Method2.java
*
* Created on 02 February 2007, 17:49
*
* Process binary file, byte by byte performing a replace
* using Strings & replace() function.
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
public class Method2 {
public Method2() {
}
public static void main(String[] args) throws Exception{
Date startTime = new Date();
Date endTime;
String inFile = "testfile.dat";
String outFile = "outputfile.dat";
char oldValue = 0×00;
char newValue = 0xFF;
final int bufferSize = 4 * 1024; // 4kb buffer
byte[] buffer = new byte[bufferSize];
FileInputStream in = new FileInputStream(inFile);
FileOutputStream out = new FileOutputStream(outFile);
int read = in.read(buffer);
while (read >= 0) {
if (read > 0) {
out.write(new String(buffer,0,read).replace(oldValue,newValue).getBytes());
}
read = in.read(buffer);
}
out.close();
in.close();
endTime = new Date();
System.out.println(" Method 2 - time taken (ms) : "+(endTime.getTime() - startTime.getTime()));
}
}
/*
* Method3.java
*
* Created on 02 February 2007, 17:49
*
* Process binary file, byte by byte performing a replace
* using byte comparison only
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;
public class Method3 {
public Method3() {
}
public static void main(String[] args) throws Exception{
Date startTime = new Date();
Date endTime;
String inFile = "testfile.dat";
String outFile = "outputfile.dat";
byte oldValue = (byte)0×00;
byte newValue = (byte)0xFF;
final int bufferSize = 32 * 1024; // 32kb buffer
byte[] buffer = new byte[bufferSize];
byte[] cBuffer = new byte[bufferSize];
FileInputStream in = new FileInputStream(inFile);
FileOutputStream out = new FileOutputStream(outFile);
int read = in.read(buffer);
while (read >= 0) {
if (read > 0) {
for (int i = 0; i < read; i++) {
if (buffer[i] == oldValue)
cBuffer[i] = newValue;
else
cBuffer[i] = buffer[i];
}
out.write(cBuffer,0,read);
}
read = in.read(buffer);
}
out.close();
in.close();
endTime = new Date();
System.out.println(" Method 3 - time taken (ms) : "+(endTime.getTime() - startTime.getTime()));
}
}
/*
* Method4.java
*
* Created on 02 February 2007, 17:49
*
* Process binary file, byte by byte performing a replace
* using buffered streams
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
public class Method4 {
public Method4() {
}
public static void main(String[] args) throws Exception{
Date startTime = new Date();
Date endTime;
String inFile = "testfile.dat";
String outFile = "outputfile.dat";
byte oldValue = (byte)0×00;
byte newValue = (byte)0xFF;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
bis = new BufferedInputStream(new FileInputStream(inFile));
bos = new BufferedOutputStream(new FileOutputStream(outFile));
int theByte;
while ((theByte = bis.read()) != -1) {
if (theByte != oldValue)
bos.write(theByte);
else
bos.write(newValue);
}
bos.close();
bis.close();
endTime = new Date();
System.out.println(" Method 4 - time taken (ms) : "+(endTime.getTime() - startTime.getTime()));
}
}
Share and Enjoy:
These icons link to social bookmarking sites where readers can share and discover new web pages.
Category: Software Development