Category Archives: VB Feng Shui

Best Programming Font

19
Filed under Font, Fonts, VB Feng Shui
Tagged as

NOTE: I originally did this post back in 2007. I’ve updated it a few times since then with new fonts. I added Lucida Sans Typewriter at the request of a comment by Row Sham Bow. Also new is Inconsolata, DroidSansMono, Liberation Mono, and Monofur.
And for 2012, at the suggestion of Chris Nicholls, Borte.fon is also new.
Thanks to everyone who’s pointed me to new fonts to try!

I’ve tried out the newer fonts for varying lengths of time, but, at least so far, I still end up back with Consolas.

But if you have a favorite font you’d like mentioned, please let me know!

I’ve noticed something a bit peculiar about fonts and programmers.

There’s the camp that’s thoroughly researched the topic, experimented with piles of fonts and ended up selecting one that they can be quite vocal about.

And then there’s the camp there never changes the default that came setup in the IDE they installed.

I guess I come from the former. Courier? No way. Arial? Ack! Programming in a variable width font just seems, so, ewww. I was a good, old fashioned FixedSys man for ages. It was decent, had a nice fixed width, slightly too bold, but I could live with it, came with every copy of windows and was pretty legible across all the common characters. But about a year ago, I embarked on a quest to find a better font.

Many, many downloads later, I believe I’ve ended up with the best of the options out there. The freely available ones, anyway.

I’ve taken screen snapshots of all fonts at approximately 14pt size. I used 14pt because it’s the most comfortable size for me.

I’ve also included a snapshots of the better fonts at different sizes, so you can get a feel for how they scale.

Bitmap fonts

I’m not a big fan of the bitmap fonts (the FON files). They don’t scale well except where they’ve been defined at multiple sizes (not really scaling), and don’t believe they take advantage of ClearType, certainly not very well. Still, there are some interesting bitmap fonts out there.

Most of the good ones are intended to be used as very small fonts. If you have eagle vision, some of them might work quite well. But my eyes would jump screaming from my their sockets if I tried to program in some of these all day.

image 10×20-iso8859-1.fon Not bad but it doesn’t scale. Some elements bleed too much.
image 9×15-iso8859-1.fon Too thin for me
image 9×18-iso8859-1.fon Also too thin
image BSUKermit.FON Base size is too small. Doesn’t scale
image Borte.FON A bit small and thin for me, but otherwise looks very clear. Doesn’t scale
image Dina.fon Base size is too small. Doesn’t scale
image DOSLIKE.FON Not bad, but it doesn’t scale. Has a few too many serifs for my taste.
image GwdTE_437.fon Base size is too small. Doesn’t scale
image Hackd.ttf My own custom version of Hack, ligatures, slashed zero, nice percent, Powerline glyphs
image Hyperlt.fon Actually called HyperFont LT
image IBMPC.fon 10pt. Yikes. Quite small.
image IBMPC.fon 14pt. This is what happens when bad fonts scale.
image PROFONT.FON 12pt. Too small, and the letters bleed together at this size.
image PROFONT.FON 14pt. Way too thick at this size, plus kerning is wacked.
image Raize.fon 10pt. Not too bad, but too small for me.
image Raize.fon 14pt. There’s just something about the letter shapes at this size that don’t feel right.
image_thumb2[1] Sysmono.fon As close to 14pt as I can get with this font.

True Type Fonts

I prefer the true type fonts. They scale well all the way down to about 7 points, but they can take advantage of ClearType, and a few are even specially designed to make optimal use of it.

image_thumb5 Arial.ttf 14pt. Just for reference, a variable width font just doesn’t work for me and programming.
image_thumb3[1] Aerial Mono.ttf 14pt. Pretty good. Seems a bit too bold.
image_thumb4[1] Andale Mono.ttf 14pt. Quite good. This one was in the running for a while.
image_thumb5[1] AnonymousRegular.ttf 14pt. Yikes, serifs and programming just don’t mix.
image_thumb6 AnonymousRegular.ttf 11pt. Smaller size, same serif problems. I do like the zero, however.
image_thumb7 Bitstream Vera Sans Mono.ttf 14pt. Excellent font. Maybe just a tad too bold, but this one was also in the running.
image_thumb1[1] Consolas.ttf 14pt. Excellent all around.
image_thumb4 Consolas.ttf 10pt. For reference. Scales well.
DroidSansMono.ttf 12pt. Very good font. Google makes it available free here. Only downside is the zero is not slashed.
image_thumb8 Everson Mono Unicode.ttf 14pt. Very good, but the letters seem to be a bit thinner than numbers and symbols, which looks odd to me.
image_thumb1 Fixedsys.ttf 14pt, note this is the TTF version of the FixedSys font, not the bitmapped version. It’s too heavy for me.
image_thumb9 HyperFont.ttf 14pt. Not bad but similar problems to Everson Mono.
Inconsolata.ttf 12pt. A nice font but I don’t really care much for what anti-aliasing does to it. It seems fuzzier than necessary and some letters end up with a nib below them, which I don’t care for.
image_thumb10 Larabiefont Bold.ttf 14pt. Wow. Those zeros. oh, wow. Screams l33t!
image Letter Gothic Line.ttf 14pt. This one’s not too bad, but check out the lower case m’s. Funky.
LiberationMono.ttf 12pt. A very good font. Available here. Very much a contender for a top spot, but it uses a dotted zero instead of a slash.
Lucida Sans Typewriter 12pt. Not bad, though it seems a little thin to stare at all day.
image Monaco.ttf 14pt. Excellent font. Originally from the Mac. the parens are a little odd, but this was definitely in the running.
Monofur.ttf 12pt. Good but a little odd to program in all day long. The dotted ‘zero’ doesn’t feel right to me, but I do like the symbols.
image PixelCarnageMonoTT.ttf 14pt. Hmm, seems small for 14pt. Decent, but not right for me.
image ProFontWindows.ttf 14pt. The “u”, “n” and “c” threw me. This is just a little too “programming in the FUTURE.. FUTURE.. FUTURE.. FUTURE”.
image ProggyCleanTT.ttf Intended to be used small. Ouch, my eyes!
image Reader Sans Roman.ttf 14pt. Funky horizontals.
image_thumb2 Terminal.ttf 12pt. Decent, available, a bit thick in general.
image_thumb3 Terminal.ttf 8pt. Fine if you don’t mind going blind at 30.
image Ti92Pluspc.ttf 14pt. Not bad but a little tall for my taste. Any shorter, though, and it gets too thin.
image Topaz-8.ttf 14pt. Ugh. Someone actually recommends this?

