Dec
13
2003

MasterMind Solver

After playing Code Breakers (a MasterMind clone) at Neopets for a while, my head started to hurt. I thought there's got to be a better way to win this thing. Hunting round the Net turned up the two very good resources in the Links section. I've adapted Frans van Gool's excellent MasterMind Java Applet into my own Visual Basic beast.

My MasterMind Solver project shows all the remaining possible solutions at each stage of the game. This could be further optimised by deciding which is the best guess to elimate the most possibilities (and it's not necessarily one of the remaining possibilities). But this one works good enough for me - and it's simple too.

Downloads

  MasterMindSolver.zip - contains: Complete Master Mind Solver Project (22 kb)

Links

The excellent MasterMind java applet by Frans van Gool (on which this project is based)

A very good article on MasterMind solving algorithms by Gary Darby

Aug
28
2003

Zip Extraction Class

Extract Zip archives using the ZLib.dll

Well I've finally put the Zip Extraction Class together. It's got a very simple and somewhat limited interface. Limitations include having to extract all the files in a zip archive and not setting the extracted file's Modify Date to its Modify Date in the archive.

If you declare the ZipExtractionClass in the declerations area of a Class Module or Form using the WithEvents keyword then you gain access to the Status, Progress and Error Events.

Usage

Add ZipExtractionClass.cls to your project and ensure that zlib.dll is reachable

Option Explicit

Private WithEvents zip As ZipExtractionClass

Public sub Unzip

   Set zip = New ZipExtractionClass
   If zip.OpenZip("C:\Test\Test.zip") Then
      If zip.Extract("C:Test\Extract", True, True) Then
         MsgBox "Zip files extracted successfully", vbInformation
      End If
      zip.CloseZip
   End If
   Set zip = Nothing

End Sub

Downloads

  ZipExtractionClass.zip - contains: ZipExtractionClass.cls, Appnote.txt, ZLib.dll (45.0 kb)

  ZipProject.zip - contains: A sample project using the ZipExtractionClass (60 kb)

Links

The ZLib home page where you'll find the ZLib.dll: www.zlib.org

The PKZip File Format: www.pkware.com

More...

Aug
1
2003
VB6 // Wininet // HTTP

HTTP Class

Implement HTTP POST and GET with the HHTP Class using the Wininet Library

This class simplifies using the Wininet Library to implement HTTP requests. Using this class it's a piece of cake to POST Url-Encoded form data to a server.

This code has been revised (28 Aug 2003): There was an error in the URLEncode function where a hexed value was not necessarily 2 digits long. The SendRequest function has also been updated to download the request directly from the server by default (Reload).

This code has been revised (02 Sep 2003): The While loop for reading the returned data in SendRequest had faulty logic (changed to While r and (Read <> 0))

This code has been revised (29 Nov 2003): Updated OpenHTTP to both add the option to connect to any port and the ability to authenticate using basic authentication (plain text).

What it can't do

  • Return Progress Messages
  • Return Detailed Error Messages
  • Return the Response Header

Usage

Add HTTPClass.cls to your project

   'Example: POST a Form

   Dim h As HTTPClass

   Set h = New HTTPClass

   h.Fields("Username") = "Andrew"
   h.Fields("Email") = "andrew@paradoxes.info"
   h.Fields("Password") = "Secret"

   If h.OpenHTTP("www.paradoxes.info") Then
      Debug.Print h.SendRequest("test.asp", "POST")
   End If

   Set h = Nothing

   'Example: Download an Image to file

   Dim fh As Long
   Dim h As HTTPClass

   Set h = New HTTPClass

   If h.OpenHTTP("www.paradoxes.info") Then
      fh = FreeFile
      Open App.Path & "\vbcode.jpg" For Binary As #fh
      Put #fh, , h.SendRequest("/pics/vbcode.jpg", "GET")
      Close #fh
   End If

   Set h = Nothing

Downloads

  HTTPClass.zip - contains: HTTPClass.cls (1.9 kb)

More...

Jul
24
2003
VB6 // Stack

Stack Class

Store Items with this simple Stack Class

Sometimes I need to hold a few items in a stack and use the Collection Object to do this. There's no need of course, now that that Stack Class is here anyway. I've used a Variant array to hold the items so it can take strings, numbers, objects etc.

The buffer size is set to 100. If you're intending to store a lot more than 100 items in the stack (say 1000) then you'll want to adjust the buffer size to increase efficiency (as the Items array would be redimensioned 10 times).

Usage

Add StackClass.cls to your project

'Example 1

   Dim Stack as StackClass

   Set Stack = New StackClass

   Stack.Push 1
   Stack.Push 2
   Stack.Push 3

   Debug.Print Stack.Peek  'Prints 3
   Debug.Print Stack.Pop   'Prints 3
   Debug.Print Stack.Pop   'Prints 2
   Debug.Print Stack.Pop   'Prints 1

   Set Stack = Nothing


'Example 2

   Dim Stack as StackClass

   Set Stack = New StackClass

   Stack.Push 1
   Stack.Push 2
   Stack.Push 3

   While Stack.Count > 0
      Debug.Print Stack.Pop 'Prints 3, then 2, then 1
   Wend

   Set Stack = Nothing

Downloads

  StackClass.zip - contains: StackClass.cls (717 bytes)

More...

Jun
26
2003

PropertyBag Class

Persist private objects with the PropertyBag Class

If you use the PropertyBag Object then you'll know how indispensable it is. It does have some drawbacks though (primarily the lack of persistence for private object modules). My PropertyBag Class goes a long way towards fixing those drawbacks. I’ve added the ability to persist private object modules, to output to file (binary) or string (base64 encoded), to optionally compress the output using the zlib library, and I’ve managed to keep it compatible with the Microsoft’s PropertyBag!

I must give mention to Francesco Balena (see the links at the bottom of the page) whose article on the PropertyBag inspired me.

What it can do

  • Retains compatibility with Visual Basic's built-in PropertyBag
  • Persist Private Class Modules using the IPropertyBagClass Interface
  • Save/Load the PropertyBagClass contents to file or string
  • Optionally compress the PropertyBagClass Contents using the ZLib dll

Usage

Add PropertyBagClass.cls and IPropertyBagClass.cls to your Project

'To persist a Private Object you need to Implement the IPropertyBag Class
'MyGameClass Object
Option Explicit

Implements IPropertyBagClass

Public Name As String
Public Score As Long
Public HitPoints As Long
Public Lives As Long

Public PosX As Long
Public PosY As Long

Private Sub IPropertyBagClass_ReadProperties(PropBag As PropertyBagClass)

   Name = PropBag.ReadProperty("Name", "")
   Score = PropBag.ReadProperty("Score", 0)
   HitPoints = PropBag.ReadProperty("HitPoints", 0)
   Lives = PropBag.ReadProperty("Lives", 0)

   PosX = PropBag.ReadProperty("PosX", 0)
   PosY = PropBag.ReadProperty("PosY", 0)

End Sub

Private Sub IPropertyBagClass_WriteProperties(PropBag As PropertyBagClass)

   PropBag.WriteProperty "Name", Name
   PropBag.WriteProperty "Score", Score
   PropBag.WriteProperty "HitPoints", HitPoints
   PropBag.WriteProperty "Lives", Lives

   PropBag.WriteProperty "PosX", PosX
   PropBag.WriteProperty "PosY", PosY

End Sub

'And to save it...

   Dim mg As MyGameClass
   Dim pb As PropertyBagClass

   Set pb = New PropertyBagClass
   pb.WriteProperty "MyGame", MyGame
   If Not pb.SaveToFile(Path, False, True) Then
      MsgBox "Couldn't save the file " & Path, vbExclamation
   End If
   Set pb = Nothing

'And to reload it...

   Dim mg As MyGameClass
   Dim pb As PropertyBagClass

   Set pb = New PropertyBagClass
   If pb.LoadFromFile(Path) Then
      Set mg = New MyGameClass
      'Note: When reading a private object you have to create an instance
      'of it first and pass it as the default parameter
      Set mg = pb.ReadProperty("MyGame", mg)
      Set MyGame = mg
      Set mg = Nothing
   Else
      MsgBox "Couldn't load the file " & Path, vbExclamation
   End If
   Set pb = Nothing

Downloads

  PropertyBagClass.zip - contains: PropertyBagClass.cls, IPropertyBagClass.cls, zlib.dll (29.5 kb)

  MyGame.zip - A simple project to demonstarte how to persist private objects (27.4 kb)

Links

Another good article on vbaccelerator about persisting objects/data to XML by Steve McMahon

More...

May
3
2003

Alarm Class

Replace the Timer Control with this Alarm Class

This is a very simple Alarm Class. You set the alarm to go off in so many milliseconds and it will fire the Alarm event when the inverval is reached. The API callback function TimerProc is used, hence the need for the Alarm Module.

The code is undocumented, but should be easy enough to follow.

Usage

Add AlarmClass.cls and AlarmModule.bas to your project

Option Explicit

Dim WithEvents Alarm As AlarmClass

Private Sub Alarm_Alarm()

   MsgBox "Alarm!"

End Sub

Private Sub cmdSetAlarm_Click()

   Alarm.SetAlarm 5000

End Sub

Private Sub cmdCancelAlarm_Click()

   Alarm.CancelAlarm

End Sub

Private Sub Form_Load()

   Set Alarm = New AlarmClass

End Sub

Private Sub Form_Unload(Cancel As Integer)

   Set Alarm = Nothing

End Sub

Downloads

AlarmClass.zip - contains: AlarmClass.cls, AlarmModule.bas (0.9 kb)

More...

Feb
27
2003

String Class

Fast String concatenation with the String Class

Every time you concatenate a String in Visual Basic, the String is redimensioned to the length of the new String. If you are doing multiple concatenations in a loop then this becomes very inefficient.

The String Class dimensions a buffer and only redimensions the buffer when it becomes full. So if you choose the buffer length wisely (the best size would be the final length of the string) then you can gain enormous efficiency from using the String Class.

You may notice that the CopyMemory API is used to insert the string to be appended into the buffer and that the Prepend method calls CopyMemory twice. This means that the Prepend method is approximately half as fast as the Append method (still a lot quicker than using Strings though).

Usage

Add StringClass.cls to your project

   'In this example the buffer will be redimensioned 10 times.
   'If the same loop was done with a String then it would require
   '1000 redimensions (which is 50 times slower on my computer).

   Dim s As StringClass
   Dim MyString As String
   Dim l As Long

   MyString = space(1000)

   Set s = New StringClass
   s.BufferSize = 100000
   For l = 1 To 1000
      s.Append MyString
   Next
   Set s = Nothing

Downloads

StringClass.zip - contains: StringClass.cls (1 kb)

More...

Feb
25
2003

FTP Class

FTP Class based on the FileSystemObject using the Wininet Library

The FTP Class has been designed to mimmic the style of the FileSystemObject. There are two files (FTPClass.cls and FTPFileClass.cls). The Files and Folders properties in the FTPClass both return Collections of FTPFileClass objects.

This code has been revised (05 Sep 2003): Added the ability to connect using Passive FTP semantics.

What it can't do

  • Execute FTP commands

Usage

Add FTPClass.cls and FTPFileClass.cls to your project

   'This example opens a FTP connection, changes to a given folder and
   'downloads all the files contained in that folder to a local folder

   Dim ftp As FTPClass
   Dim f As FTPFileClass

   Set ftp = New FTPClass

   If ftp.OpenFTP("ftp.mydomain.com", "user", "pass") Then
      If ftp.SetCurrentFolder("MyFolder") Then
         For Each f In ftp.Files
            ftp.GetFile f.FileName, DownLoadFolder & "\" & f.FileName, True
         Next
      End If
      ftp.CloseFTP
   End If

   Set ftp = Nothing

Downloads

FTPClass.zip - contains: FTPClass.cls, FTPFileClass.cls (4 kb)

More...

Jul
2
2002
VB6 // Base64

Base64 Class

Base 64 Encoding/Decoding Class

After seeing the excellent Base64 code on VBspeed (see links below) and comparing it to my own I realised that there was a plenty of room for imporovement in my code. I've managed to speed up the Encoding by 3 times and the decoding by almost 4 times. It's not as fast as the VBspeed's fastest ones but at least it's in the ball park now.

The functions have also been changed. You can now encode either a Byte Array or a String to a String. Likewise a String can be decoded to either a Byte Array or a String. I've done away with reading and writing to files as I've found I've hardly used them.

This code has been revised (12 Jan 2004): Major speed imporvments, new function definitions (as noted above).

Usage

Add Base64Class.cls to your Project

   Dim b64 As Base64Class
   Dim EncodedText As String

   Set b64 = New Base64Class

   'To Encode
   EncodedText = b64.EncodeString("This is a test String.")

   'To Decode
   Debug.Print b64.DecodeToString(EncodedText)

   Set b64 = Nothing

Downloads

  base64.zip - contains: Base64.cls, rfc1521(Base64).txt (4.1 kb)

Links

VBSpeed: : Check out their Base64Dec and Base64Enc sections for some very fast Base64 functions.

The Complete RFC 1521 which includes the definition of Base64 Encoding.

More...

Jun
28
2002

Zip Class

PKZip compatible Zip files using the ZLib.dll

A big thanks to Jean-loup Gailly and Mark Adler for their ZLib compression/decompression Library (you'll need it if you want to use this code, download it from the links at the bottom of the page - best to copy the dll into your system directory). I've put it to good use with my classes for writing PKZip compatible files in Visual Basic. I'm not a big fan of in-line documentation (it just gets in the way) so I hope you can follow it. There's two classes (ZipClass and ZipFile). ZipFile should be a private class, it handles all the nasty stuff.

I intend to expand the code to read Zip files at some stage when I get the time but don't hold your breath.

What it can do

  • Write Zip files in a PKZip compatible format

What it can't do (yet?)

  • Span multiple disks
  • Read Zip Files

Usage

Add ZipClass.cls and ZipFile.cls to your project and ensure that zlib.dll is reachable

   Dim z As ZipClass

   Set z = New ZipClass

   z.AddFile "c:\test.doc"
   z.AddFile "c:\test.jpg"
   z.WriteZip "c:\test.zip", True

   Set z = Nothing

Downloads

  ZipClass.zip - contains: ZipClass.cls, ZipFile.cls, Appnote.txt, zlib.dll (45.3 kb)

Links

The ZLib home page where you'll find the ZLib.dll: www.zlib.org

The PKZip File Format: www.pkware.com

More...