Wednesday, July 27, 2011

Apple Magic Mouse

I've been using the Apple Magic Mouse for over a month now, and I must say that I really like it.  Make sure that you use it with BetterTouchTool.  With BetterTouchTool, you can program the mouse to do different things to your liking.  ButterTouchTool has a "windows snapping" feature like Windows 7 if you like that.

Tuesday, July 26, 2011

Acer Aspire 5732z Touchpad Not Working

Problem:  

A friend asked me for help.
Acer Touchpad suddenly stopped working.  Tried Fn+F7 as suggested, not working.  Tried uninstalling/reinstalling driver, not working.

Solution: 

On the left of the power button (where you turn your laptop on and off), there is a little button.  It's the on/off button for the touchpad.  Make sure that it's on.  Simple as that.  Took me a while to figure that out.  Since it wasn't my laptop, I didn't know all of its functions.  Hope this helps someone someday.

Wednesday, July 20, 2011

Removing Sweat Sheen With Photoshop

  1. Create a new layer and "darken" for blending mode
  2. Choose the brush and set "opacity=20%"
  3. Alt (keyboard) to pick the area without the sweat and apply to the sweat area
Reference:  http://www.youtube.com/watch?v=wEZgawNrt2E

Friday, July 15, 2011

HmacSHA1 in Java and C#

Java:

byte[] password = "password".getBytes();
SecretKeySpec keySpec = new SecretKeySpec(password,"HmacSHA1");
Mac hmacsha1 = Mac.getInstance("HmacSHA1");
hmacsha1.init(keySpec);
byte[] hash = hmacsha1.doFinal("test".getBytes());
String hashBase64 = new String(Base64.encodeBase64(hash));
System.out.println(hashBase64);

C#:

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] password = encoding.GetBytes("password");

HMACSHA1 hmacsha1 = new HMACSHA1(password);
byte[] hash = hmacsha1.ComputeHash(encoding.GetBytes("test"));

String hashBase64 = Convert.ToBase64String(hash);
Console.WriteLine(hashBase64);

Base64 Encoding String in Java and C#

Java:

String base64 = new String(org.apache.commons.codec.binary.Base64.encodeBase64("test".getBytes()));
System.out.println(base64);

C#:

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string base64 = System.Convert.ToBase64String(encoding.GetBytes("test"));
Console.WriteLine(base64);

Convert String To Hex in Java and C#

Java:


String hex = new String(org.apache.commons.codec.binary.Hex.encodeHex("test".getBytes()));
System.out.println(hex);

C#:

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string hex = System.BitConverter.ToString(encoding.GetBytes("test")).Replace("-", string.Empty);
Console.WriteLine(hex);




Thursday, July 14, 2011

Parse XML String in Java

Here are a couple of easy ways to parse an xml string in java:

String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://playingtreee.blogspot.com/\">4654ebd75e9cbd8a4823e964f0dceef0</string>";

Example 1:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
System.out.println(doc.getFirstChild().getTextContent());

Example 2:

DOMParser parser = new DOMParser();
parser.parse(new InputSource(new StringReader(xml))); 

Document doc = parser.getDocument();
System.out.println(doc.getFirstChild().getTextContent());

Wednesday, July 13, 2011

Key-Value Pairs in .NET

You can add these to App.config and Web.config.



  <appSettings>
    <add key="blog" value="playingtree"/>
  </appSettings>


To read it,


using System.configuration;


ConfigurationManager.AppSettings["ReportProcessingRoot"];

Monday, July 11, 2011

Farewell AJ