Finding the Fonts

I found all these fonts through various sites. Googling the font file name should get you where you want to be. I’m not sure as to posting the fonts for download here, so I’m erring on the side of safety. I apologize in advance for making you hunt them down.

The Winner

I chose Consolas in the end, for several reasons:

  • It comes with the newer Windows and it’s a VERY high quality font.
  • The symbols aren’t weird, and most of them, plus the parentheses, kind of ‘pop’, which I happen to like.
  • It’s got a good slashed zero
  • Line spacing is nice. Not too tight or loose.
  • It’s thick enough to avoid strange looking “thin spots” but not so thick as to be annoying or have characters bleed (like Terminal)
  • No pseudo-serifs (like Anonymous)

I’m sure there’s a lot more possibilities out there, but I didn’t see them before I quit looking.

If you have a favorite font, let me know. If I can download it, and it’s a serious programmer font, I’ll add a sample.

If you tell me you program in Comic Sans, somewhere, out there, a daemon will abend.

Gaining Access to a Running Instance of Windows Media Player In VB.net

14
Filed under Code Garage, VB Feng Shui, WindowsMediaPlayer

Over the past few weeks, I’ve been working on a little screensaver side project to run in an old radio cabinet that I’ve converted into a touchscreen jukebox. Details of that project will be coming, but for now, I thought I’d share some interesting software bits I’ve discovered.

The screensaver that I’ve working on is intended to:

1) Recognize a Media Player that’s running on the computer when the screensaver loads up.

2) Connect to and monitor that media player for any changes in what’s it playing. Particularly, I want to know Artist name, album name and track name.

3) Hit a few search engines for some images related to what’s playing and display them in a nice “Ken Burns Pan and Zoom” style animation.

Well, long story short, WPF made short work of the image animations, and connecting to two of my favorite media players, J River Media Center and Album Player, was pretty trivial.

But, within just a few days of posting the first version, someone asked if it worked, or could work, with Windows Media Player (and, as it turns out, Windows Media Center, which is just a nicer shell over WMP).

Why Not?

My first thought was, sure! All I have to do it be able to see what’s currently playing and when it changes. Shouldn’t be too tough, right?

Well, after quite of bit of digging, it turns out that Windows Media Player (WMP), is far more gracious about hosting “plugins” that it is about being remotely attached to. There are several plugins available for WMP that write out info on the current playing media to an XML file, or the registry, or a web service, or whatever. But that requires "my application’s user” to install some other application to make things work. Not cool. At least, not for me.

Plan two. Most MS Office apps register themselves with the Running Object Table (The ROT). Other programs can query the ROT and retrieve objects from it that they’re interested in connected to. You often see the VB GetObject() function used for this purpose.

But WMP doesn’t register itself with the ROT, so that’s not an option.

On to Plan C.

WMP Remoting

However, as luck would have it, MS did do something about this type of situation. They call it “Media Player Remoting”. However, it’s just about the least documented concept I’ve come across yet. There’s just very little info about exactly how to set up this “remoting” or what it’s capable of.

Eventually,though, I did come across mention of a demo project written by Jonathan Dibble, of Microsoft no less, that illustrates the technique in C#. There’s a thread here that contains links to the original code, though that page appears to be in Japanese.

Looking further, I found several variations of Dibble’s project, some vastly more involved and complex than others.

I grabbed the simpler version and started hacking!

The Conversion

Converting Mr. Dibble’s code was fairly straightforward. He did a pretty fair job in commenting it and breaking things down nicely. As usual, one of my favorite Web Resources, DeveloperFusion’s CodeConverter, got a workout, and did a fine job on most of the conversion gruntwork.

