<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>DBWS.NET &#187; Software Development</title>
	<atom:link href="http://www.dbws.net/blog/category/software-development/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dbws.net/blog</link>
	<description>Software development mutterings and maybe a little something about myself.</description>
	<lastBuildDate>Wed, 09 Nov 2011 16:56:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Launch an intent to start google maps in Navigation mode</title>
		<link>http://www.dbws.net/blog/2010/04/28/launch-an-intent-to-start-google-maps-in-navigation-mode/</link>
		<comments>http://www.dbws.net/blog/2010/04/28/launch-an-intent-to-start-google-maps-in-navigation-mode/#comments</comments>
		<pubDate>Wed, 28 Apr 2010 08:42:41 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[intent]]></category>
		<category><![CDATA[maps]]></category>
		<category><![CDATA[navigation]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/2010/04/28/launch-an-intent-to-start-google-maps-in-navigation-mode/</guid>
		<description><![CDATA[Android code to launch google maps in Navigation Mode!]]></description>
			<content:encoded><![CDATA[<p>Android code to launch google maps in Navigation Mode!</p>
<pre class="brush: java; title: ; notranslate">Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse(&quot;google.navigation:q=Hemsworth+Pontefract&quot;));
startActivity(i);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2010/04/28/launch-an-intent-to-start-google-maps-in-navigation-mode/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails, jQuery and the jQuery Grid &#8211; Tutorial One</title>
		<link>http://www.dbws.net/blog/2010/03/21/grails-and-jquery-grid-tutorial/</link>
		<comments>http://www.dbws.net/blog/2010/03/21/grails-and-jquery-grid-tutorial/#comments</comments>
		<pubDate>Sun, 21 Mar 2010 16:05:17 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Grails Tutorials]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[GRAILS]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jqgrid]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/?p=39</guid>
		<description><![CDATA[I&#8217;ve been intending for quite some time to write a series of articles on my experiences so far with Grails based web applications. So I&#8217;m tackling this now whilst my experiences are still relatively fresh before my focus takes another direction. I don&#8217;t want to go into the why&#8217;s of using grails when there are [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been intending for quite some time to write a series of articles on my experiences so far with Grails based web applications. So I&#8217;m tackling this now whilst my experiences are still relatively fresh before my focus takes another direction.</p>
<p>I don&#8217;t want to go into the why&#8217;s of using grails when there are already many other frameworks out there but for me, I love Java for its power, vast number of libraries and community support available. I also love Ruby On Rails, for its convention over configuration benefits so when I discovered Grails is a kind of merge of the two, it quickly gained my interest. There are many cool features to Grails but to pinpoint a couple, not having to go through all the initial setting up of Spring, Hibernate, JPA etc is a real time saver, and how it allows you to use it&#8217;s own Groovy code alongside pure Java is something in my opinion both very clever and incredible beneficial to us web developers.</p>
<p>My target for these tutorials are not just for beginners to Grails but for anyone looking for quick how-to instructions to use Grails with various Ajax features such as displaying data in a jQuery grid, ajax filtering of data.</p>
<p>I do make the assumption however that you already know the basics of a grails based application and can already create, modify and deploy projects. I also don&#8217;t want to insist on any particular IDE for working on these tutorials, although I will be using IntelliJ&#8217;s IDEA IDE, Netbeans also has great Grails support but at the time of writing does not offer gsp tag completion. I cannot offer any other comment on the others as I am not familiar with Grails support in the other main contenders.</p>
<p>I also cannot recommend enough the combination of using Firefox as your browser with the Firebug plugin installed so you can keep an eye of your AJAX calls from your page to server. Firebug is a great tool that allows you to easily see what you are sending and what you are receiving.</p>
<p>Anyway enough introduction, let&#8217;s move onto the first tutorial of my series.</p>
<p>Grails, JQuery and the Jquery Grid.</p>
<p>In this tutorial I aim to show you how to use the jQuery Grid to present data to your users.</p>
<p>I am using Grails version 1.2 alongside MySQL database.</p>
<p>I will setup a mock up of a customer database for this example, so first you will need to create a new Grails project and setup your datasource details so you are all setup ready to go.</p>
<p>The first step after you&#8217;ve created your project and defined your datasource is to create a new Grails Domain class called Customer.   I&#8217;ve kept it simple, but with enough fields for us to create and display several columns in a grid.</p>
<pre class="brush: groovy; title: ; notranslate">class Customer {
  static constraints = {
    firstName(blank:false,maxSize:50)
    lastName(blank:false,maxSize:50)
    age(nullable:true)
    emailAddress(nullable:true)
  }

  String firstName
  String lastName
  Integer age
  String emailAddress
}</pre>
<p>Once your class is defined, you should go ahead and generate the customer controller and corresponding views.</p>
<p>Now would be a good time to add some test data so we have something we can use to manipulate our views. A handy shortcut to create test data here is to edit the bootstrap groovy file so we can create some data at the time our application is launched. This is a technique I often use to preload testdata.</p>
<pre class="brush: groovy; title: ; notranslate">class BootStrap {

def init = { servletContext -&amp;gt;
  // if we have an empty customer database,
  // create some test data
  if (Customer.count() == 0) {
    new Customer(
      firstName:'John', lastName:'Smith',
      age:27,
      emailAddress:'john@somewhere.com'
    ).save()

    new Customer(
      firstName:'Frank', lastName:'Malone',
      age:37,
      emailAddress:'frank@somewhere.com'
    ).save()

    new Customer(
      firstName:'Dave', lastName:'Brown',
      age:34,
      emailAddress:'dave@somewhere.com'
    ).save()

    new Customer(
      firstName:'Barney', lastName:'Rubble',
      age:44,
      emailAddress:'barney@somewhere.com'
    ).save()
  }
}

def destroy = { }
}
</pre>
<p>I will also change the urlmappings so when we launch the application our default page is the customer index view :</p>
<pre class="brush: groovy; title: ; notranslate">class UrlMappings {
  static mappings = {
    &quot;/$controller/$action?/$id?&quot;{
      constraints {
      // apply constraints here
    }
  }
  &quot;/&quot;(controller:&quot;customer&quot;,action:&quot;index&quot;)
  &quot;500&quot;(view:'/error')
  }
}</pre>
<p>So try running the application now and you should see the default presented list on the customer page. So far so good.</p>
<p>Before we create the necessary adjustments to use a jQuery grid, you will first need to download the required javascript librarys as well css styles for your grid from the following links:</p>
<p>jQuery <a href="http://docs.jquery.com/Downloading_jQuery#Current_Release">latest release</a></p>
<p>jQuery Grid <a href="http://www.trirand.com/blog/?page_id=6">latest release</a> &#8211; contains the necessary javascript and css (ui.grid.css). Copy the ui.grid.css to the web-app/css folder.</p>
<p>jQuery UI css themes : <a href="http://jqueryui.com/download">theme download</a> &#8211; this is a great site that allows you to visual different UI themes for jquery widgets/plugins before downloading the necessary css/images.</p>
<p>I download the &#8216;min&#8217; versions of the javascript librarys to cut down download time for the user. jquery.jqGrid.min.js and jquery-1.3.2.min.js both go into the web-app/js folder.<br />
You theme will be downloaded as a zip file, you will need to copy the jquery-ui-1.7.2.custom.min.js script into your applications js folder and the contents of the css folder go into your web-app/css folder. For the purpose of this tutorial I downloaded the ui-lightness theme.</p>
<p>So now I want to switch from the default list view, to a jQuery Grid to present our customer data.</p>
<p>Edit your Customer/list.gsp, and perform the following.</p>
<p>1. Include our new javascript librarys by adding the includes into the  head section. Our css style sheet should also be reference by also adding to the head section. Your head section should then contain the following:</p>
<pre class="brush: groovy; title: ; notranslate">
&lt;link rel=&quot;stylesheet&quot; href=&quot;${resource(dir:'css',file:'main.css')}&quot; /&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;${resource(dir:'css',file:'ui.jqgrid.css')}&quot; /&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;${resource(dir:'css/ui-lightness',file:'jquery-ui-1.7.2.custom.css')}&quot; /&gt;
&lt;g:javascript library=&quot;jquery-1.3.2.min&quot;/&gt;
&lt;g:javascript library=&quot;jquery-ui-1.7.2.custom.min&quot;/&gt;
&lt;g:javascript library=&quot;grid.locale-en&quot;/&gt;
&lt;g:javascript library=&quot;jquery.jqGrid.min&quot;/&gt;
</pre>
<p>2. Remove the tag and contents of</p>
<div class="list">tag as well as the paginator tag that immediately follows it.3. I usually create page fragments for my jquery specific grids but for this example we will just place the code directly into the main list page.</p>
<p>You have to create a table element to hold our grid, as well as div element to go at the end of the table to display record count, paginator.</p>
<p>Insert the following jquery Grid definition. This defines a very basic grid which will be rendered when the page loads in the browser. Notice the url parameter, url:&#8217;jq_customer_list&#8217;. This is the url from which the grid will load its data. I have also specified the format of the data will be JSON. These parameters lead us to our next stage, we need to create the necessary function in our Customer controller that will return the data.</p>
<pre class="brush: groovy; title: ; notranslate">
&lt;!-- table tag will hold our grid --&gt;
&lt;table id=&quot;customer_list&quot; class=&quot;scroll jqTable&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot;&gt;&lt;/table&gt;
&lt;!-- pager will hold our paginator --&gt;
&lt;div id=&quot;customer_list_pager&quot; class=&quot;scroll&quot; style=&quot;text-align:center;&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
/* when the page has finished loading.. execute the follow */
$(document).ready(function () {
  jQuery(&quot;#customer_list&quot;).jqGrid({
  url:'jq_customer_list',
  datatype: &quot;json&quot;,
  colNames:['First Name','Last Name','Age','Email Address','id'],
  colModel:[
    {name:'firstName'},
    {name:'lastName'},
    {name:'age'},
    {name:'email'},
    {name:'id'}
  ],
  pager: jQuery('#customer_list_pager'),
  viewrecords: true,
  gridview: true
  });
});
// ]]&gt;&lt;/script&gt;</pre>
<p>4. Create the jq_customer_list action in the Customer controller to respond to the grids request for JSON data.</p>
<p>As we are returning JSON type data, you must add an import to the top of the controller : import grails.converters.JSON</p>
<p>Note that the order of the fields must match the order in which we defined the order in the colModel and colNames in the grid definition. The minimal code to return the data is as follows:</p>
<pre class="brush: groovy; title: ; notranslate">
def jq_customer_list = {
  def customers = Customer.list()
  def jsonCells = customers.collect {
    [cell: [it.firstName,
    it.lastName,
    it.age,
    it.emailAddress], id: it.id]
  }
  def jsonData= [rows: jsonCells]
  render jsonData as JSON
}</pre>
<p>5. Try and run your application, if all succeeded you should be presented with your customer data in a nice looking grid.</p>
<div id="attachment_40" class="wp-caption aligncenter" style="width: 310px"><a rel="attachment wp-att-40" href="http://www.dbws.net/blog/2010/03/21/grails-and-jquery-grid-tutorial/customer_list/"><img class="size-medium wp-image-40" title="customer list image" src="http://www.dbws.net/blog/wp-content/uploads/2010/03/customer_list-300x136.jpg" alt="customer list presented in a jquery grid" width="300" height="136" /></a><p class="wp-caption-text">Browser showing customer list presented in jquery grid</p></div>
<p>The entire project for this tutorial can be downloaded <a href="http://www.dbws.net/blog/attach/Tutorial1.zip">here</a>.</p>
<p>In my next tutorial I will take what we have done so far, and implement ajax pagination and table sorting when the user clicks on a column header.</p>
<p>Interested in learning more grails?  Head over and join up at the <a title="Grails Forum - Grails Discussion and support group" href="http://www.grailsforum.co.uk" target="_blank">grails forum</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2010/03/21/grails-and-jquery-grid-tutorial/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Grails 2 DataAccessResourceFailureException Solved</title>
		<link>http://www.dbws.net/blog/2010/02/15/grails-2-dataaccessresourcefailureexception-solved/</link>
		<comments>http://www.dbws.net/blog/2010/02/15/grails-2-dataaccessresourcefailureexception-solved/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 14:15:20 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[DBCP]]></category>
		<category><![CDATA[GRAILS]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Tomcat]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/?p=29</guid>
		<description><![CDATA[For those using MYSQL and have either updated to grails version 2 or starting with grails 2 and have run into this exception then this solution works perfectly well for me. The problem is releated to Grails running out of connections to MySQL over time, &#38; not freeing stale connections.Â  I believe it happens when [...]]]></description>
			<content:encoded><![CDATA[<p>For those using MYSQL and have either updated to grails version 2 or starting with grails 2 and have run into this exception then this solution works perfectly well for me.</p>
<p>The problem is releated to Grails running out of connections to MySQL over time, &amp; not freeing stale connections.Â  I believe it happens when there hasn&#8217;t been activity for over 8 hours, which in my case happened everyday due to the overnight period.</p>
<p>So what we should be doing is managing our own database connection pool.Â Â  I use Tomcat 6 on my production servers so the following solution is specifically for tomcat 6.</p>
<p>What we need to do is first change our application configuration so it sets up a database connection pool through tomcat.Â  And secondly we need to tweak the configuration so that we validate the connection is present periodically and removed stale connections.</p>
<p>The first thing then is to define the connection pool in &lt;your application dir&gt;/web-app/META-INF/context.xml</p>
<p>A typical context.xml would be :</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Context path=&quot;/MyApplication&quot;&gt;
&lt;Resource
 auth=&quot;Container&quot;
 driverClassName=&quot;com.mysql.jdbc.Driver&quot;
 maxActive=&quot;20&quot;
 maxIdle=&quot;10&quot;
 maxWait=&quot;-1&quot;
 removeAbandoned=&quot;true&quot;
 name=&quot;jdbc/myAppsPool&quot;
 type=&quot;javax.sql.DataSource&quot;
 url=&quot;jdbc:mysql://localhost:3306/Database_Name&quot;
 username=&quot;user&quot;
 password=&quot;password&quot;
 validationQuery=&quot;SELECT '1'&quot;
 removeAbandonedTimeout=&quot;60&quot;
 logAbandoned=&quot;true&quot;/&gt;
&lt;/Context&gt;</pre>
<p>This alone will create the necessary database connection pool when you application is deployed.</p>
<p>All thats left to do now is to change your datasource configuration to refer to the connection pool so in your DataSource.groovy file, locate the production section and alter it to refer to the new pool, e.g :</p>
<pre class="brush: groovy; title: ; notranslate">production {
  dataSource {
    pooled = false
    dbCreate = &quot;update&quot;
    jndiName = &quot;java:comp/env/jdbc/myAppsPool&quot;
  }
}</pre>
<p>That should solve any of those DataAccessResourceFailureExceptions from now on.[</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2010/02/15/grails-2-dataaccessresourcefailureexception-solved/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RegEx validation of Latitude and Longitude</title>
		<link>http://www.dbws.net/blog/2009/10/23/regex-validation-of-latitude-and-longitude/</link>
		<comments>http://www.dbws.net/blog/2009/10/23/regex-validation-of-latitude-and-longitude/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 09:31:58 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[regex latitude longitude]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/2009/10/23/regex-validation-of-latitude-and-longitude/</guid>
		<description><![CDATA[Below are regex patterns to match against valid latitude and longitude. Both formats are based on Decimal coordinates. Latitude range is from -90 to +90 Longitude from -180 to +180 For Latitude the regex pattern is (-?[0-8]?[0-9](\.\d*)?)&#124;-?90(\.[0]*)? For Longitude use (-?([1]?[0-7][1-9]&#124;[1-9]?[0-9])?(\.\d*)?)&#124;-?180(\.[0]*)? This will also restrict the decimal values being &#62; 0 for both +- 90&#8242; [...]]]></description>
			<content:encoded><![CDATA[<p>Below are regex patterns to match against valid latitude and longitude.</p>
<p>Both formats are based on Decimal coordinates.</p>
<p>Latitude range is from -90 to +90</p>
<p>Longitude from -180 to +180</p>
<p>For Latitude the regex pattern is</p>
<p><code>(-?[0-8]?[0-9](\.\d*)?)|-?90(\.[0]*)?</code></p>
<p>For Longitude use</p>
<p><code>(-?([1]?[0-7][1-9]|[1-9]?[0-9])?(\.\d*)?)|-?180(\.[0]*)?</code></p>
<p>This will also restrict the decimal values being &gt; 0 for both +- 90&#8242; and +- 180</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2009/10/23/regex-validation-of-latitude-and-longitude/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Docbook -&gt; WebHelp</title>
		<link>http://www.dbws.net/blog/2008/07/09/docbook-webhelp/</link>
		<comments>http://www.dbws.net/blog/2008/07/09/docbook-webhelp/#comments</comments>
		<pubDate>Wed, 09 Jul 2008 10:15:49 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/2008/07/09/docbook-webhelp/</guid>
		<description><![CDATA[Steps to get from docbook to fully interactive webhelp.. 1. Generate HTMLHELP via Oxygen. 2. (can compile to CHM) or carryon and import HTMLHelp project (hhp) file into Robohelp.]]></description>
			<content:encoded><![CDATA[<p>Steps to get from docbook to fully interactive webhelp..</p>
<p>1. Generate HTMLHELP via Oxygen.</p>
<p>2. (can compile to CHM) or carryon and import HTMLHelp project (hhp) file into Robohelp.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2008/07/09/docbook-webhelp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sorting the request Parameters</title>
		<link>http://www.dbws.net/blog/2008/01/24/sorting-the-request-parameters/</link>
		<comments>http://www.dbws.net/blog/2008/01/24/sorting-the-request-parameters/#comments</comments>
		<pubDate>Thu, 24 Jan 2008 14:19:33 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[getParameterMap]]></category>
		<category><![CDATA[getParameters]]></category>
		<category><![CDATA[J2EE]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[request]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/2008/01/24/sorting-the-request-parameters/</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 :</p>
<pre>
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);
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2008/01/24/sorting-the-request-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a pocket pc iPhone style picture button for the .NET compact framework</title>
		<link>http://www.dbws.net/blog/2007/12/07/creating-a-pocket-pc-iphone-style-picture-button-for-the-net-compact-framework/</link>
		<comments>http://www.dbws.net/blog/2007/12/07/creating-a-pocket-pc-iphone-style-picture-button-for-the-net-compact-framework/#comments</comments>
		<pubDate>Fri, 07 Dec 2007 10:30:37 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[compact framework]]></category>
		<category><![CDATA[picture button]]></category>
		<category><![CDATA[ppc]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/?p=14</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>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.</p>
<p>First of all we must setup the development environment.</p>
<p>Start by creating a new project (see figure1).</p>
<p><a href="/blog/images/NewUserControlProject.JPG" target="_blank" rel="lightbox[14]"><img src="/blog/images/NewUserControlProject.JPG" alt="new User control project" height="353" width="500" /></a><br />
<strong><em>(figure 1)</em></strong></p>
<p>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.<br />
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.</p>
<p>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.</p>
<p>So lets add the Test project now, again in Solution explorer right  click the solution and click Add, then â€œNew Project&#8230;â€. In the dialog  that appears choose Device Application and give it a meaningful name  (see figure2).</p>
<p><a href="/blog/images/NewDeviceApplication.JPG" target="_blank" rel="lightbox[14]"><img src="/blog/images/NewDeviceApplication.JPG" alt="New Device Application" height="316" width="500" /></a><br />
<em><strong>(figure 2)</strong></em></p>
<p>Your solution explorer should now show both the UserControl project and the Testing Project(see figure3).</p>
<p><img src="/blog/images/SolutionExplorerAfterAddingDAProject.JPG" alt="solution explorer" /><br />
<strong><em>(figure 3)</em></strong></p>
<p>Now we can begin to add some functionality to our control.</p>
<p>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.</p>
<p>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).</p>
<p><img src="/blog/images/ControlStage1.JPG" alt="usercontrol with picturebox" /><br />
<em><strong>(figure 4)</strong></em></p>
<p>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.</p>
<p>Begin by bring up the code for our PictureButtonControl.cs class.  Not much to see at the moment.</p>
<pre>namespace PictureButton {
	public partial class PictureButtonControl : UserControl
	{
		public PictureButtonControl()
		{
			InitializeComponent();
		}
	}
}</pre>
<p>After the constructor enter the following code;</p>
<pre>public Image ButtonImage{
	get
	{
		return pictureBox1.Image;
	}

	set
	{
		pictureBox1.Image = value;
		this.Refresh();
	}
}</pre>
<p>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.</p>
<p>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.</p>
<p>More importantly if you scan the toolbox you should now see our new custom control(see figure 5);</p>
<p><img src="/blog/images/ControlInToolbox.JPG" alt="image showing our custom control appearing in toolbox" /><br />
<em><strong>(figure 5)</strong></em></p>
<p>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.</p>
<p><a href="http://www.dbws.net/blog/images/ControlOnForm1.JPG" target="_blank" rel="lightbox[14]"><br />
<img src="http://www.dbws.net/blog/images/ControlOnForm1.JPG" alt="Showing Contontrol on form" height="343" width="500" /><br />
<em><strong>(figure 6)</strong></em></a></p>
<p>Select the ButtonImage property, and click the &#8230; button to select  an image from your computer that you would like to use on the button,  choose a small picture.<br />
Once selected you should see the image you chose appear in the PictureBox of our control(figure 7).</p>
<p><img src="/blog/images/ImageLoadedOntoPicturebox.JPG" alt="Showing first image on control" /><br />
<strong><em>(figure 7)</em></strong></p>
<p>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.</p>
<pre>private void PictureButtonControl_Resize(object sender, EventArgs e)</pre>
<p>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;</p>
<pre>private void PictureButtonControl_Resize(object sender, EventArgs e){            	pictureBox1.Width = this.Width - 6;	pictureBox1.Height = this.Height -6;}</pre>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>Add the following code to your user control class.</p>
<pre>// SizeMode - Defines Picturebox image sizing strategy.

public System.Windows.Forms.PictureBoxSizeMode SizeMode
{
	get
	{
		return pictureBox1.SizeMode;
	}

	set
	{
		pictureBox1.SizeMode = value;
		this.Refresh();
	}
}</pre>
<p>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.</p>
<p>You can try testing this yourself, make sure you first remove the  control from the test application form before rebuilding the solution.</p>
<p>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.</p>
<p>I will add a set of properties using the same technique as before for Font, Forecolor, and Text.</p>
<p>We will also need to adjust our resizing event, so that it takes into account the label height when resizing the PictureBox.</p>
<p>The entire code for my user control class is now;</p>
<pre>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);        }    }}</pre>
<p>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.</p>
<p>Figure 8 shows the current control in our designer, and figure 9  shows the same control running within our test app on the emulator.</p>
<p><img src="http://www.dbws.net/blog/images/designmode%20with%20label.JPG" alt="Control in designer" /><em><strong><br />
(figure <img src='http://www.dbws.net/blog/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> </strong></em></p>
<p><em><strong><img src="http://www.dbws.net/blog/images/running%20in%20emulator%20with%20label.JPG" alt="control running in test app on emulator" /></strong></em><br />
<em><strong>(figure 9)</strong></em></p>
<p>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.</p>
<p>Again we will need to add a new property called ButtonImageClick  along with a private variable to hold the reference to the image.</p>
<p>Create</p>
<pre>private Image _ButtonImageClick;
private Image _ButtonImage; // Used for temp holder of main image</pre>
<p>and</p>
<pre>	// 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);	}</pre>
<p>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.</p>
<p>Test the control again now, loading both images and you should have a functional custom control that redraws accordingly when clicked.</p>
<p>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.</p>
<p>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.</p>
<p>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&#8217;d have to capture and pass up the chain lots of events. I&#8217;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.</p>
<p>Well thats about the end of this article, I hope someone out there finds it useful.</p>
<p><a href="http://www.dbws.net/blog/attach/entire_picture_button_solution.zip"><img src="http://www.dbws.net/blog/blog/images/download.jpeg" alt="Download source code for this article" align="absmiddle" border="0" height="48" hspace="5" width="48" />Download Entire Source Code &amp; Test Application Solution</a> (75k)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2007/12/07/creating-a-pocket-pc-iphone-style-picture-button-for-the-net-compact-framework/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Superbase &amp; Vista Premium/Bus/Ultimate</title>
		<link>http://www.dbws.net/blog/2007/05/23/superbase-vista-premiumbusultimate/</link>
		<comments>http://www.dbws.net/blog/2007/05/23/superbase-vista-premiumbusultimate/#comments</comments>
		<pubDate>Wed, 23 May 2007 07:59:02 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/?p=12</guid>
		<description><![CDATA[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.&#160; The FindWindow call takes two parameters a &#39;class&#39; and the window caption you are looking for. If you&#39;re not sure of the class [...]]]></description>
			<content:encoded><![CDATA[<p>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.&nbsp; The FindWindow call takes two  parameters a &#39;class&#39; and the window caption you are looking for. </p>
<p>If you&#39;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). </p>
<p>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.&nbsp; Killing the NTVDM would make no  difference. </p>
<p>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. </p>
<p>The thing I noted was the windows class name was &quot;ThumbnailClass&quot; &#8211;  Which I&#39;m pretty sure is to do with Vista&#39;s &quot;Desktop Window Manager&quot;  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.&nbsp; However the problem is  existant on the Business edition and I presume the Premium edition as  the fancy Aero effects dont come with&nbsp; the Basic edition. </p>
<p>So the solution I used was to find the class of the Superbase  application window and also use that in my call to FindWindow. </p>
<p>So if you&#39;re checking for a class name the REGISTER definition will be: </p>
<p>REGISTER &quot;USER&quot;,&quot;FindWindow&quot;,&quot;HCC&quot; </p>
<p>if you dont know the class name and will pass a 0 instead it will be: </p>
<p>REGISTER &quot;USER&quot;,&quot;FindWindow&quot;,&quot;HJC&quot; </p>
<p>And to get the handle of a window of a SB Application by its caption the  call will be: </p>
<p>hwnd% = CALL (&quot;FindWindow&quot;,&quot;SBV3DATACLASS&quot;,caption$) </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2007/05/23/superbase-vista-premiumbusultimate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Posting large xml documents from VB6 to a Java servlet.</title>
		<link>http://www.dbws.net/blog/2007/05/18/posting-large-xml-documents-from-vb6-to-a-java-servlet/</link>
		<comments>http://www.dbws.net/blog/2007/05/18/posting-large-xml-documents-from-vb6-to-a-java-servlet/#comments</comments>
		<pubDate>Fri, 18 May 2007 18:21:18 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/?p=10</guid>
		<description><![CDATA[Posting XML from Visual Basic 6 is pretty straightforward.&#160; One would think.&#160; But like many development tasks which you&#39;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 ?&#160; To answer this the easiest method [...]]]></description>
			<content:encoded><![CDATA[<p>Posting XML from Visual Basic 6 is pretty straightforward.&nbsp; One would think.&nbsp; But like many development tasks which you&#39;d expect to take an hour or two, this one turned into a couple of days.</p>
<p>First of all, How are you going to get the XML across the wire ?&nbsp; 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.</p>
<p>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.&nbsp; So I went with version 3.</p>
<p>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. </p>
<p>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.</p>
<p>The immediate solution is to compress the data.&nbsp; 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.&nbsp; I used the ZLIB library from http://www.zlib.net/.&nbsp; 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.&nbsp;&nbsp;</p>
<p>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.</p>
<p>So now I&#39;ve got the compressed data,&nbsp; I can just post this ? No.&nbsp; It must be encoded first.&nbsp; Without going into why data crossing across the internet must be converted to 7 bit ASCII for succesful transmission, just accept that it does.</p>
<p>What encoding method should we use ? &nbsp;&nbsp; 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.&nbsp; 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.&nbsp; This would raise an error from MSXML.&nbsp; You HAVE to insert a byte array.</p>
<p>These problems led me to trying various other base64 encoding solutions, each giving different results !</p>
<p>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.&nbsp; As soon as I insert my compressed byte array into the &quot;Data&quot; node, it is automatically encoded to base64 so it can be transmitted successfully.</p>
<p>&nbsp;But not quite. I was still having issues..&nbsp; When my servlet decodes, then decompress the data&#8230; Its all in unicode !&nbsp; So I was unable to recreate an XML document on the servlet side.</p>
<p>&nbsp;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.</p>
<p>&nbsp;Once that was sorted everything works great.. &nbsp; &amp; Also across HTTPS. So my XML transmission is fast and secure. </p>
<p>&nbsp;Source code examples on request.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2007/05/18/posting-large-xml-documents-from-vb6-to-a-java-servlet/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Binary file processing with Java</title>
		<link>http://www.dbws.net/blog/2007/02/28/binary-file-processing-with-java/</link>
		<comments>http://www.dbws.net/blog/2007/02/28/binary-file-processing-with-java/#comments</comments>
		<pubDate>Wed, 28 Feb 2007 18:55:18 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/?p=8</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>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.</p>
<p>So i decided to embark upon a little experiment to see what I could find to be the most efficient method.</p>
<p>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.</p>
<p>I wrote 4 little tests during the experiment,  trying String replacement, byte comparison and replacement and buffered readers/writers. The result surprised me.</p>
<p><strong>Method 1.</strong></p>
<p>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.</p>
<p><strong>Method 2</strong></p>
<p>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.</p>
<p><strong>Method 3</strong></p>
<p>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.</p>
<p><strong>Method 4</strong></p>
<p>Feeling encouraged by the results in method 3, I thought now if I use the Buffered Input &amp; Output Stream objects java gives us, then I was sure to reap extra benefits, But the time taken rose dramatically.</p>
<p>Timing Results.</p>
<p>To come up with these results, I ran the classes from the command prompt 10 times each and recorded the average time taken.</p>
<p>Method1 : 500 ms<br />
Method2 : 700 ms<br />
Method3 : 150 ms<br />
Method4 : 2800 ms</p>
<p>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.</p>
<p>I tried 1k, 16k, 32k, 100k, and 512k.</p>
<p>With a 1k buffer the average time was 280 ms.<br />
A 16k buffer gave me an average of 90 ms.<br />
A 32k buffer gave me an average of 78 ms.<br />
A 100k buffer averages out at 125 ms.<br />
And the 512k buffer was back to roughly 200ms.</p>
<p>So using a 32k buffer gave me the best results.</p>
<p>Conclusion.</p>
<p>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.</p>
<p>Below you will find all the code used in these tests:</p>
<div class="source">
<p>/*<br />
* CreateTest.java<br />
*<br />
* Created on 04 February 2007, 11:19<br />
*<br />
* Purpose: To create a binary test file used in file processing tests.<br />
*/</p>
<p>import java.io.FileOutputStream;<br />
import java.util.Random;</p>
<p>/**<br />
*<br />
* @author DAVE<br />
*/<br />
public class CreateTest {</p>
<p>static final long fileSize = 10 * 1024 * 1024; // Lets make it 10mb<br />
static final String outFile = &#8220;testfile.dat&#8221;;<br />
private static Random rn = new Random();</p>
<p>/** Creates a new instance of CreateTest */<br />
public CreateTest() {<br />
}</p>
<p>public static void main(String[] args) throws Exception{<br />
// Open file for output<br />
FileOutputStream out = new FileOutputStream(outFile);</p>
<p>for (int i = 0; i &lt; fileSize; i++) {<br />
// Get Random int between 0 &amp; 32<br />
int idx = rand(0,32);<br />
out.write(idx);<br />
}<br />
out.close();<br />
System.out.println(&#8220;testfile.dat created.&#8221;);<br />
}</p>
<p>// get Random number<br />
private static int rand(int lo, int hi) {<br />
int n = hi &#8211; lo + 1;<br />
int i = rn.nextInt() % n;<br />
if (i &lt; 0)<br />
i = -i;<br />
return lo + i;<br />
}<br />
}</p>
</div>
<div class="source">/*<br />
* Method1.java<br />
*<br />
* Created on 02 February 2007, 17:49<br />
*<br />
* Process binary file, byte by byte performing a replace<br />
* using Strings &amp; replace() function.<br />
*<br />
*/</p>
<p>import java.io.FileInputStream;<br />
import java.io.FileOutputStream;<br />
import java.util.Date;</p>
<p>public class Method1 {</p>
<p>public Method1() {<br />
}</p>
<p>public static void main(String[] args) throws Exception{<br />
Date startTime = new Date();<br />
Date endTime;</p>
<p>String inFile = &#8220;testfile.dat&#8221;;<br />
String outFile = &#8220;outputfile.dat&#8221;;</p>
<p>char oldValue = 0&#215;00;<br />
char newValue = 0xFF;<br />
final int bufferSize = 4 * 1024; // 4kb buffer<br />
byte[] buffer = new byte[bufferSize];</p>
<p>FileInputStream in = new FileInputStream(inFile);<br />
FileOutputStream out = new FileOutputStream(outFile);</p>
<p>String s = null;<br />
int read = in.read(buffer);<br />
while (read &gt;= 0) {<br />
if (read &gt; 0) {<br />
s = new String(buffer);<br />
if (s.length() != read) {<br />
s = s.substring(0,read);<br />
}<br />
s = s.replace(oldValue,newValue);<br />
out.write(s.getBytes());<br />
}<br />
read = in.read(buffer);<br />
}</p>
<p>out.close();<br />
in.close();<br />
endTime = new Date();</p>
<p>System.out.println(&#8221; Method 1  &#8211; time taken (ms) : &#8220;+(endTime.getTime() &#8211; startTime.getTime()));</p>
<p>}<br />
}</p>
</div>
<div class="source">/*<br />
* Method2.java<br />
*<br />
* Created on 02 February 2007, 17:49<br />
*<br />
* Process binary file, byte by byte performing a replace<br />
* using Strings &amp; replace() function.<br />
*/</p>
<p>import java.io.FileInputStream;<br />
import java.io.FileOutputStream;<br />
import java.util.Date;</p>
<p>public class Method2 {</p>
<p>public Method2() {<br />
}</p>
<p>public static void main(String[] args) throws Exception{<br />
Date startTime = new Date();<br />
Date endTime;</p>
<p>String inFile = &#8220;testfile.dat&#8221;;<br />
String outFile = &#8220;outputfile.dat&#8221;;</p>
<p>char oldValue = 0&#215;00;<br />
char newValue = 0xFF;<br />
final int bufferSize = 4 * 1024; // 4kb buffer<br />
byte[] buffer = new byte[bufferSize];</p>
<p>FileInputStream in = new FileInputStream(inFile);<br />
FileOutputStream out = new FileOutputStream(outFile);</p>
<p>int read = in.read(buffer);<br />
while (read &gt;= 0) {<br />
if (read &gt; 0) {<br />
out.write(new String(buffer,0,read).replace(oldValue,newValue).getBytes());<br />
}<br />
read = in.read(buffer);<br />
}</p>
<p>out.close();<br />
in.close();</p>
<p>endTime = new Date();<br />
System.out.println(&#8221; Method 2  &#8211; time taken (ms) : &#8220;+(endTime.getTime() &#8211; startTime.getTime()));</p>
<p>}<br />
}</p>
</div>
<div class="source">/*<br />
* Method3.java<br />
*<br />
* Created on 02 February 2007, 17:49<br />
*<br />
* Process binary file, byte by byte performing a replace<br />
* using byte comparison only<br />
*/</p>
<p>import java.io.FileInputStream;<br />
import java.io.FileOutputStream;<br />
import java.io.OutputStreamWriter;<br />
import java.util.Date;</p>
<p>public class Method3 {</p>
<p>public Method3() {<br />
}</p>
<p>public static void main(String[] args) throws Exception{<br />
Date startTime = new Date();<br />
Date endTime;</p>
<p>String inFile = &#8220;testfile.dat&#8221;;<br />
String outFile = &#8220;outputfile.dat&#8221;;</p>
<p>byte oldValue = (byte)0&#215;00;<br />
byte newValue = (byte)0xFF;</p>
<p>final int bufferSize = 32 * 1024; // 32kb buffer</p>
<p>byte[] buffer = new byte[bufferSize];<br />
byte[] cBuffer = new byte[bufferSize];</p>
<p>FileInputStream in = new FileInputStream(inFile);<br />
FileOutputStream out = new FileOutputStream(outFile);</p>
<p>int read = in.read(buffer);<br />
while (read &gt;= 0) {<br />
if (read &gt; 0) {<br />
for (int i = 0; i &lt; read; i++) {<br />
if (buffer[i] == oldValue)<br />
cBuffer[i] = newValue;<br />
else<br />
cBuffer[i] = buffer[i];<br />
}<br />
out.write(cBuffer,0,read);<br />
}<br />
read = in.read(buffer);<br />
}</p>
<p>out.close();<br />
in.close();<br />
endTime = new Date();<br />
System.out.println(&#8221; Method 3  &#8211; time taken (ms) : &#8220;+(endTime.getTime() &#8211; startTime.getTime()));<br />
}<br />
}</p>
</div>
<div class="source">/*<br />
* Method4.java<br />
*<br />
* Created on 02 February 2007, 17:49<br />
*<br />
* Process binary file, byte by byte performing a replace<br />
* using buffered streams<br />
*/</p>
<p>import java.io.BufferedInputStream;<br />
import java.io.BufferedOutputStream;<br />
import java.io.FileInputStream;<br />
import java.io.FileOutputStream;<br />
import java.util.Date;</p>
<p>public class Method4 {</p>
<p>public Method4() {<br />
}</p>
<p>public static void main(String[] args) throws Exception{<br />
Date startTime = new Date();<br />
Date endTime;</p>
<p>String inFile = &#8220;testfile.dat&#8221;;<br />
String outFile = &#8220;outputfile.dat&#8221;;</p>
<p>byte oldValue = (byte)0&#215;00;<br />
byte newValue = (byte)0xFF;</p>
<p>BufferedInputStream bis = null;<br />
BufferedOutputStream bos = null;</p>
<p>bis = new BufferedInputStream(new FileInputStream(inFile));<br />
bos = new BufferedOutputStream(new FileOutputStream(outFile));</p>
<p>int theByte;<br />
while ((theByte = bis.read()) != -1) {<br />
if (theByte != oldValue)<br />
bos.write(theByte);<br />
else<br />
bos.write(newValue);<br />
}</p>
<p>bos.close();<br />
bis.close();<br />
endTime = new Date();<br />
System.out.println(&#8221; Method 4  &#8211; time taken (ms) : &#8220;+(endTime.getTime() &#8211; startTime.getTime()));<br />
}<br />
}</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2007/02/28/binary-file-processing-with-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