AJ passed away yesterday.  Gave him a burial today.  How sad :(  

Different Ways of Loading Properties Files in Java


MethodParameter formatLookup failure behaviorUsage example
ClassLoader.
getResourceAsStream()
"/"-separated names; no leading "/" (all names are absolute)Silent (returns null)this.getClass().
getClassLoader()
.getResourceAsStream
("some/pkg/resource.properties")
Class.
getResourceAsStream()
"/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's packageSilent (returns null)this.getClass()
.getResourceAsStream
("resource.properties")
ResourceBundle.
getBundle()
"."-separated names; all names are absolute;.properties suffix is impliedThrows unchecked
MissingResourceException
ResourceBundle.
getBundle("some.pkg.resource")




http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html?page=2

Friday, July 8, 2011

Where to put mime.types in web app?

Put it under WEB-INF/classes/META-INF/mime.types so MimetypesFileTypeMap can find and load it.

vsvars32.bat is missing

C:\Program Files\Microsoft Visual Studio 10.0\Common7\Tools\vsvars32.bat


I installed Visual Studio 2010 Express and couldn't find the file vsvars32.bat anywhere; however, after I installed Visual Studio 2010 Professional, I was able to find it.

Install, Uninstall, Start, Stop Windows Service at Command Line

To install,
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil MyService.exe


In uninstall,
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil /u MyService.exe


To start,
net start MyService


To stop,
net stop MyService

Client/Server Communication Between Host OS and Guest OS in VirtualBox

Context:


Host OS:  Mac OS X
Guest OS:  Windows XP
VirtualBox


Problem:


I have IIS Express 7.5 running .NET web services in Windows XP.  I have Jetty running JEE web application in Mac OS X.  I need to make requests to IIS server, and in return, I also need to make requests to Jetty server.


Solution:


To enable the communication line to IIS Express in Windows XP, I need to set up a port forwarding with VirtualBox.  To do this, you go into the Network Adapters settings and choose "Port Forwarding,"  choose the plus sign (Insert new rule), you get a new row with six columns.  


Here's my settings:
  Name               Protocol         Host IP        Host Port       Guest IP     Guest Port
IIS Express         TCP           127.0.0.1         1071                                     1071


Guest IP is intentionally left blank.  When I do http://localhost:1071 in Mac OS X, the traffic gets forwarded to IIS Express in Windows XP running at port 1071.  One thing to note is that your Windows Firewall may block the traffic, so make sure that you allow that to happen.


To enable the communication line to Jetty from Windows XP, I don't need to set up anything.  I simply need to connect to it with its IP address.   In my case, my Mac has an IP address of 192.168.1.104, so I can connect to it with that IP address.

Missing Semicolon After &#xA0 With XmlWriter

Recently, I ran into this error:

Exception thrown in BuildReports: Invalid syntax for a hexadecimal numeric entity reference. Line 175, position 3159.

This exception was thrown when &#160; was converted into &#xA0 with the missing semicolon instead of &#xA0;

This was random.  Some &#160; got converted correctly with the semicolon; and some got converted with the missing semicolon.

I was able to fix it with changing the encoding from ASCII to UTF8

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;

Thursday, July 7, 2011

Struts 2 Gzip HTML Output

I want to send back gzip file of an html file.


struts.xml:



<action name="ReportView" class="ReportViewAction" method="execute">
    <result name="success" type="stream">
        <param name="contentType">text/html</param>
        <param name="inputName">fileStream</param>
        <param name="bufferSize">1024</param>
    </result>
</action>


Note:  you can set/override this static params in your action by providing getters.  For example, to return a dynamic value for the contentType


public String getContentType() {
   // contentType is set to whatever you want
   // depending on your content.
   // be it text/html, application/vnd.ms-excel, application/pdf
   return contentType;  
}


Action:



public class ReportViewAction extends ActionSupport implements ServletResponseAware {

    private String id;
    private InputStream fileStream;
    
    @Override
     public String execute() throws Exception {
         Session session = HibernateUtil.currentSession(false);
         Report report = (Report)session.load(Report.class, id);
         // content is a Blob
         fileStream = report.getContent().getBinaryStream();
         return super.execute();
    }
     
     public String getId() {
         return id;
     }

     public void setId(String id) {
         this.id = id;
     }

     // this matches the inputName specified struts.xml
     public InputStream getFileStream() {
         return fileStream;
     }

     public void setFileStream(InputStream fileStream) {
         this.fileStream = fileStream;
     }

     @Override
     public void setServletResponse(HttpServletResponse response) {
         response.setHeader("Content-Encoding", "gzip");
     }
}



Struts 2 File Upload

JSP:


<s:form action="FileUpload" enctype="multipart/form-data">
   <s:file name="upload" label="File"></s:file>
   <s:submit/>
</s:form>


Action:


public class FileUpload extends ActionSupport {
    private File file;
    private String contentType;
    private String filename;

    @Override
    public String execute() throws Exception {
       return super.execute();
    }

    public void setUpload(File file) {
       this.file = file;
    }

    public void setUploadContentType(String contentType) {
       this.contentType = contentType;
    }

    public void setUploadFileName(String filename) {
       this.filename = filename;
    }
}

Unzip and Gzip with Java

Download the zipped file.  Get the files within the zipped file and gzip each of the file.


ZipInputStream zipStream = null;

try {
    final int BUFFER = 2048;

    GZIPOutputStream dest = null
;
    zipStream = new ZipInputStream(new BufferedInputStream(
                                   new FileInputStream(file)));

    ZipEntry zipEntry;
    while ((zipEntry = zipStream.getNextEntry()) != null) {
       int count;
       byte data[] = new byte[BUFFER];

       String reportName = zipEntry.getName();
       File report = File.createTempFile("rpt", "gz");
       dest = new GZIPOutputStream(

              new FileOutputStream(report), BUFFER);

       while ((count = zipStream.read(data, 0, BUFFER)) != -1) {
         dest.write(data, 0, count);
       }
       dest.flush();
       dest.close();
    } finally {
       if(zipStream != null) {
          zipStream.close();
 
       }   
    }

Hibernate.createBlob with Apache HttpClient


I wanted to download a file with Apache HttpClient and save it as a blob with Hibernate.

HttpEntity httpEntity = response.getEntity();
Hibernate.createBlob(httpEntity.getContent(), (int) httpEntity.getContentLength());

The thing to note here is that the size of the file has to be specified by doing this(int) httpEntity.getContentLength()for it to work.

MySQL Data Modeler and UML Diagrams on Mac OS X

MySQL Workbench has a data modeling tool.  It's inconspicuous though.  To get to it, you have to open up the SQL Editor and do File -> New Model.  It can export to different output formats such as pdf, png, and even SQL that you can run on your database.  Additionally, you can "reverse engineer" your existing tables.


For UML Diagrams,  I like yEd Graphical Editor.  It does what I want it to do.


Both are free tools.

MySQL Database Browser on Mac OS X

I started using MySQL Workbench and Sequel Pro.  They work really well.

Upload files with other parameters in .NET

To simply send a file, .NET has this built-in.  Very easy to use.


System.Net.WebClient webClient = new System.Net.WebClient();
webClient.UploadFileAsync(new Uri(anURL),  aFile);


However, I needed to specify the file name and send other parameters, so here's what I did with the help of Krystalware.HttpUploadHelper:


// my files to upload
UploadFile[] files = new UploadFile[] { 
  new UploadFile(aFile, "aFileName", "application/zip")
};


// form data
NameValueCollection form = new NameValueCollection();
form["guid"] = guid;


HttpUploadHelper.Upload(anURL, files, form);

Wednesday, July 6, 2011

Running a Site using IIS Express from the Command Line

http://learn.iis.net/page.aspx/870/running-iis-express-from-the-command-line/
  1. Open a command prompt.

    You do not need Administrator user rights to run the commands in this walkthrough. However, you must have Administrator user rights if you want to run IIS Express on ports numbered 1024 or less.
  2. Run the following command to navigate to the IIS Express installation folder:

    cd \Program Files\IIS Express
    or if you are using a 64-bit OS, run the following command:

    cd \Program Files (x86)\IIS Express
  3. Run the following command to view the IIS Express usage string:

    iisexpress /?

    IIS Express Usage:
    ------------------
    iisexpress [/config:config-file] [/site:site-name] [/siteid:site-id] [/systray:boolean]
    iisexpress /path:app-path [/port:port-number] [/clr:clr-version] [/systray:boolean]

    /config:config-file
    The full path to the applicationhost.config file. The default value is the IISExpress8\config\applicationhost.config file that is located in the user's Documents folder.

    /site:site-name
    The name of the site to launch, as described in the applicationhost.config file.

    /siteid:site-id
    The ID of the site to launch, as described in the applicationhost.config file.

    /path:app-path
    The full physical path of the application to run. You cannot combine this option with the /config and related options.

    /port:port-number
    The port to which the application will bind. The default value is 8080. You must also specify the /path option.

    /clr:clr-version The .NET Framework version (e.g. v2.0) to use to run the application. The default value is v4.0. You must also specify the /path option.

    /systray:boolean
    Enables or disables the system tray application. The default value is true.

    /trace:debug-trace-level
    Valid values are info or i,warning or w,error or e.

    Examples:
    iisexpress /site:WebSite1
    This command runs WebSite1 site from the user profile configuration file.

    iisexpress /config:c:\myconfig\applicationhost.config
    This command runs the first site in the specified configuration file.

    iisexpress /path:c:\myapp\ /port:80
    This command runs the site from c:\myapp folder over port 80. 
  4. Run your site using one of the following:
    • Use /config to run a site from a configuration file.

      See "Running your site from a configuration file" for more information.
    • Use /path to run a site from the application folder.

      See "Running your site from the application folder" for more information.
    Note: The /path option and the /config option cannot be combined.
  5. Once your site is running, you can use the IIS Express system tray to manage it. For more information, see Use the Windows System Tray to Manage Websites and Applications. Alternatively, you can disable the system tray by running the following option:

    /systray:false

Running your site from a configuration file

IIS Express and IIS use the ApplicationHost.config file, which specifies global settings for sites, application pools, handlers, etc. IIS Express uses a default, user-specific ApplicationHost.config file to allow many users to share the same computer without interfering with other user's settings. This file is located in the %userprofile%\Documents\IISExpress\config folder or %userprofile%\My Documents\IISExpress\config folder, depending on your OS. When you run a site from a configuration file, you can specify which site to run.
You can use the following commands:
  • To run the website Website1 in the default configuration file, run:

    iisexpress /site:WebSite1
  • To run the first website in the default configuration file, run:

    iisexpress
  • To run the first website in a custom configuration file, run:

    iisexpress /config:c:\myconfig\applicationhost.config
  • To run a site called MyBlog from a custom configuration file, run:

    iisexpress /config:c:\myconfig\applicationhost.config /site:MyBlog
Note: The /config option specifies the full path of the configuration file. You can omit this option if you want to use the default configuration file. The /site option specifies a particular site in the configuration file. You can omit this option to run the first site in the configuration file.

Running your site from the application folder

You can also use the /path option to run a site directly from a folder. This option works for any type of application, including static HTML, ASP.NET, PHP, and WCF. By default, IIS Express will run the site on http://localhost:8080/. For a managed website, such as ASP.NET, IIS Express will use .NET 4.0. You can use the /port and /clr options to override these default values.
For example, the following command runs the specified application, "myapp," on http://localhost:9090/ by using .NET 2.0:
iisexpress /path:c:\myapp\ /port:9090 /clr:v2.0

Tuesday, July 5, 2011

ASP.NET: Visual Studio 2010 with IIS Express 7.5

Context:

Windows XP
Visual Studio 2010
ASP.NET
IIS 5.1
IIS Express 7.5

Problem:

I wanted to run my ASP web site from Visual Studio 2010 and access the web site from another computer.  In my case, it's a Windows XP running in VirtualBox.

Visual Studio 2010 came with a development server, you could run your ASP pages directly from it.  However, it is restricted.  You can only access it locally, meaning that you can only access it on the same machine that Visual Studio 2010 is running.

Since I wanted to access it from a different machine,  I tried publishing my web site to IIS 5.1.  After registering ASP.NET Framework 2 with it to work with aspx and asmx, I tried to access it from a different machine, and I got this in my event log:

Failed to execute request because the App-Domain could not be created. Error: 0x80131902 


Failed to initialize the AppDomain:/LM/W3SVC/1/ROOT


Exception: System.Configuration.ConfigurationErrorsException


Message: Exception of type 'System.Configuration.ConfigurationErrorsException' was thrown.


StackTrace:    at System.Web.Configuration.ErrorRuntimeConfig.ErrorConfigRecord.System.Configuration.Internal.IInternalConfigRecord.GetLkgSection(String configKey)
   at System.Web.Configuration.RuntimeConfigLKG.GetSectionObject(String sectionName)
   at System.Web.Configuration.RuntimeConfig.GetSection(String sectionName, Type type, ResultsIndex index)
   at System.Web.Configuration.RuntimeConfig.get_HostingEnvironment()
   at System.Web.Hosting.HostingEnvironment.StartMonitoringForIdleTimeout()
   at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters)
   at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters)
   at System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironment(String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters)
   at System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironmentAndReportErrors(String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters)

