Friday, December 16, 2005

Geek Heaven

I came across the Dictionary of Algorithms and Data Structures tonight on Digg. This site has everything you would ever want to know on an exhaustive list of algorithms, algorithmic techniques, data structures, archetypical problems, and related definitions.


Dictionary of Algorithms and Data Structures

Technorati Tags: ,

Sunday, December 11, 2005

Ten Commandments of Egoless Programming

I came across this list tonight. These are some very interesting principles to live by in regards to one's programming career.


Ten Commandments of Egoless Programming - (Lamont Adams, Builder.com | Sunday, July 14 2002)

  1. Understand and accept that you will make mistakes. The point is to find them early, before they make it into production. Fortunately, except for the few of us developing rocket guidance software at JPL, mistakes are rarely fatal in our industry, so we can, and should, learn, laugh, and move on.
  2. You are not your code. Remember that the entire point of a review is to find problems, and problems will be found. Don't take it personally when one is uncovered.
  3. No matter how much "karate" you know, someone else will always know more. Such an individual can teach you some new moves if you ask. Seek and accept input from others, especially when you think it's not needed.
  4. Don't rewrite code without consultation. There's a fine line between "fixing code" and "rewriting code." Know the difference, and pursue stylistic changes within the framework of a code review, not as a lone enforcer.
  5. Treat people who know less than you with respect, deference, and patience. Nontechnical people who deal with developers on a regular basis almost universally hold the opinion that we are prima donnas at best and crybabies at worst. Don't reinforce this stereotype with anger and impatience.
  6. The only constant in the world is change. Be open to it and accept it with a smile. Look at each change to your requirements, platform, or tool as a new challenge, not as some serious inconvenience to be fought.
  7. The only true authority stems from knowledge, not from position. Knowledge engenders authority, and authority engenders respect—so if you want respect in an egoless environment, cultivate knowledge.
  8. Fight for what you believe, but gracefully accept defeat. Understand that sometimes your ideas will be overruled. Even if you do turn out to be right, don't take revenge or say, "I told you so" more than a few times at most, and don't make your dearly departed idea a martyr or rallying cry.
  9. Don't be "the guy in the room." Don't be the guy coding in the dark office emerging only to buy cola. The guy in the room is out of touch, out of sight, and out of control and has no place in an open, collaborative environment.
  10. Critique code instead of people—be kind to the coder, not to the code. As much as possible, make all of your comments positive and oriented to improving the code. Relate comments to local standards, program specs, increased performance, etc

Thursday, December 08, 2005

SQL Server

Currently installing SQL Server 2005. I get to do some work with the latest SQL Server version starting today. Time to go visit the local bookstore.

tags:

Tuesday, December 06, 2005

Ten essential add-ins for Visual Studio

James Avery has posted an article on MSDN where he focuses on 10 essential add-ins that every Visual Studio developer must have now.

I have used TestDriven.Net in the past myself, but I have not used any of the other tools. I need to download the tools that Mr. Avery talks about in the article and try them out.

read more | tags: , ,

Thursday, November 24, 2005

MCSD

I started working on my MCSD a while back, but we started doing more Java at work. Recently, we have been doing a lot more C#, so I am interested in picking it up again. I want to complete it this time, though.

Wednesday, November 09, 2005

Delphi

I used to use Delphi in my job all the time. I got moved to a different project since that time and I have not really used Delphi in over two years. I had to start using it a bit this past week at work. It is so funny to feel like a newbie when you sit down to something after programming for 16+ years. :)

I finally started remembering things and got back up to speed.

tags: , ,

Tuesday, September 13, 2005

Eclipse Wiki

I just came across the Eclipse Wiki today. According to the site, it was created to provide the development community with a place to share information about Eclipse and its sub-projects.

read more | tags: , ,

Thursday, August 18, 2005

Using JUnit Test Groups

I came across an interesting article on DogBiscuit today that talks about how to setup test groups in JUnit if you have expensive setup code that would normally be run before each test.

read more | tags:

Saturday, July 16, 2005

Does Intel's compiler cripple AMD performance?

One of the claims in AMD's sensational antitrust complaint against Intel has been getting some play around the web lately. Specifically, folks are focusing on what AMD says about Intel compilers and how they react to the presence of AMD processors. Here's the meat of the claim, taken directly from the AMD complaint:

