Showing posts with label General. Show all posts
Showing posts with label General. Show all posts

Monday, 4 December 2017

Global variables

Having been an Access guru until 2004 and then not really doing anything with it since, it has been joyous recently to get drawn back into the world of Microsoft's desktop database. There have been a lot of changes since 2004 though, mostly for the best. Even the changes that are not so good (the demise of user-level security, for example) I can understand - Microsoft want to push developers who need user-level permissions towards other platforms, like SQL Server.

But I digress. Doing Access development again has been fun, and I found myself thinking about global variables on the way into work this morning. What are they, and where should you put them?

Well, a global (or environment) variable is a variable with global scope, meaning that it is visible and accessible throughout the program. And in Access, there are two places you can put them:

  1. Create a module called something like basGlobal and add the following:
  2. Option Explicit
    
    Public strMsg As String 'Adds a global string variable called strMsg, accessible everywhere because it's public
    Public Const lngSomeNumber As Long = 994 'Adds a numeric global constant called lngSomeNumber
  3. Create a table and store it there. Create a table called USysMetadata (and watch how prefixing a table with USys ["user-system"] hides it from default users) with two columns, MetaName and MetaValue. Store the name of the global variable in MetaName and the value in MetaValue.

Easy, right? But which approach to use, when? Especially when both have their advantages. The module approach is better for performance, especially if your database is deployed compiled (MDE or ACCDE). Retrieving variable values from USysMetadata might typically involve a DLookup("MetaValue", "USysMetadata", "MetaName='YourVariableNameHere'") or some SQL, neither or which is so fast. But on the flip side, if you need to add more global variables, well, you can't do that in a multi-user environment so easily for the basGlobal approach, since you need exclusive access to make design changes. By contrast, to add more using USysMetadata, just add a new row to the table. Couldn't be easier, and exclusive access is not required.

The other difference here is that USysMetadata allows variable values to be retained after you've logged out - basGlobal doesn't allow this.