Solution:

For a while, I didn't know what the problem was.  I searched the Internet and found different solutions, such as trying to grant security access to the wwwroot and whatnot.  I tried it all, but it didn't work for me.  It was frustrating.


After some research, I found out that I could get what I wanted through getting Visual Studio 2010 SP1 and IIS Express 7.5.  After installing the SP1 and IIS Express, to tell Visual Studio to use IIS Express instead of the default Visual Studio Development Server, you right click on your web project and choose "Use IIS Express..."  That's it.  I did get it to work how I wanted it to.

P.S.  I've been a Java guy for a long time.  Recently, I started working on this project which has .NET stuff, so I just started digging into .NET for a couple of weeks now.

.NET Web Service: System.InvalidOperationException: Missing parameter:

Context:

.NET Web Service
Apache HttpClient

Problem:


When I tried to call the service as follows from my JUnit Test

HttpPost post = new HttpPost("http://localhost:1287/service.asmx/SubmitZip");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
MultipartEntity entity = new MultipartEntity();
entity.addPart("b64zip", new StringBody(new String(Base64.encodeBase64(IOUtils.toByteArray(submissionStream)))));
post.setEntity(entity);

I got this error:

System.InvalidOperationException: Missing parameter: b64zip.
   at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
   at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

Solution:


To fix it, I needed to call it as follows:


List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("b64zip", new String(Base64.encodeBase64(IOUtils.toByteArray(submissionStream)))));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

Apache HttpClient and Charles Web Debugging Proxy

To set Charles Web Debugging Proxy to capture http traffic run from Apache HttpClient:

DefaultHttpClient client = new DefaultHttpClient();
// you can set various parameters for your client here.
// set up the proxy.
HttpHost proxy = new HttpHost("localhost", 8888);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

Monday, July 4, 2011

RED Scarlet. Canon 5D Mark II. Analog vs. Digital

i was trying to explain to a friend something, something about the RED Scarlet.  the information provided here is as good as my understanding.  read it at your own risk :)

before the advent of digital cameras, traditionally, movies have been shot with 35mm film.  35mm has been dominating for more than a century.  35mm has been unchallenged for a long time until the digital revolution gave rise to the digital camera and digital cinema.  besides the quality, the advantages of digital over film are obvious.  speaking of quality, it was a problem for digital before, but no longer it is.  digital has caught up and is able to produce stunning quality.

when we speak of quality, disregarding the other factors, the simplest comparison is resolution.  what resolution means is the the number of horizontal pixels X the number of vertical pixels.  this is how much detail that you can put in a picture.  what you hear a lot nowadays is HD.  HD comes in 2.5 flavors:  1. 1280x720p, 2. 1920x1080i, 2.5. 1920x1080p.  Not going into too much details, full HD is 1080.  this is the best resolution that you can get at home at the current moment.