read more | digg story

Sunday, July 10, 2005

Regular Expression Library

A library of pre-written regular expressions that you can plug into your code. Also, features a regular expression online testing engine against inputted text or a website text. Very handy resource!

read more | digg story

Thursday, July 07, 2005

Excited about programming again

For the past year or so, I have had a situation at work where I have been limited in what I could due to some issues between my current company and my previous company. It seemed like everything that I got put on, a couple of weeks later, someone came along and said that I could not work on that particular project. My job seemed to be going no place.

I got word this week that things have finally been cleared up and I can go back to working on some of the projects that I had been attempting to work on in tthe past. This was like someone lifting a huge elephant right off my back or something. I had been quite down as of late due to all of this.

After getting this news this week, I have actually been interested in programming again. Hopefully everything will start picking up and works gets fun again.

Friday, July 01, 2005

Programming doldrums

Have you ever been in a state where there was so much that you wanted to do in programming, yet you didn't really want to do anything? I am at that point right now in my programming life. I have been jerked, pulled, and tossed around so much lately that I do not know which way is up.

In the past 3 months, I have been on and off projects that used Java, C++, C#, Delphi, and VB. It is like someone threw it all in a blender, turned it up on high, and out comes a lot of mush.

I have a personal project that I was really getting into when I was working with Java, but lately, I have been on a C++ kick. I got the Power Mac back in May and I want to do some programming in Objective-C and Cocoa for it, but that is just another ingredient to add to the mix.

I am not really sure what I want to do at this point. I just sit here at night now playing around in iTunes listening to various technical podcasts and I do not do any programming. I need a plan for something that I can stick to and finish. I guess I should just pick up the personal project again.

I just hope that I have not gotten into such a rut that I cannot get myself out of it.

Tuesday, June 28, 2005

AMD files suit against Intel

Wow! This one caught me off guard. I can certainly expect something like this from a software company that is fighting against the big fish in the pond, but I did not expect something like this in the computer chip market. I wonder if this has anything to do with Apple's decision to use Intel for their product line going forward?

Read the CNET News.com article for more information.

Eclipse 3.1 released at JavaOne

Eclipse.org released the latest version of the Eclipse development environment at JavaOne yesterday. Much of the excitement regarding Eclipse 3.1 centered on the Rich Client Platform upon which you can build very professional looking applications.

The Rich Client Platform has been greatly enhanced in this version of Eclipse. The system has improved performance, expanded tool support, bettery support for Java Web Start (JNLP), and Visual Editor support.

For more information and a podcast on the launch, check out this story on Between the Lines.

Sunday, June 26, 2005

Blog puke

I am not sure what exactly happened today at Blogger, but my mother emailed me asking about my blog and why the Blogroll was gone. I took a look and the template had reverted to the default and lost my changes at some point in the past 36 hours. It is fixed now.

Thursday, June 23, 2005

Eclipse CDT project 3.0 RC0

Eclipse.org has also released the first release candidate for the CDT (C/C++ Development Tools) Project. This is an excellent plugin development environment for Eclipse that gives full C/C++ development and debugging capabilities. CDT 3.0 RC0 runs under Eclipse 3.1 M7 and later.

Eclipse 3.1 RC3

Eclipse.org has released the Eclipse 3.1 RC3 development environment for all platforms. The environment seems to be getting quicker and more stable with each RC release at this point.

Saturday, June 18, 2005

Going home

God took one of his children home tonight. My father's sister, Lillian Parker, was taken to be with God tonight. She had a really bad heart attack Saturday and was put in the hospital.

My parents went to see her earlier today. My mother said that she looked quite bad with only about 20% functionality in her heart. My father called just a little while ago to give me the news and said that he knew it was just a matter of time earlier today, because she seemed to be just holding on... just like her mother did so many years ago when I was young.

My aunt was a life long member of Harmony Baptist Church in a small, unincorporated area of Blount county in Alabama. She always laughed and smiled when I saw her. Her laugh was always infectious. She was definitely a special lady.

Please pray for my family in this time of mourning, but please do not shed a tear, for she is in no longer suffering and she is much happier than we could ever be, because she is laughing and singing with her mother, Jesus, and having a wonderful fellowship with God, The Father!