But when the dust cleared, it didn’t work.

After a lot of stepping with the debugger, it turns out that Jonathan’s handling of  IOleClientSite.GetContainer isn’t quite right. His original code threw a “Not implemented” exception that would cause a crash for me every single time.

The function itself isn’t particularly useful for what I needed to do, and after reading up on the documentation, I felt certain that there’s really wasn’t anything that “needed” to be done in that function. But, it did get called by WMP, and something other than throwing an exception had to be done there.

Then, I realized that a number of other OLE-centric functions that Jonathan had implemented had a return value of HRESULT, and simply returned a E_NOTIMPL value.

So, I changed up the definition of GetContainer and had it returning an E_NOTIMPL, and presto! It works!

Since Jonathan’s demo project appears to be at least 4 years old, I’m not sure whether I may have indeed worked that way at one point, or was a bug, or, quite possibly, was something I didn’t get quite right in the conversion in the first place. Regardless, this version works, so bob’s your uncle.

How to Use It

For anyone not interested in the details, I’ll dive right in to how you actually use this technique.

First off, you’ll need to add a reference to WMP.DLL. This file should be in your Windows\system32 folder if a Windows Media Player is installed. Once added, you’ll have a WMPLib reference in your References tab:

image

Next, copy the WMPRemote.vb file into your own project.

Finally, though this isn’t strictly necessary, you may want to alter your project’s AssemblyInfo.vb file and set the CLSAttribute to false.

....
<Assembly: AssemblyCopyright("blah")> 
<Assembly: AssemblyTrademark("blah")> 
'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'THE BELOW LINE YOU MIGHT ADD OR CHANGE TO "FALSE"
<Assembly: CLSCompliant(False)> 

'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("12333333-33454-1233-1234-123451234512")> 
.....

The main class to work with is WMPRemote. It has two static properties; IsWindowMediaPlayerLoaded, and ActivePlayer.

These are static properties, so you access them using the WMPRemote class, like so:

If WMPRemote.IsWindowsMediaPlayerLoaded Then
   Dim Player = WMPRemote.ActivePlayer
End If

At that point, if WMP is loaded, you’ll have a reference to the full WMPlib.WindowsMediaPlayer object in the Player variable.

From there, you can do whatever you need to.

Query properties:

Debug.print Player.playState 

Attach to events:

AddHandler Player.CurrentItemChange, AddressOf CurrentItemChange
AddHandler Player.PlayStateChange, AddressOf PlayStateChange

Or whatever else is necessary.

How It Works

WMPRemote

Since this class is the main access point, I’ll start here. There are only 2 static functions defined here:

IsWindowsMediaPlayerLoaded

This function simply uses the .net Processes object to query for any processes named WMPlayer. If there are any, it returns TRUE, if not, FALSE. Obviously, it could be wrong, but that’s not terribly likely.

ActivePlayer

If things have already been initialized, this function just returns whatever it’s already retrieved for the Active WindowsMediaPlayer object.

If not, it checks if WMP appears to be loaded and, if so, creates and shows an instance of the internal frmWMPRemote form. During the load of this form, it’s immediately hidden so the user will never see it.

The only purpose of frmWMPRemote, is to host the WindowsMediaPlayer ActiveX Control. This all happens during the form Load event:

Me.Opacity = 0
Me.ShowInTaskbar = False
_InternalPlayer = New WMPRemoteAx
_InternalPlayer.Dock = System.Windows.Forms.DockStyle.Fill
Me.Controls.Add(_InternalPlayer)
Me.Hide()

Note that it actually is creating an instance of the WMPRemoteAx control, and then siting it on the form.

WMPRemoteAx

This class is based on the AxHost control, and is what allows an ActiveX COM-based control to exist on a .net WinForms form.

Once created as actually sited on a control (or WinForms Form, in this case), the AttachInterfaces method is called by the .net runtime to connect this host up with whatever COM ActiveX Control it will be hosting. I’ve told this control to host the WindowsMediaPlayer ActiveX control by setting the GUID in the constructor:

MyBase.New("6bf52a52-394a-11d3-b153-00c04f79faa6")

AttachInterfaces connects up the ActiveX control with a clientsite as necessary, but more importantly, it exposes the internal OCX instance by casting it as an instance of WindowsMediaPlayer:

Dim oleObject As IOleObject = TryCast(Me.GetOcx(), IOleObject)

Dim a = TryCast(Me, IOleClientSite)
oleObject.SetClientSite(a)

_RemotePlayer = DirectCast(Me.GetOcx(), WMPLib.WindowsMediaPlayer)