since 35mm has no pixels, 35mm film is usually scanned in and processed at 2K (2048x1080) or 4K (4096x2160).  For a long time, digital cameras would not to able to produce films at these levels. 

then comes the RED ONE camera, manufactured by RED, to my knowlege, the first digital camera that could capture at the maximum of 4.5K (4480x2304) and really pushed the envelope of digital cinema and closed the gap.  a lot of the movies have been shot with the RED ONE.  if you go to RED's web site, you can see the long list of movies.  the RED ONE has been sold and in use for a while now.

the RED EPIC is the next generation.  it can capture at a maximum of 5K (5120x2700).  the body has scaled back.  the brain weighs only 5 pounds.  whereas the RED ONE only captures motion pictures, the RED EPIC not only captures motion pictures but also still pictures.  the EPIC comes in different models varying in prices.  what i really like about RED cameras, besides the superb quality, is that they have the modular design, meaning that all the components are interchangable.  why this is good?  you can change or upgrade a certain component without upgrading the whole thing.  they have a lot of accessories.  better yet, they even work with Canon and Nikon lenses using lens mounts.  it has a lot of inputs and outputs.  in short, it's really robust, flexible and extensible.

since the EPIC is quite expensive, it's not for common consumers.  what i'm really waiting for is the SCARLET which is supposed to be cheaper.  i haven't seen the specs on the SCARLET yet, but i will be happy at 3K for a price of $5000 (brain only.)  adding a lens and a component or two, it will end up like $10,000.