Friday, June 17, 2005

Going back in time

I recently started playing around with C++, partly because I wanted to work with a cross-platform language other than Java that I could use on my Windows based laptop and my PowerPC Mac. I have been a developer for 16+ years, but working with C++ has me feeling like I am a new programmer again.

I have been struggling with virtual methods, abstract classes, and templates. I am currently stuck on a situation where I have a pure abstract class defined that I want to use in a collection to represent one of three different derived classes, but I seem to be getting some compile errors where I use it.

At least I am not getting paid like a new developer again.  I would go hungry. :)

Tuesday, April 05, 2005

JFrame setMinimumSize() and setMaximumSize() issue

I have been playing around with Swing tonight using JDK 1.5.0_02. I have found an issue where the setMinimumSize and setMaximumSize dimensions are not enforced on a JFrame. I wanted to keep a dialog from being resized smaller than a minimum bounds or larger than a maximum bounds. To do this, I originally used the following code in my application:

frame.setMinimumSize( new Dimension( 250, 200 ) ); frame.setMaximumSize( new Dimension( 325, 275 ) );
Unfortunately, as I mentioned above, this does not prevent you from resizing the frame smaller or larger than the specified sizes. Of course, you could just decide to not allow any resizing of the frame. To do that, you could use this line of code in your application:

frame.setResizable( false );
However, if you want to allow the user to resize a dialog, then this is not a viable alternative. I decided to create my own class derived from JFrame. This class takes a title as well as minimum and maximum dimensions. My constructor for the class looks like this:

private Dimension minimumSize;
private Dimension maximumSize;

public MyJFrame( String title, Dimension minimumSize,
  Dimension maximumSize ) throws HeadlessException
{
  super( title );
  this.minimumSize = minimumSize;
  this.maximumSize = maximumSize;
  initialize();
}
The initialize(): call does nothing more than make a call to addComponentListener on the frame. In this call, I create an anonymous ComponentAdapter class which overrides the componentResized method to handle the constraints on the frame. The code looks like this:

private void initialize() {
    this.addComponentListener( new ComponentAdapter() {
        @Override
        public void componentResized( ComponentEvent e ) {
            MyJFrame frame = (MyJFrame) e.getSource();
            int width = frame.getWidth();
            int height = frame.getHeight();
            boolean resize = false;
            if ( width < minimumSize.getSize().width ) {
                width = minimumSize.getSize().width;
                resize = true;
            }
            else if ( width > maximumSize.getSize().width ) {
                width = maximumSize.getSize().width;
                resize = true;
            }
            if ( height < minimumSize.getSize().height ) {
                height = minimumSize.getSize().height;
                resize = true;
            }
            else if (height > maximumSize.getSize().height ) {
                height = maximumSize.getSize().height;
                resize = true;
            }
            if ( resize ) {
                frame.setSize( width, height );
            }
        }
    })
}
This code is pretty straight forward. It grabs the current size constraints for the frame that fired the event. It then checks these constraints against the specified minimum and maximum dimensions. If the constraints on the frame are not met, the size of the frame is set explicitly, otherwise, the flow falls through and the frame is resized according to the size that the user has resized it.

There may be better ways to handle this situation. This is what I came up with tonight and it works pretty well. Hopefully future versions of the JDK will enforce the setMinimumSize and setMaximumSize dimensions on the JFrame component.

Technorati Tags: , ,

Monday, April 04, 2005

Eclipse Milestone Build 3.1M6 released; SWT problem?

Eclipse Foundation has released the latest milestone build of Eclipse 3.1 for download. This version has quite a few bug fixes and some enhancements. One of the enhancements allows for plugins to be setup in JAR files instead of a directory structure.

I downloaded it today and set it up on my laptop. I then opened up the SWT application that I am currently working on at home and found that there appears to be an issue with SWT in this build. My classpath is setup correctly and the build works, but when the application launches, I get a NullReferenceException on a call to super.configureShell( shell ). This all works in Eclipse 3.1M5a. I am not sure what has changed, but I need to play around with it a little more to see what is going on.

One thing that I noticed with the new plugin setup is that the SWT DLL for Win32 is located in a totally different directory now. I think they have a little work to do on this new plugin strategy. Of course, that is why they call this beta software. It might not work for everything that you want to do.