So, some general rules (whilst noting that there are always exceptions to such rules):

  • For global constants (i.e. not variables) use basGlobal for performance.
  • For session variables (i.e. that don't need to be retained between log-ins) use basGlobal for performance.
  • For true system variables (i.e. that can be set and read by all users and/or that need to be retained across sessions) use USysMetadata for flexibility.

It's nice to be back, offering up my Access two penn'orth, even if no-one reads it.

Wednesday, 11 November 2015

Performance VIII - hasty hardware

The purpose of these performance posts is to suggest ways you can try to improve the performance of your Access applications. Some of the tips are just a brain-dump from the author, others have been collated from various Microsoft, FMS and other third-party sources.

Note that some of the tips contradict each other. This is because an optimization in one part of your application may cause a bottleneck in another part. For example, to make a form with subforms open and scroll faster, you may add indexes to each of the fields used to link the form with the subform. This will indeed make the form faster, but the added indexes will make operations like adding and deleting records slower.

Also, there is no such thing as perfect optimization advice. Some of the tips given here may make things run faster on your specific system, some may introduce new performance problems. The point is that optimization is not an exact science. You should evaluate each tip as it applies to your specific application running on your specific set-up. To help in this regard, each tip is rated ■, ■■ or ■■■, with ■■■ being the most advantageous in the author’s experience.

Make the most of the cache ■

Use cache memory wherever possible when using external SQL data sources. Access forms and reports have automatic caching mechanisms. When using recordsets in your code, try using the CacheStart, CacheEnd and FillCache methods to maximize cache effectiveness.

Access Help topic: FillCache method

Increase RAM ■■

Increase the amount of RAM on your computer. The minimum acceptable amount Access 2000 is 64MB, although 128MB is preferable and 256MB is better yet. The basic message here is: the more RAM, the better.

Avoid NTFS compression ■

If you are using NTFS compression, move your database to a non-compressed drive. NTFS adds a significant amount of overhead during disk operations, and Access applications are very disk-intensive.

Get a faster processor ■■

Okay, so it's stating the obvious but the faster your PC's processor the better. As little as 100MHz can give fair performance for 95/97; I'm currently running 2000 with 2.3GHz. Like RAM, the message here is: the more the merrier!

Keep enough local disk space free ■

Access requires a fair amount of disk space to operate, especially with large databases. Operations such as running large action queries, adding lots of data, importing data, and compiling and saving module code can use a lot of additional space on a temporary basis. Additionally, transactions, and compacting the database can use a lot of disk space. As a minimum, try to keep ten times the size of your largest database available in free local storage.

Optimize that disk ■

Keep your disk in clean and tidy by deleting surplus files and emptying your Recycle Bin. Look at Disk Defragmenter and Disk Cleanup within Windows, or investigate clean-up tools like the always excellent (and snappily titled) freeware Crap Cleaner.

Virtual Memory ■

Although the Windows default virtual memory settings are okay for most systems, you may want to consider changing the settings if you don't have a lot of space on the disk being used for virtual memory, or if you have a local drive that is faster than the one being used by default for virtual memory. Exercise caution and change in small increments though.

Strip your wallpaper ■

If your PC is really struggling, you may find the tiniest performance hike by removing desktop wallpaper, or switching to a small tiled bitmap.

Avoid disk compression software ■

Don't use disk compression software on the drive where you have installed Access, or where your database file(s) are located. Disk compression has a big negative impact on db performance.

Disable Office startup programs ■

I can't guarantee this applies to all versions, but in my experience Office installs one or more startup programs in your Start Menu Startup folder (e.g. Office Fast Start and Office Find Fast indexing utilities). Consider removing these, as they use memory. Find Fast runs continuously, so is especially damagaing to performance.

Don't journal ■

If you have Outlook installed (not Outlook Express), disable journalling unless it is absolutely essential to you - otherwise Outlook watches out for every time you open an Access database, and logs it, inevitably slowing things down. To disable this annoying function, select Tools, Options, Preferences, Journal options from the Outlook menu.

Don't spring too many leaks ■

I don't care what our friends at Redmond might say, almost all Windows applications "leak" memory. This is due to data structures, variables, and other memory consumers that are not correctly released by the application. By closing and reopening Access now and again, you allow Windows to reclaim any leaked memory.

Install Windows locally ■

Your OS should be installed on a local fixed drive on your computer. Because of the number of components involved in running Windows, a network installation causes relatively worse performance, especially for resource-hungry database app's.

Keep databases local too ■

Where possible, keep your databases on a local drive instead of on a network drive - 9 times out of 10, local disk access is faster than network access.

And install Access locally too ■

Most applications designed for PCs are faster when run from local drives than from a networked location, and Access is no exception.

Close other applications ■

Okay, it's an obvious one but you can free up memory by closing applications that you aren't using.

Review running Services ■

A whole host of services are running all the time in the background of your Windows OS - stop any you don't need (but set them to start automatically when needed) to free up system resources, but do so with caution and understanding - it's worth taking a look at this basic but comprehensive services guide before you change anything.

Monday, 2 November 2015

Performance I - amazing Access

The purpose of these performance posts is to suggest ways you can try to improve the performance of your Access applications. Some of the tips are just a brain-dump from the author, others have been collated from various Microsoft, FMS and other third-party sources.

Note that some of the tips contradict each other. This is because an optimization in one part of your application may cause a bottleneck in another part. For example, to make a form with subforms open and scroll faster, you may add indexes to each of the fields used to link the form with the subform. This will indeed make the form faster, but the added indexes will make operations like adding and deleting records slower.

Also, there is no such thing as perfect optimization advice. Some of the tips given here may make things run faster on your specific system, some may introduce new performance problems. The point is that optimization is not an exact science. You should evaluate each tip as it applies to your specific application running on your specific set-up. To help in this regard, each tip is rated ■, ■■ or ■■■, with ■■■ being the most advantageous in the author’s experience.

Don't AutoCorrect ■■■

In Tools, Options, General, uncheck "Track name AutoCorrect info". You'll find huge improvements in the time it takes your database to do virtually anything. Note that this function (which cascades changes you make to object names) can be useful in a development environment, but should be turned off in a production environment.

Access help topic: AutoCorrect options

Compact and repair ■■■

Compact and/or repair your database regularly (in Access 2000 and above, one action does both). Compacting your database reclaims unused space and makes nearly everything faster. Also, compact anytime you import/delete objects in your database, or compile and save VBA code. If you find this an onerous chore, investigate admin scheduling tools like the Handy Access Launcher. And don't forget to compact your MDW files sometimes too!

Access help topics: Compact, Repair

Analyze this! ■■

Access has its own performance analyzing capabilities (Tools, Analyze, Performance). Select All Objects Types, check Select All and hit OK - Access will recommend optimization techniques for anything and everything in your database, which might give you some ideas. Be wary of implementing too many indexes though - Access is forever recommending them and you might have good reasons not to put too many in.

Access Help topic: Performance Analyzer

Power up the Jet engine ■■

There are many Registry settings you can play with to optimize the Jet database engine, including these:

  • Threads: the number of operating system threads available to the Jet database engine.
  • MaxBufferSize: the data buffer used by Jet.
  • UserCommitSync: tunes the performance of explicit transactions.
  • ImplicitCommitSync: tunes the performance of implicit transactions.
  • FlushTransactionTimeout: tunes the performance of asynchronous write operations.
  • ExclusiveAsyncDelay: tunes the performance of asynchronous mode writes to exclusively opened databases.
  • SharedAsyncDelay: tunes the performance of asynchronous mode writes to databases opened for shared access.
  • PageTimeout: the delay for checking other user's changes to the database.
  • LockDelay: how long Jet waits between retries on locked pages in a shared database.
  • MaxLocksPerFile: the maximum number of locks can be placed on a database.
  • RecycleLVs: determines how memo, OLE and hyperlink data pages are recycled.

Now I don't pretend to know the best settings for all of these, and if you're unsure you're advised to leave the defaults alone (this is good advice for any changes you might ever make to any part of the Registry). But if you do want to experiment, these keys can be found in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Jet 4.0 (for Jet 4) and can be edited either with RegEdit or, if you're familiar with good old DAO, the DAO SetOption command in VBA (or SaveSetting in later versions of Access). Don't forget to back-up the Registry before you start experimenting.

Access Help topics: Registry, SetOption method, SaveSetting method

Do the splits! ■■■

You can improve performance (and simplify maintenance) by splitting your database in two. The "application" front-end (FE) of your database holds all objects except tables, and is linked to the "data" back-end (BE) that contains the actual tables. This can give particular gains in a multi-user, networked environment, as the FE can be installed on each user's workstation with only the BE on a server. Later versions of Access even have a wizard to help you make this split (Tools, Database Utilities, Database Splitter).

Access Help topic: Splitting an Access database

Keep your Options open! ■■

Avoid lock conflicts by experimenting with the Refresh Interval, Update Retry Interval, Number of Update Retries and ODBC Refresh Interval Settings - you'll find these in Tools, Options.

Be Exclusive ■

If you are opening a database that no other users need to use, open it in Exclusive mode. To do this, check the Exclusive checkbox in the Open Database dialog.

Friday, 30 October 2015

Polls

In case these past polls are of interest to somebody, somewhere, here are four survey's worth of results...

Standards

Why should you bother with standards? Maybe a couple of illsutrations are in order: consider a finance database that has a table called "Account", a query called "Accounts", a form called called "Account" and a report called "Accounts". Pretty confusing already, isn't it? Now try referring to these items in code, and you'll see what a nightmare naming can be. Alternatively, think of a form you've created without changing any of the control names - in six months time are you going to be able to easily tell TextBox8 from TextBox9, or ComboBox13 from ComboBox31?

Wouldn't it be a whole lot easier to adopt a naming convention that enables you to know what something is just from its name? Well, there are numerous naming conventions out there, the most popular of which, from an Access perspective at least, is the Leszynski/Reddick VBA naming conventions, a copy of which can be found in Word format here. You'll find the code samples on this site loosely conform to these standards. Like many developers, I use the subset of these standards that works for me, and I expect you'll do the same.

Anyway, regardless of whether you buy into the Leszynski/Reddick conventions or define your own, here are some general pointers on standards:

  • even if you define your own, use some sort of standard and stick to it - you'll thank me for this later. It's more important to work to a standard - any standard - than to adhere slavishly to a particular standard.
  • document your conventions so that others may follow your work. If you use an existing convention, reference it in your application's documentation.
  • don't use spaces in object names - concatenate words instead, and use capitalisation to make things clear (e.g. use "CustomerDetails" instead of "Customer details"). apply your convention as you go along - backtracking over your database to rename all objects is no fun, and mistakes are easily made, even with third-party "search-and-replace" tools.

Wednesday, 14 October 2015

Deploying user-specific desktop shortcuts

So you've got a networked database and you need an easy way of deploying customised desktop shortcuts for it to your users. Here's a cunning method.

The basis for this method is the use of Visual Basic scripting in the form of a VBS file - saves you having to build a setup.exe file or anything strenuous like that. Now VBS files have had something of a bad press, mainly because script-kiddies have used them to write viruses. Don't let that put you off.

Anyway, create a file in the text-editor of your choice and name it something intelligent like install_production.vbs - note the extension. Now the script shown below does the following:

  1. Prompts the user to confirm their database username - since I use the user's Windows username for their database username, this is shown as the default response. If you're not using user-level security you can skip this step.
  2. Creates and names the shortcut, checking the Registry to look-up the location of the user's version of Access (you can hard-code the Access executable's location if you'd prefer)
  3. Sets the "run in" directory
  4. Sets the shortcut icon
  5. Sets the shortcut's window style

In the example that follows:

  • MyApp is the name of the database application
  • \\srvr\share\fldr\myapp.mdb is the location of the database file
  • \\srvr\share\fldr\system.mdw is the location of the workgroup information file
  • \\srvr\share\fldr\myapp.ico is the location of the application icon file

Okay, here's the script:

Set WshNetwork = WScript.CreateObject("WScript.Network")
Dim strI
strI = InputBox("Enter your MyApp database username here. If a default has been suggested, please " & _
    "check it before you proceed, amending as required." & Chr(10) & Chr(13) & Chr(10) & Chr(13) & _
    "NOTE: leaving this blank cancels the installation!", "Shortcut personalisation", WshNetwork.Username)
If Len(strI)>0 Then
    Dim WSHShell
    Set WSHShell = WScript.CreateObject("WScript.Shell")
    Dim MyShortcut, DesktopPath, AccessPath
    DesktopPath = WSHShell.SpecialFolders("Desktop")
    Set MyShortcut = WSHShell.CreateShortcut(DesktopPath & "\MyApp - production.lnk")
    AccessPath = WSHShell.RegRead("HKCR\.mdb\")
    AccessPath = WSHShell.RegRead("HKCR\" & AccessPath & "\shell\new\command\")
    AccessPath = Replace(Left(AccessPath, InStr(1, AccessPath,"/", 1) -1), """", "")
    MyShortcut.TargetPath = AccessPath
    MyShortcut.Arguments = "\\srvr\share\fldr\myapp.mdb /wrkgrp \\srvr\share\fldr\system.mdw /user " & strI
    MyShortcut.WorkingDirectory = "C:\Program Files\Microsoft Office\Office\"
    MyShortcut.WindowStyle = 3 '1=normal, 2=minimised, 3=maximised
    MyShortcut.IconLocation = "\\srvr\share\fldr\myapp.ico"
    MyShortcut.Save
    Msgbox "Installation completed successfully.", 64, "MyApp"
Else
    Msgbox "Installation was cancelled.", 48, "MyApp"
End If

Note that your users may get prompted to confirm that they want to run a VBS file, depending on their PC/environment security settings. Like I said before, this is a security measure to help prevent the feeble-minded exploiting the power of Visual Basic scripting to be malicious.

Tuesday, 13 October 2015

An easy backup routine

It's always wise to make regular copies of all your database files. Whilst there are numerous tools that will do this for you, some of these are expensive, whilst others are overly complex.

If you have a fairly simple backup requirement, i.e. you just want to archive all the files in the database's directory on a regular basis, you might want to consider using a file zipping program, with a command-line interface. This lets you easily zip up all the relevant files with one command, whilst the command itself can be scheduled to run using Windows Task Scheduler or even the Handy Access Launcher.

Using this principal, I like to use WinZip to do my backups for me - the command-line interface is a freely downloadable add-on. Using the WinZip command-line interface takes the following form:

[WinZip command-line zipping executable] [Destination ZIP file] [Files to be zipped] [-switches]

For example:

"c:\program files\winzip\wzzip.exe" "g:\mdb\backup\cd.zip" "f:\mdb\cd\*.*" -ex -P -r -u

There are numerous available switches, described in full in the command-line help file that comes with the add-on. The switches shown in the above example (the only ones I feel it is necessary to use) have the following effects:

  • -ex - sets compression to maximum;
  • -P - causes all folder information specified in the command-line to be stored;
  • -r - recurse into folders (include subfolders). This option requires the -p or -P option;
  • -u - only add files that are new or have changed since the last zip file creation.

A series of these command-line statements can then be written in a single batch file. In this way, I backup seven production databases, and all associated files (e.g. workgroup information files, help files, icon files, splash-screen bitmaps, etc) in a single batch job which is scheduled to run twice a day. In other words, I get regular incremental backups without having to do anything!

I should probably point out a few of the drawbacks of this approach. If a file is in use when the backup runs, WinZip warns you that the zipped version may become corrupted. I haven't had any such problems but if WinZip feels such a warning is appropriate, then it must be possible. Secondly, this method only provides you with incremental backup, i.e. each backup overwrites the previous one. If this is inappropriate for your needs, consider something else. If you just want quick and easy regular backups of your production databases though, this may be for you.

Finally, if you've got a good reason for not using WinZip, you might want to look into 7-Zip which is entirely free (WinZip is shareware), has a superior compression ratio and a command-line interface. Indeed, if anyone does use 7-Zip to perform a backup in the manner described on this page please use the comments below to share the details.

Monday, 12 October 2015

Creating a splash screen

Okay, so you've created you database application in Access but you don't really want everyone to see that annoying Microsoft splash screen every time you start up, right? Fortunately the solution is unfeasibly simple.

Let's say the filename of your database is my1stdb.mdb - create the image you want to use for a splash screen and save it as a bitmap with the same filename (i.e. my1stdb.bmp) in the same directory as the database. Lo and behold, next time you start the database up (assuming you open it directly from Explorer or a shortcut, rather than opening Access first and then opening your database from within it) your bitmap will be displayed instead of the usual homage to Bill Gates. Neat, but be warned - the bigger and more colourful the bitmap (and hence its file size) the more this will slow your database's start-up.

Okay, but what if you want to get rid of the splash screen altogether? Well (and I haven't checked this bit for versions higher than 97) you can't - but you can do the next best thing. Create a bitmap of size 1 pixel by 1 pixel - reduce the number of colours to 2, to minimize the size (so it loads as fast as possible) and name it as described above. This then pops up on the user's screen, but as a monochrome single pixel, who'll notice? This also has the advantage of keeping the database's start-up speedy, as a monochrome single pixel bitmap is only 66 bytes.

Friday, 9 October 2015

About Access Relic

Morning all. I used to develop database applications using Access. I got pretty good at it too, to the extent that at one point I was in discussions about writing a textbook on the subject. I also used to maintain a website full of handy hints, tips and pointers for Access developers of all skill levels. I also offered plenty of code samples, some add-ins and freeware, and sample databases. It was a popular site, once upon a time.

Jobs change, and I don't get to do much with Access any more, I'm sorry to say. And the host I used for the old website pulled their free hosting, so that's gone too. I've still got all the old content though, so my plan is to release it gradually on here and ensure that it's still "out there" and available to anyone who might find it useful. Some of the content might be a bit dated (I doubt many of you remember Access 1.1 and 2) but I'll put the whole lot up, eventually, and let you decide for yourself.

The old website used to be called Accessory, but in starting this new blog it's time to acknowledge what I am now ... an Access Relic.

The small print, about you

The purpose of Access Relic is to share knowledge with other developers. However, to preserve the integrity of this site's content, and to follow common developer courtesy, the following conditions for use of code on this site must be observed:

  • You may use any code here in any application you develop, provided a reference to this site is included in source code and associated documentation.
  • You may not copy, redistribute or republish any source code code from this site in any form, including redistributing the code on the web, in zip files, or on CD collections. If you want to use something you find here please link users to the corresponding page(s) of this site.
  • In other words, anything that lets you capitalise on my generous nature is just not on.

The other small print, covering me

The author of this site expressly disclaims any warranty for the code contained herein. The code and any related documentation is provided "as is" without warranty of any kind, either express or implied, including, without limitation, the implied warranties or merchantability, fitness for a particular purpose, or non-infringement. The entire risk arising out of use or performance of the code remains with you. Furthermore, in no event shall the author of this site be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or any other pecuniary loss) arising out of the use of or inability to use this code, even if the author of this site has been advised of the possibility of such damages. Because some jurisdictions do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation may not apply to you.