you probably have heard of the Canon 5D Mark II.  it's one of Canon cameras that is video capable.  it's very popular.  amazon retails it for around $3200 (body + lens).  it can capture motion pictures at HD.  it's supposed to be very good in low light.  if you want something now and don't care to shoot at more than HD, it's a good one to have.  if you want something to shoot more than HD and are willing to spend more money, i think SCARLET will be awesome.

if you have a lot of money and don't care how you spend it, i would recommend the top model of the EPIC.  since you don't care how you spend your money, get me one too, will you?  :)

Friday, July 1, 2011

That assembly does not allow partially trusted callers

I got this error "That assembly does not allow partially trusted callers" when I was trying to install a Windows Service written in C#.  After searching the Internet for a while and trying different solutions such as [assembly: System.security.AllowPartiallyTrustedCallers()] and others, nothing seemed to help.  My problem turned out to be that I was trying to install the service from a mapped network drive. After I copied the service over to the local drive, I was able to install it successfully.

Copying Music from IPod to Mac

  1. Download Detune from http://www.headlightsoft.com/detune/
  2. Install and run it on the Mac
  3. Connect IPod
  4. Create new folder on the Mac
  5. Highlight, select the songs, and drag them from Detune to the new folder
  6. Done.  That's it.

VirtualBox - Increasing Disk Space for Guest OS

Context:

VirtualBox 4.0.8
Host OS:  Mac OS X 10.6
Guest OS:  Windows XP

Problem:

I need to increase the primary virtual hard drive from the default size of 10GB.  

Solution:

If you simply want to add more space to the guest os, you can easily add additional hard drives by doing settings > storage > add hard disk and designate those as secondary hard drives.  For me, I need to increase the size of the primary hard drive, because Visual Studio 2010 requires things to be installed there.  Fortunately, starting with version 4, VirtualBox has made it really easy.  
  1. Open up Terminal
  2. Run the command VBoxManage modifyhd WindowsXP.vdi --resize 40000  (WindowsXP.vdi is my disk image.  I want to increase it to 40GB.)
  3. Step 2 increases the size of the hard disk, but  to the guest OS, it is still 10GB.  To make Windows XP aware of the new size of 40GB, I need to download GParted  live CD ISO and run it.  To run the GParted ISO, go to settings > storage > Empty (CD icon under IDE Controller) > CD icon (right of CD/DVD Drive: IDE Secondary) > Choose a virtual CD/DVD disk file...
  4. Start the guest OS.  GParted will boot up.
  5. Once I'm in GParted, I can simply drag to increase the size of the partition from 10GB to 40GB.
P.S.  You, reader, may find other detailed solutions elsewhere with pictures if you need more detailed instructions.

If you happen to have vmdk file instead of vdi, you need to convert your vmdk to vdi first by doing this: VBoxManage clonehd --format VDI WindowsXP.vmdk WindowsXP.vdi