Update: I worked with this some more tonight and it appears that there is definitely an issue with SWT in the latest milestone build. I would imagine that it might be in the swt-win32-3128.dll file, but of course, you should not bank on that information. I use milestone build M6 and pointed it ot the swt.jar and the swt-win32-3123.dll for milestone build M5a and my application works.

Technorati Tags: , ,

Friday, April 01, 2005

Regular Expressions in Java

I started playing around with regular expressions this past week. I am going to use them in the personal project that I am working on to validate different user input data strings. I recently purchased a very good book from Apress called Regular Expression Recipes: A Problem-Solution Approach by Nathan A. Good. They have another book specifically for Java called Java Regular Expressions: Taming the java.util.regex Engine, but I did not know about it before I purchased the first book. It may have helped me with this problem. :)

Anyway, the book that I purchased has examples for Perl, Python, and shell scripting. Since it was the first example for each recipe, I picked off the regular expressions from the Perl code for the particulat items that I wanted to validate and used that in Java. I was dumbfounded when it did not work. As an example, I used a regular expression to validate an email address. The regular expression looked like this from the Perl example:

/^[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}$/
I spent a couple of evenings after work at home on this problem before I finally figured it out. You should not use the starting and ending slash ("/") when using any regular expression in Java. Java's regular expression compiler apparently sees this as a literal character when it compiles the expression and the corresponding validation ends up failing. When I removed those slashes, the validation unit test past and things were grand!