At this point, COM calls several other interfaces that have been implemented by WMPRemoteAx, including:

  • IOleServiceProvider
  • IOleClientSite

    Most of the methods on these interfaces need not actually do anything. They are required for more sophisticated integrations. However, IOleServiceProvider_QueryService does have a very specific purpose.

    Remoting

    Remember that this entire situation is made possible by something WMP calls “Remoting”. Turns out, this callback method is how our control communicates to WMP that we are, in fact, setting up a remoting situation.

    If riid = New Guid("cbb92747-741f-44fe-ab5b-f1a48f3b2a59") Then
        Dim iwmp As IWMPRemoteMediaServices = New RemoteHostInfo()
        Return Marshal.GetComInterfaceForObject(iwmp, GetType(IWMPRemoteMediaServices))
    End If

    When WMP calls this function with the given riid as above, our control has to respond by returning an object of type IWMPRemoteMediaServices (in this case implemented by the RemoteHostInfo object in the project).  That object has a few properties that WMP queries for some basic information, but really, the fact that our control (WMPRemoteAx) has responded by returning an IWMPRemoteMediaServices is the main thing that sets up the remoting connection.

    The OLE Interfaces and Enums

    The rest of WMPRemote.vb is made up of several COM Enums and interfaces that are necessary to bring all this together, but that aren’t readily defined in VB.net. None of that code should normally be altered in any way because it’s actually defining interfaces and values that have already been defined in COM, but that we need defined for use in a .net application. For instance:

    <ComImport(), ComVisible(True), Guid("00000118-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
    Public Interface IOleClientSite

    This is the start of the definition of the IOleClientSite interface.  That interface is a “well defined” interface with a specific GUID (the value of the GUID attribute), and a specific interface type. Changing our .net definition of that interface would likely break everything.

    Where’s the code?

    Right here. This particular version is in VS2010 with .net 4.0 framework, but I don’t imagine there’d be any problems converting back to VS2008, or possibly even VS2005. I suspect you will need at least .net framework 2.0 though, but I haven’t tested this.

    Also, check out a few of my other projects in the Code Garage.

    And finally, let me know what you think!

  • Visual Basic 11 beta is out

    3
    Filed under .NET, Rants, VB Feng Shui

    vs2010_iconlibrary

    OK, It’s been a few weeks, so this is likely not “new” news, but still.

    Looks like MS isn’t backing off on VB one bit, and that’s a good thing. Heck, as I understand it, there’s even a project in skunkworks build VB in VB! I’ve always said the mark of a complete language is when it’s actually written in itself.

    But I digress. Back to VB 11. The VB Team website has a nice rundown of some of the high points of the release here.

     

     

     

     

    To summarize:

    1. Async support. Meh. VB (actually any .net language) has always had this. The Async stuff definitely makes it easier, so I won’t complain too much. Personally, I’ve kind of gotten into the Javascript notion of lambdas for callbacks in support of async stuff. You can do that in VB, but lambda’s, being limited to single lines) haven’t been all that useful for it, up till now with….
    2. Multi-line Lambdas. That’s right, you can finally declare a Function()….. lambda that spans multiple lines.
    3. Iterators. Which basically means a Yield keyword that can fall out of an iteration loop to allow the iterating code to perform it’s work.
    4. Caller info. This is a big one for me. I’ve written more than my share of error logging/trapping/handling frameworks over the years, starting with VB3, on through VB6 and then into .net. Unfortunately, this feature has nothing to do with that!
      Caller info allows a function to easily and straightforwardly retrieve the Name, Line number or FilePath, of the calling function. While the Line number and Calling path are of dubious value, the caller name is incredibly powerful for things like front ending field accessors in data access libraries. Say you have a small function that retrieves a value from a VB, via a name. With this feature, you can easily create properties of an object that are named that name and then pass the property name down to the accessor function to retrieve the value.
      This has been doable for ever in .net as well (via the call stack), but was not straightforward and was susceptible to corruption if you used code obfuscators. No word on whether this feature will play better with obfuscators at this point, though.
    5. Call View Hierarchy. Looks like a very nice feature, but I’ll have to play with it more before making any concrete observations.
    6. Global Namespace. Another meh. On some projects, I could see this being handy. But it’s nothing to get too excited over. A very incremental improvement.

     

    What’s missing

    1. Unsafe code. At least, I’ve seen no mention of it.
    2. Property-level scope. They added auto properties in VB10. Property-level scope seems like the next natural step for that. And by this, I mean:
      Public Property Name() as string
           Private _Name as string      <—– Property level scope
           Get()
                  Etc
            End Get()
            Set ()
                  Etc
            End Set
      End property

      EDIT: The suggestion that I posted to MS’s suggestion board ended up getting a comment from Lucian Wischik. You can read his full comments here.
      Property Scope Variables
    3. More Dynamic functionality, though you could argue that you can actually do quite a lot of dynamic stuff now in .net languages.

    It’s good to see the language getting very close to parity with C#, and the news of a forthcoming VB.net coded compiler is even more exciting.

    Helpful Enum Description Attribute

    2
    Filed under .NET, VB Feng Shui

    imageWhen you work with Enums, often, it’s nice to have a description to go along with the value. Of course, you can use reflection to retrieve the name of the enum, and that’s sufficient for many purposes. But sometimes, using the name ends up being awkward, or just won’t work.

    For those times, I created an EnumDisplayName Attribute.

    First, the attribute definition:

    <AttributeUsage(AttributeTargets.Field)> _
    Public Class EnumDisplayNameAttribute
        Inherits Attribute
    
        Public Property DisplayName As String
    
        Public Sub New(ByVal DisplayName As String)
            Me.DisplayName = DisplayName
        End Sub
    End Class

    Using it would then look something like this:

    Public Class Core
        Public Enum ChimeSoundsEnum
            <EnumDisplayName("None")> _
            None = 0
            <EnumDisplayName("Air Raid")> _
            AirRaid = 1
            <EnumDisplayName("Beeper")> _
            Beeper = 2

    Now, all you need is an extension method on Enum to read the DisplayName for a particular enum value:

    Imports System.Runtime.CompilerServices
    
        <Extension()> _
        Public Function DisplayName(ByVal e As [Enum]) As String
            Dim enumType = e.GetType
            If enumType.IsEnum Then
                Dim f = enumType.GetField(e.ToString())
                Dim displayNameAttribute = DirectCast(f.GetCustomAttributes(GetType(EnumDisplayNameAttribute), False).FirstOrDefault(), EnumDisplayNameAttribute)
    
                If displayNameAttribute IsNot Nothing Then
                    Return displayNameAttribute.DisplayName
                End If
            End If
            Return [Enum].GetName(enumType, e)
        End Function

    And finally, to read all the DisplayNames for a particular Enum type:

        Public Function GetEnumDisplayNames(ByVal et As Type) As String()
            If et.IsEnum Then
                Dim l = New List(Of String)
                Dim flds = From f In et.GetFields Where f.IsLiteral = True
                For Each f In flds
                    Dim desc = DirectCast(f.GetValue(f), [Enum]).DisplayName()
                    If Desc IsNot Nothing Then
                        l.Add(desc)
                    End If
                Next
                Return l.ToArray
            Else
                Return Nothing
            End If
        End Function

    Using that last function, you get back an array of DisplayNames that you can then databind to (for, say the ItemSource of a ListBox).

    And finally, using these same techniques, you can create any number of other Enum metadata elements to make enums much more useful and easier to work with. You could have a ShortName attribute, a DataColumn attribute, maybe a PermissionLevel attribute, etc.

    A Reasonable Approach to Exceptions

    0
    Filed under Error Handling, VB Feng Shui

    A comment thread on LinkedIn today ended up pointing me to an article by Eric Lippert about Vexing Exceptions.

    The article is a little old (around 2008), but I found it to be one of the best-reasoned articles on exception handling I’ve seen.

    In it, he basically categorizes exceptions into 4 types:

    • Fatal – You can’t predict and can’t do anything about it
    • Boneheaded – Results from a bug in your code
    • Vexing – Results from a bad design (like Integer.Parse)
    • Exogenous – Results from outside factors, but can be handled by your code.

    Fatal and boneheaded exceptions you can’t do anything about (at least not initially). The best defense against them is a good logging framework that allows for multiple logging levels, like off, normal, and debug  for instance.

    Vexing Exceptions are those that result from a poor API design. The example Eric gives is the Integer.Parse function. It will throw an exception when the parsed text doesn’t result in an integer, but that’s the whole point of parsing the text in the first place! With vexing exceptions, I usually try to find an alternate implementation that simply doesn’t generate the exception. When that’s not possible, you wrap the block in a Try and just eat the exception. It’s the only other choice you have.

    Exogenous exceptions are probably the most typical exceptions you’ll handle in normal code. These are exceptions that you can generally deal with when they occur, but you can’t write code such that they won’t occur, because they are caused by factors outside your code. The typical example is a File Not Found error. Your code can usually easily recover from this type of error, but there’s simply no way to code around it such that you can guarantee it won’t happen.

    Which actually leads me to an additional conclusion Eric touched on.

    Pre-coding Exceptions (or Why you shouldn’t)

    Often, I’ll see (and have certainly written more than once) code such as:

    if not FileExists(MyFile) then
    
       Msgbox “The File Doesn’t exist”
    
    else
    
       OpenFile MyFile
    
       Read/Write/Whatever
    
       Close MyFile
    
    End If

    This is an example of an exogenous error that I’m trying to “Code around”, using the FileExist function to detect whether the file is there before trying to open it.

    Unfortunately, because there’s no way to predict when the file in question might be deleted, you can still get a file not found error at the OpenFile line, because other code may have deleted the file between the execution of the FileExists test and the OpenFile command itself.

    Because of this, it’s often just a waste of time and code to put the FileExists test in, since to be truly covered, you also have to trap for the FileNotFound exception.

    And since most exogenous exceptions fall into this pattern, I generally don’t try to code around them anymore. Rather, I just put the appropriate Try Catch blocks in place and deal with those exceptions that way.

    Try
    
       OpenFile MyFile
    
       Read/Write/Whatever
    
       Close MyFile
    
    Catch Ex as FileNotFoundException
    
       Msgbox “The File wasn’t found”
    
    Catch Ex2 as Exception
    
       ‘Handle other exceptions as applicable
    End Try

    To do otherwise means you’re likely to miss exceptions occasionally, or you’ll be doing more coding than necessary (and repeating yourself, an even worse situation).

    Typical Application Types

    What Eric’s post didn’t touch on was exception handling strategies for different application types.

    Most applications will fall into a few distinct types. Granted, you’ll always have drivers, embedded systems, and others that have even more specific error handling needs, but I generally see these types most often.

    Command line applications

    Your typical command line app is single purpose, with a host of command line switches to control its behavior. For these apps, I generally set up a single TRY CATCH in the sub Main to log or display to the console any unhandled exceptions, and then use a few scattered try blocks throughout the processing code to handle any vexing or exogenous exceptions. Everything else, just let fall back to the main Try block, since the run has basically been fatally terminated anyway.

    Event driven UI applications

    For these, I usually setup a thread exception handler and a process wide exception handler, just to prevent the application from failing completely with no logging of any sort.

    Then, I always setup try blocks in the sub Main, and in every non-trivial event handler, at a minimum. “Non-trivial” here means any event handler containing code or calls to code that could possibly result in an exception.

    And finally, I use a small scattering of Try blocks to deal with code where I expect there “could” be an exception, even though there normally won’t be, but that I can adequately handle in any case.

    For this scenario, I’ve found that an AOP (aspect oriented programming) approach, using something like PostSharp or Spring.net, is a quick, easy and very maintainable way to get these try blocks in place.

    Function Libraries

    Since function libraries typically don’t (and shouldn’t) display any UI components, I generally let any unexpected exceptions bubble out of the library code back to the caller naturally.

    On some occasions, it’s necessary to expose new exceptions from the library. In those cases, I usually create an MyLibrary.Exceptions namespace, containing all the custom exceptions that might be thrown from my library, and then throw them when appropriate.

    Logging

    No discussion on exception handling would be complete without mentioning logging. Any non-trivial app really should have a logging framework in place. Two of my (free) favorites are Log4Net, and NLog.

    They’re both very similar, very capable and very easy to use. Log4net is the “old guy on the block” having been around for a number of years now. NLog is the newcomer, but very capable none-the-less.

    Both make configurable logging so trivially easy, it’s almost criminal not to use them.

    And, realistically speaking, exception handling is a much more powerful concept when coupled with a comprehensive logging strategy.

    Finally, logging is a perfect use case for AOP, so definitely investigate some of the AOP frameworks when you start down this path.

    A GOSUB By Any Other Name

    3
    Filed under .NET, Rants, VB Feng Shui

    imageI’ve been using VS2010 for a while now, and there’s definitely a lot to like in this release. Granted, the UI is a little slower than 2008, but that’s mostly because of all the new WPF goodness baked into every nook and granny of the IDE now.

    One thing that I’d been looking forward to is multi-line lambdas in VB. C# has had that since 2008 (or possibly before), but VB was always limited to a single line or (more typically) a call to a function, which could be multiline.

    Still, when you’re talking about lambdas, you’re typically talking about small chunks of code that you almost never really want to be a separate function, Private or not. It’s just that much more clutter.

    VB2010 finally addresses that disparity and you can now do multi-line lambdas in VB.

    Dim MyLambda = Function(arg As String) As String
       arg &= ","
       arg &= "More"
       Return arg
    
    'And to call it
    Debug.Print(MyLambda("TestArg"))

    Now, technically speaking, you might argue that “MyLambda” is an anonymous method. And you’d be right. Anonymous methods, delegates, and lambdas are, essentially, different names for the same thing. Basically, they’re all just ways of “embedding” code into a variable, and then being able to call that code.

    In the olden days, you’d use pointers for such folderol, but this is managed .net code, and pointers are all but verboten in these parts.

    But wait!

    The thing is, it struck me at one point, while recently describing how you might actually use a delegate to a colleague, of the similarities between anonymous functions like the above, and the much maligned VB GOSUB statement (GOTO’s less recognized little brother).

    Dim Arg as string = "testArg"
    Gosub MyLambda
    Debug.print(Arg)
    Return
    
    MyLambda:
       arg &= ","
       arg &= "More"
       Return

    Don’t get me wrong, I never found GOSUB to be particularly all that clean a construct. I used it on occasion, but not often. You couldn’t pass explicit arguments with GOSUB, and executing a variable GOSUB required the ON x GOSUB statement, which was pretty abysmal to use.

    Still, all the makings of a lambda were right there, all along.

    Normal Ol’ DLLs from VB.net

    7
    Filed under .NET, Arcade, Code Garage, MSBuild, VB Feng Shui

    Every once in a while, I find a need to do something a bit off the wall. Recently, I had another one of those situations.

    I’ve spent a lot of time working with some of the old arcade emulators that are floating around (the most famous of which is MAME, or Multi Arcade Machine Emulator).

    Mame itself is pretty utilitarian, so there are a number of front ends  that are essentially menuing systems to provide a user with an easy to browse interface for selecting games to play and among the more popular front ends is MaLa.

    image

    MaLa Main screen (using one of many available skins) showing list of games, and a screenshot of the selected game

    One nice aspect of MaLa is that it supports plugins, and there are a number of them out there, to control LED lights, play speech, etc.

    I had had a few ideas about possible MaLa plugins for awhile, but the MaLa plugin architecture centers around creating a standard Win32 DLL with old fashioned C styled Entrypoints, and, well, I kinda like working in VB.net these days.

    Gone Hunting

    Eventually, curiousity got the better of me, and I started looking for ways to expose standard DLL entry points from a .net assembly. I ended up finded Sevin’s CodeProject entry called ExportDLL that allowed just that. Essentially, it works by:

    1. You add a reference in your project to a DLL he created, that only contains a single Attribute for marking the functions you want to export.
    2. Create the functions you want to export as shared functions in a MODULE
    3. You mark those functions with the Attribute
    4. You compile your DLL
    5. You then run ExportDLL against your freshly compiled DLL
    6. ExportDLL then decompiles your DLL into IL, tweaks it, and recompiles the IL code back into a DLL

    It sounds complicated but it’s really not.

    I set it all up and had things working in about 30 minutes.

    Gone South

    Unfortunately, all was not quite right. MaLa requires 2 entry points (among a host of them) defined with a single integer argument passed on the stack. Pretty simple stuff. So I coded up:

        <ExportDLL("MaLaOrientationSwitch", CallingConvention.Cdecl)> _
        Public Shared Sub EntryPoint_MaLaOrientationSwitch(ByVal Orientation As Integer)

    But when I ran the DLL within MaLa, it crashed immediately after calling this function, even with NO CODE in the function itself.

    What this meant is that something about the export process was trashing the stack. I spent a solid day hunting for clues as to what might be failing. I did find that eliminating the argument from the exposed entrypoint allowed MaLa to work properly AND call my entrypoint, but, being unable to get the passed Orientation value, the call was basically useless.

    Gone Around Again

    In digging through it all, I happened to notice a comment on the CodeProject page for Sevin’s article pointing to a similar library by Robert Giesecke. I’m not sure if the two were developed independently or not, but Robert’s is certainly a more polished set of deliverables. He even went so far as to put together a C# project template that makes it ridiculously easy to kick off a project using his technique.

    It turns out, not only is Robert’s approach cleaner, it actually properly exports the MaLaOrientationSwitch function above with no problems. MaLa can call it, pass in the argument and all is good.

    Gone Fishing

    One big difference between the two techniques is the Robert actually defines an MSBuild targets file to patch his DLL directy into the Visual Studio build process. Very cool! But, his build step happens AFTER the PostBuildEvent target, and it was in that target that I’d setup some commands to copy the DLL into a file called *.MPLUGIN, which is what MaLa specifically looks for. Hooking that process into the build itself makes debugging things quite natural, but, Mr. Giesecke’s target wasn’t allowing for that.

    Here’s Robert’s targets file:

    <Project
      xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <UsingTask TaskName="RGiesecke.DllExport.MSBuild.DllExportTask"
                 AssemblyFile="RGiesecke.DllExport.MSBuild.dll"/>
      <Target Name="AfterBuild"
              DependsOnTargets="GetFrameworkPaths"
              >
          <DllExportTask Platform="$(Platform)"
                       PlatformTarget="$(PlatformTarget)"
                       CpuType="$(CpuType)"
                       EmitDebugSymbols="$(DebugSymbols)"
                       DllExportAttributeAssemblyName="$(DllExportAttributeAssemblyName)"
                       DllExportAttributeFullName="$(DllExportAttributeFullName)"
                       Timeout="$(DllExportTimeout)"
                       KeyContainer="$(KeyContainerName)$(AssemblyKeyContainerName)"
                       KeyFile="$(KeyOriginatorFile)"
                       ProjectDirectory="$(MSBuildProjectDirectory)"
                       InputFileName="$(TargetPath)"
                       FrameworkPath="$(TargetedFrameworkDir);$(TargetFrameworkDirectory)"
                       LibToolPath="$(DevEnvDir)\..\..\VC\bin"
                       LibToolDllPath="$(DevEnvDir)"
                       SdkPath="$(FrameworkSDKDir)"/>
      </Target>
    </Project>

    I’d worked with MSBuild scripts before, so I knew what it was capable of, I just couldn’t remember the exact syntax. A few google searches jogged my memory, and I ended up here at a great post describing exactly how you can precisely inject your own targets before or after certain other predefined targets.

    I modified Robert’s targets file and came up with this:

    <Project
        xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
        <UsingTask TaskName="RGiesecke.DllExport.MSBuild.DllExportTask"
                 AssemblyFile="RGiesecke.DllExport.MSBuild.dll"/>
    
      <!-- Add to the PostBuildEventDependsOn group to force the ExportDLLPoints
           target to run BEFORE any post build steps (cause it really should) -->
      <PropertyGroup>
        <PostBuildEventDependsOn>
          $(PostBuildEventDependsOn);
          ExportDLLPoints
        </PostBuildEventDependsOn>
      </PropertyGroup>
    
      
      <Target Name="ExportDLLPoints"
              DependsOnTargets="GetFrameworkPaths"
              >
        <DllExportTask Platform="$(Platform)"
                       PlatformTarget="$(PlatformTarget)"
                       CpuType="$(CpuType)"
                       EmitDebugSymbols="$(DebugSymbols)"
                       DllExportAttributeAssemblyName="$(DllExportAttributeAssemblyName)"
                       DllExportAttributeFullName="$(DllExportAttributeFullName)"
                       Timeout="$(DllExportTimeout)"
                       KeyContainer="$(KeyContainerName)$(AssemblyKeyContainerName)"
                       KeyFile="$(KeyOriginatorFile)"
                       ProjectDirectory="$(MSBuildProjectDirectory)"
                       InputFileName="$(TargetPath)"
                       FrameworkPath="$(TargetedFrameworkDir);$(TargetFrameworkDirectory)"
                       LibToolPath="$(DevEnvDir)\..\..\VC\bin"
                       LibToolDllPath="$(DevEnvDir)"
                       SdkPath="$(FrameworkSDKDir)"/>
      </Target>
    </Project>

    Now, I can perform the compile, and execute my postbuild event to copy the DLL over to the MaLa Plugins folder and give it the requisite MPLUGIN name, all completely automatically.

    And, the icing on the cake is that I can build a MaLa plugin completely in VB.net, with no C or C# forwarding wrapper layer and with a fantastic XCOPY-able single DLL application footprint (save for the .net runtime, of course<g>).

    It’s a wonderful thing.

    Software Design Pattern Quick Reference

    1
    Filed under Software Architecture, VB Feng Shui

    I’m a somewhat reluctant believer in software design patterns. On the one hand, it can be handy to have a lingua franco to discuss common patterns with. On the other, the concept has seemed to me to be so wildly hyped over the past few years, that you’d think it was the brand new answer to everything.

    Truth is, I’m guessing most every programmer who’s been working for any length of time recognizes most of the common patterns, and has applied them innumerable times over the years.

    Still, I’ve never spent much time truly digging into the meat and potatoes of each pattern.

    Then I came across Jason McDonald’s Design Pattern Quick Reference PDF here.

    image

    To the right is a reduced view of one of the pages.

    Really well done reference sheets for those that want to put the names with the patterns they likely already know quite well.

    Highly recommended!

    Word and the Disappearing Cell

    0
    Filed under Office, Troubleshooting, VB Feng Shui

    image

    So I was off working on a new bit of code today when an email came through:

    “The tool is blanking out a cell when it’s not supposed to!”

    Ack.

    No big deal though. I fire up the project, load up the document in question and give it a run.

    Sure enough, a cell that contains some text and a merge field (under my control) is being completely cleared out. Only the merge field should be being cleared.

    I dig a little more and eventually narrow the culprit down to a single function.

    Private Function MyFunc(Rng as Range)
       ....
       Rng.Delete
       ....
    End Function

    When I hit that Rng.Delete line, the ENTIRE CELL was being cleared. Including text that had nothing to do with my merge field (other than the fact that it was also in the same table cell).

    After a bit more single stepping through code, I discovered that the Range being deleted was actually empty. In other words, it’s Start position was the same as it’s End position.

    Now, I’ve know from dealing with Word for far too many years that when you’re working with an empty range like that, there are a good number of things that don’t work quite right. Many will throw errors, but I was getting no error here.

    Then it hit me. As a test, I added a few chars of text at the VERY END of the cell, after my merge field.

    Sure enough, everything worked, even though the range being deleted was still empty.

    The End-of-Cell Marker.

    Word stores an End-of-Cell marker character at the end of each cell in a table. The marker is a Chr(7) if you retrieve it, but you wouldn’t normally ever even bother with it.

    However, if you end up with an empty Range object that is situated right at the end of a cell, then that Range is effectively pointing at the End of Cell marker, and if you invoke the Delete method on the Range, you’ll end up invoking it on the End of Cell Marker.

    And what happens if you try and delete an End of Cell Marker?

    Well, duh. The cell is cleared.

    Moral of the Story

    The short version of all this is simple:

    If you plan on deleting a Range, make sure that the Range.Start <> Range.End before you do:

    If Range.Start <> Range.End Then
       Range.Delete
    End If

    Technically speaking, if start = end, then there’s nothing in the range anyway and so there shouldn’t be anything there to delete. But doing so can definitely have detrimental effects in some cases.

    And, as usual, your mileage may vary.

    When Debug.Print Doesn’t Work Anymore

    2
    Filed under .NET, Troubleshooting, VB Feng Shui

    This is one of those “back to basics” posts that, none-the-less, tripped me up for a few minutes, just because it’d been so long since I’d even looking at the setting involved.

    I’d been working on a project for a while, when, one day a few weeks back, debug.print just stopped working. Even weirder, when I’d debug, the debugging would completely skip over the Debug.print statement.

    When it first happened, I was right in the middle of working through some other problem and didn’t want to get sidetracked. But it hit me again a few weeks later, and I decided to start looking around.

    It didn’t take long before I realized this setting was amiss.

    cap1

    It’s checked in the image above, but in my project, somehow it’d become UNCHECKED, and in the Debug project configuration!?

    Still not sure how that happened, other than probably got a little click happy one day with the mouse and didn’t realize it.

    Amazing how the little things can still get ya’ sometimes…

    (and nobody say anything about my dll base address <g>! )