One other thing to remember in Java with regular expressions is that the backslash ("\") is an escape character. Unfortunately, it is also an escape character in Java. Thusly, you have to use double backslashes for the escape character in your regular expressions in Java. So, in the example above, the first \w should be set in Java as \\w.

Technorati Tags: , , ,

SWT/JFace, MVC, JUnit

Whew! Did I get them all in there? I have been struggling lately with the Model-View-Controller pattern. Well, I haven't been struggling with the pattern itself as much as I had been struggling with how to implement it properly and create unit tests in an SWT/JFace application. Being new to MVC, one struggles with what should be in the controller and what should not. I was trying to put everything in the controller, but that is not always feasible.

In my case, I was unsure about the inherited methods from the JFace Window class, such as createContents(), initializeBounds(), etc. Well, those methods do not need to be in the controller, because there is no interaction with the model. These methods are strictly there to create and initialize the view. The methods that I ended up putting in the controller were only those that dealt with the view with respect to the model.

For instance, in my example application that I put together tonight to play around with this process, I have a Contact class (model), a setup dialog (view), and a controller class. The model contains nothing more than first, middle, and last name strings for this example. It is quite simple. The view is also simple in that it has three Label controls, three Text controls, and two Button controls (Print and Cancel).

My controller class ended up having the following methods:

public void onFirstNameChanged();
public void onMiddleNameChanged();
public void onLastNameChanged();
public void onPrintClick();
public void onCancelClick();
The first three methods are called in the focusLost method for the FocusListener on the respective edit control for each component of the contact name. The onPrintClick method is called when I click on the Print button. It fires the print method on the view and does nothing more than print the contents of the model out to the console in this simple example. The onCancelClick method fires the close method on the view.

I was able to create unit tests for my controller class and the model, but I did not really create anything for the view. The view does nothing more than initialize itself and wait for user input or receives events from the controller. Since all of the major work for updating the model and other user interaction is handled in the controller, then I am not even sure if it matters that there are no unit tests for the view.

I could have simplified this example a little more by combining the view and the model, but since I have most of the classes already created for an application that I am currently working on for myself, I figured I would see if I could get things working with a model that is separate from the view.

I came across an interesting discussion on Martin Fowler's web site tonight which talks about Model-View-Presenter.  I need to investigate this further.

Technorati Tags: , , , , , , , ,

Saturday, March 19, 2005

ImageDescriptor problem on JFace actions?

I found what seems to be an issue with setting an jface.resource.ImageDescriptor for an jface.Action class.  I have a few standard button bar images that I was going to use in my application.  When I first set the image for the action, I thought I was doing something wrong.  I set the image originally, like this:

public ExitAction() extends Action {
 
    public ExitAction() {
        super( “E&xit@Ctrl+X“, ImageDescriptor.createFromFile( “images\\close.gif“ ) );
        setToolTipText( “Exit Application“ );
    }
}
Unfortunately, this produced a small red square on the button and on the menu item that the ExitAction was assigned to.  I checked the image thinking it was corrupt, but all was well.  After doing a little snooping, I found that you can also create an ImageDescriptor from a swt.graphics.Image.  I changed the code to look like this:

public ExitAction() extends Action {
 
    public ExitAction() {
        super( “E&xit@Ctrl+X“ );
        setToolTipText( “Exit Application“ );
        Image image = new Image( Display.getCurrent(), “images\\close.gif“ );
        setImageDescriptor( ImageDescriptor.createFromImage( image ) );
    }
}
This produces the desired results.  I am not sure why the first way of setting the image for the action did not work, but every tutorial that I have gone through and even the code in Apress' The Definitive Guide to SWT and JFace do it like I did it in the first code fragment above.

Technorati Tags: , ,

Using Ant to build an executable Jar file

Boy... I am tired.  It is 3:09 pm in the afternoon and I have only been up for just over three hours today.  I dove deep into SWT and JFace last night.  I am really enjoying JFace at this point.  It really makes building a GUI application with SWT so much easier.

Anyway, at some point during the night, for whatever reason (can't remember now), I decided to setup a build.xml file for Ant.  I did this for two reasons:  1)  I wanted to learn more about using Ant and 2) I wanted to see if I could setup a build properly for the SWT/JFace application that I am working on.

The setup of the build.xml to do a clean compile and to build a simple jar file was quite easy.  The problem came in, however, when I tried to build an executable Jar.  I never could get things to work correctly.  I kept getting a message about java not being able to find the main class when I tried to launch the jar.

A little after 6:00 am this morning, I finally decided that I should get some sleep.  I guess that helped, because after sitting here for the past 30 minutes looking at it again, I figured it out.  Well, I figured it out by accident.  :)

I did a little reading on the Sun Developer Network forums and something made me look at another executable jar file that I know I have on my computer.  When I took a look at the manifest in the jar, I noticed that all of the files listed on the Class-Path entry were in the same deployment directory as the executable jar.  I had tried putting them in a path on the classpath and putting them in the jar, but that never did work this morning.

So, I said what the heck and copied the appropriate external jar files that I knew the project needed into the directory where my jar file was located.  Now, mind you, this is the same jar that had just 30 seconds earlier given me that same “Cannot find the main class” error message.  After copying the files, I tried to launch the jar again and to my surprise, my application came right up.  Sweet!

I hate that I have wasted most of a Saturday, but I have definitely learned a lot about Ant and creating executable jar files in the past 18 hours.

Technorati Tags: , , ,

Thursday, March 17, 2005

JFace ApplicationWindow issue resolved

OK... duh... I read a couple of different articles tonight about using the ApplicationWindow class from JFace, but I missed both times that I had to include the org.eclipse.ui.workbench_<version>/workbench.jar and org.eclipse.core.runtime_<version>/runtime.jar to get it to work.

I was having another problem with my JFace demo application tonight when it came to Actions.  I had created a couple of private inner classes to handle exit and another action that I was playing around with.  Unfortunately, whenever I clicked on the menu item or the toolbar entry, I would get a stack trace in the Console window in Eclipse.

After doing some searching on Google for the past hour, I finally found out that you also have to include org.eclipse.osgi_<version>/core.jar.  I am not sure exactly what this is for as of yet, but it allows everything to work properly, so it got added.  :)

Technorati Tags: , , ,

Build errors using Ant and jCoverage

After using Ant and jCoverage at work as of late, I decided to creat a build.xml for my small application that I am writing for myself at home.  I have run into a problem that I cannot figure out at this point, though.  Whenever I do a full build (including jCoverage reports), I get the error shown below.  Has anyone seen anything like this?

coverage:jcoverage.instrument:
[instrument] jcoverage 1.0.4 copyright (c)2003 jcoverage ltd. http://jcoverage.com/
[instrument] instrumenting 13 classes to C:\Projects\MyContacts\build\instrumented
[instrument] Exception in thread "main" org.apache.bcel.classfile.ClassFormatException:
    Invalid constant pool reference: 1066. Constant pool size is: 1024
I am not sure what the problem is with this build.  It follows everything that we do at work.  Unfortunately, this is definitely something that I do not know enough about and I am unable to find too much information about it on Google.

If anyone has any insight on this problem, I would greatly appreciate any help.

Technorati Tags: , ,

GUI Development with SWT and JFace

OK... I took a dive into JFace tonight.  This is the first time that I have played around with it.  For those who do not know, JFace allows you do UI development using the SWT widgets without a lot of the overhead code that you would require if you were using the raw widgets.

I was following along with an article on JavaWorld called “Rich clients with SWT and JFace”.  The article shows a very simple demo that displays a simple window.  The class extends ApplicationWindow, which is a more robust version of the JFace abstract Window class.  Unfortunately, when I type in everything as shown and try to run it in Eclipse, I get an error that says:


Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/core/runtime/IProgressMonitor at com.pshack.application.Application.main(Application.java:30)
I changed the demo to create a separate Window class and use that instead of extending from ApplicationWindow.  This works.  I am not sure why extending from ApplicationWindow does not work for me.  It might be because I am using JDK5, but I doubt it.  I am sure it is just something that I do not understand as of yet.

Technorati Tags: , ,

Wednesday, March 16, 2005

SWT Development

I am currently writing an application that will fill a small bit of functionality that I need.  I am also using this as a way to learn more about JDK 5.0 and SWT development, in particular.  Over the past hour, I have realized, at least in JDK 5.0 (never tried it in earlier versions), you cannot override the SWT Display or Shell objects.

I was thinking about a way to have a main Application class that extends Display.  From that, I was going to have multiple window classes which extended Shell from SWT.  Unfortunately after I put together a couple of classes and tried to launch it, I get an error stating that overrides are not allowed.  I then remembered reading something like that on the web somewhere.  Unfortunately, this is one of those situations where you sort of remember something, but you cannot remember exactly where you saw it, so you have no clue where to find it again.  :)

Oh well, it is all a learning process.  That and the fact that it is just so much fun is the reason I got into software development over 16 years ago anyway.

Technorati Tags: ,

Friday, March 04, 2005

Joda-Time v1.0

I came across a new date and time API for the Java community the other day, but I did not get a chance to do anything with it until tonight.  The package is called Joda-Time v1.0.  Joda-Time provides a quality replacement for the Java date and time classes.

It is very easy to get up to speed with Joda-Time.  The main object that you will deal with if you are just doing regular date and time manipulations is the org.joda.time.DateTime class.  I refactored a couple of my classes tonight and I can say that using DateTime is far simpler than using the Date and Calendar objects from java.util.

I can actually create a new DateTime object, add some specified duration to it, and assign it to a variable all in one line of code.  Using the classes from java.util, I would have to get a Calendar object instance.  From that, I could add some specified duration.  To finally get a Date object, I call a method called getTime().  Geez!

Joda-Time is a very nice project.  The documentation is very clean and the web site has all of their JCoverage information for their unit tests.

Technorati Tags: ,

Saturday, February 26, 2005

Iterators in Java

Coming from a background in C# for the past couple of years, I am so glad to see the Java SDK add constructs that I have used in the past.

In a personal project that I am working on, I had created a couple of enumeration classes.  The classes had a lookup() method that I used to allow me to assign a particular enumeration label to a variable by looking up a particular id of one of the enumeration constants.  To facilitate the lookup of a particular enumeration value, there was a private array of all the available enumerations in the particular class.  The lookup() method was pretty straight forward...


//.. lookup procedure expects an id pass in
for ( int i = 0; i < available.length; i++ ) {
    if ( available[i].getId() == id ) {
        return available[i];
    }
    return null;
}
I decided at work yesterday to come home and setup the latest milestone release of Eclipse so that I could play around with JDK 5.0.  After getting that working, I refactored my enumeration classes to be actual enum classes now that Java 5 has the new enum keyword.  With that refactoring, I was able to make use of the new for-each style of iteration that Java 5 has added.  So, my lookup() method on the enumeration classes now look like this...

//.. lookup procedure still expects an id passed in
MyEnumType[] available = MyEnumType.values();
for ( MyEnumType e : available ) {
    if ( e.getId() == id ) {
        return e;
    }
    return null;
}
I have been used to this style of construct in C# which has the for-each style of iterations for a collection.  For a new Java developer, this method might be a little harder to understand.  There is not the explicit notion of having checking each object in a particular collection like you have in C# where you say “for each ...”, but I feel like this is a little cleaner code than the style where you use the index property, which could always lead to problems itself.

Of course, Java had the older style of iterations where you could get an iterator and then calling hasNext() on each loop iteration, but it is a bit more to type and it is nice to have the compiler itself be a little smarter in situations like this where I am looping over a collection and checking every object in the collection.

Technorati Tags: , , ,

Wednesday, February 16, 2005

Using INSERT..SELECT with MySQL

I have been working on a small application at home lately which is going to use MySQL for data persistence.  I was messing around with my tables tonight and got into a situation where I wanted to add data into one table using the last inserted value from the auto_increment primary key field in another table.

According to the documentation for MySQL, I should be able to use LAST_INSERT_ID(), but I couldn't figure out exactly how to get it to pull the last inserted ID from a different table.

So, I then tried the following code...

INSERT INTO table2 (id, field1, field2) SELECT NULL, 4, id FROM table1 t WHERE t.id IS NULL;
According to some information that I found in a comment posted on the documentation for the INSERT..SELECT command on the MySQL documentation site, this should give me the last inserted ID from the first table.  Nope... this results in no errors and no rows being added to the table.  Very weird!

Finally, I came up with the following...

INSERT INTO table2 (id, field1, field2) SELECT NULL, 4, MAX(id) from table1;
So far, this seems to give me the results that I am after.

Technorati Tags:

Tuesday, February 15, 2005

Adding a new DataRow to a DataTable

This is one little item that I never can seem to remember, because I just do not use it that often, so I thought I would commit it to my blog.

When creating a new DataRow that you want to subsequently add to a DataTable, you generally create the columns that you need for the rows and then you add data values. The code for this looks something like this...

    DataTable ErrorTable = new DataTable();
    ErrorTable.Columns.Add(new DataColumn("Fault Code Namespace", typeof(string)));
    ErrorTable.Columns.Add(new DataColumn("Fault Code Name", typeof(string)));
    ErrorTable.Columns.Add(new DataColumn("SOAP Actor that threw Exception", typeof(string)));
    ErrorTable.Columns.Add(new DataColumn("Error Message", typeof(string)));
    ErrorTable.Columns.Add(new DataColumn("Detail", typeof(string)));
    DataRow row = ErrorTable.NewRow();
    row["Fault Code Namespace"] = error.Code.Namespace;
    row["Fault Code Name"] = error.Code.Name;
    row["SOAP Actor that threw Exception"] = error.Actor;
    row["Error Message"] = error.Message;
    row["Detail"] = HttpUtility.HtmlEncode(error.Detail.OuterXml);


There is a simpler way to write the code above which sets up the data values and adds the DataRow to the DataTable. That code can be written in one line like this...

    ErrorTable.Rows.Add( new object[] {error.Code.Namespace, error.Code.Name, error.Actor,
    error.Message, HttpUtility.HtmlEncode(error.Detail.OuterXml)} );


The code is definitely not more readable and is probably more of a headache for someone to come along later and maintain, but it is easier to type the first time around. :)

Technorati Tags: , , ,

Thursday, January 06, 2005

Make sure that CLASSPATH is correct

I had an issue with a java class today that I was trying to execute from the command line.  I kept getting the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: Example
After doing a little research, I found that my CLASSPATH variable was set to c:\junit3.8.1\junit.jar which was not allowing the virtual machine to properly find the binaries it needed to execute the class.  After clobbering the CLASSPATH variable (“set CLASSPATH=“), everything worked as expected.

Update
Someone that I work with gave me a good tip today that I did not know regarding Java and how it parses the CLASSPATH variable.  Make sure that you have a dot in the path declaration at the end.  In other words, in my case, the CLASSPATH would be something like this:

CLASSPATH=.;c:\junit\junit3.8.1\junit.jar
For those of you who can't quite see it, that is a period at the beginning of the CLASSPATH declaration.  This tells Java to use the current directory when searching for classes and JAR files.

Technorati Tags: ,