Thursday, February 25, 2010

image If you’ve ever had to use the Word Object Model’s Find object, you probably know it can be a bit… well… finicky. It has guids that conflict with Excel 95 typelibs which causes problems, it uses a veritable forest of optional parameters, most of which are declared as OBJECT so intellisense doesn’t work well with it, it’s a real pain to use with C# because of C#’s lack of optional parameter handling, etc, etc.

And I have a new one to add to the list.

I was recently working on a kind of super advanced mail merge facility for Word documents. Word’s MailMerge capabilities are certainly good, but they couldn’t cut the mustard for this particular batch of requirements.

However, since the MAILMERGE field (and all the various other fields in Word) have a lot of capability, I wanted to leverage that as much as possible.

Essentially, the templates to be used would embed normal mail merge fields, but Word’s Merge ability would never get used. Instead, I’d have a VB.NET assembly that would navigate through each field in the document, analyze its code, and replace it with the appropriate result. The code looks something like this:

Dim Code = Field.Code.Text
'....parse the code for the field here
'     determine the final field contents, put it in Content

Field.Result.Text = Content
Field.Unlink

Pretty simply stuff, really.

But, the content of the field might have embedded style information. Sort of like a stripped down HTML code system. For instance, <b> might be “Turn bold on”, and </b> would turn bold off.

First thought

Initially, I thought I could just detect the existence of the opening tag, remove all the tags, and just format the entire field consistently. It’s simple and fast. But unfortunately, some field values had tags embedded within the field, meaning that only a portion of the field’s data should be formatted.

Strike 1.

RTF??? In 2010?

Then, I figured I could just swap out the formatting code with the equivalent RTF codes, and use PasteSpecial to paste the RTF formatted data directly in the field.

While this did work, it presented a bad side effect. Since the RTF text coming off the clipboard represented specific and complete formatting information, it overrode all default formatting already applied to the field. So, say the entire document was formatted in Calibri Font. When I pasted the RTF text “{\b My Text Here}”, the end result was a field formatted in bold Times New Roman, not Calibri. So even though I hadn’t specifically set the font for the text, the paste special was assuming a default of Times.

Strike 2

That ol’ Word FIND Object

I finally realized that I was going to HAVE to use the FIND object in Word to locate those formatting marks, and then apply the applicable styles to the found text.

Performing the Find is pretty straightforward, although there’s a few things to watch for.

The first is the aforementioned Excel 95 Guid clash. What it means is that you need to access the FIND object via late binding. So obtain a FIND object from the (Field.Result range) and store it in an OBJECT variable. That will force VB.net to make latebound calls to it.

The next problem is how to actually find the marks. You’ll need to use the Find object’s wildcard support for that. The code looks something like this:

Dim Find as Object = Field.Result.Find
With Find
   .ClearFormatting
   If .Execute(FindText:="\<b\>*\</b\>", MatchCase:= false, MatchWildcards:= True, Forward:= True) then
      'the text was found
   Else
      'The text was not found
   End If
End With

Again, pretty simple stuff.

But there was two problems.

The first was, the above would find the text alright, but I still needed to remove those embedded formatting marks. After a false starts, I realized that the REPLACE functionality was could do this very easily. Just mark the * (i.e. the found text that you want to keep) by enclosing it in “()”, then Replace with “\1” (the first marked substring).

Dim Find as Object = Field.Result.Find
With Find
   .ClearFormatting
   If .Execute(FindText:="\<b\>(*)\</b\>", MatchCase:= false, MatchWildcards:= True, Forward:= True, Replace:=wdReplace.wdReplaceAll, ReplaceWith:="\1") then
      'the text was found
   Else
      'The text was not found
   End If
End With

The second problem was much more insidious.

It worked perfectly on fields embedded in the body of the document, but completely failed to find anything in field embedded in cells in a table. Needless to say, I was scratching my head over that one for a while.

It turns out that Find just doesn’t work right if you attempt to use it in the Result range of a Field  object when that object has been embedded within a table.

The trick, then is to Unlink the field object before you attempt a find inside of it.

Dim Rng = Field.Result
Field.Unlink
Dim Find = Rng.Find
With Find
   '.... continue as before

With the range no longer within the field, the Find works just like it should, regardless of whether the field is in the body of the document or embedded within a table.

So there’s my terrifically arcane Office object model trivia for the day!

posted on Thursday, February 25, 2010 10:06:48 PM (Central Standard Time, UTC-06:00)   •  # •  Comments [0] • 
Kick it •  Add to del.icio.us •  View blog reactions; 
 Monday, February 22, 2010

So, I was working on parsing a WordPerfect Merge DAT file today…

Yep, you read that right, WordPerfect! Seriously old school stuff.

Anyway, this file format is a peculiar binary format with a bunch of binary headers surrounding all the nice juicy ASCII merge text fields. Dealing with such files in VB6 was easy, but it seems that the few times I’ve had to work with this type of thing in .NET, I always end up stubbing my toe on encoding.

You see, all strings in .NET are UNICODE, and reading binary data like this into a string involves an encoding or decoding process. In order for things to work the way you’d (or at least, I’d) expect them to, you have to be SURE that the strings will round trip properly. And boy, they weren’t for me.

I wrestled with it all day, finally knocking off to go home and unwind.

But it was still bugging me.

So I whipped up this little sample (why didn’t I think of this at noon today<sigh>).

    Private Sub TestEncode()
        Dim b(255) As Byte
        For x = 0 To 255 : b(x) = x : Next

        Dim buf As String = System.Text.Encoding.Unicode.GetString(b)

        Dim c(255) As Byte

        c = System.Text.Encoding.Unicode.GetBytes(buf)
        For x = 0 To 255
            If c(x) <> x Then Stop
        Next
        Stop
    End Sub

If the code stops at that stop in the last FOR loop, something didn’t round trip properly and you’re pretty much guaranteed a headache.

And sure enough, the UNICODE encoding object failed to round trip. But so does the ASCIIENCODING, UTF8, etc etc.

On a whim, I tried the “default” object, SYSTEM.TEXT.ENCODING.DEFAULT.

And it worked!

A quick check revealed that on my system, DEFAULT is actually the encoding object for the codepage 1252, which is the Windows ANSI ASCII encoding. Read more about it here. But 1252 is the codepage you want to use if you want EVERY SINGLE binary value from 0-255 to map to the exact same unicode character when you read the file into a string.

Long story short, if you’re used to looking at binary files via a hex editor, and you want to manipulate those files in VB, you have two choices.

  1. Read the file into a BYTE() array as raw data, then operate on the bytes directly.
  2. Read the data into a string, but be SURE to use the proper encoder, like so:
Dim Buf as String= My.Computer.FileSystem.ReadAllText(MyFileName, System.Text.Encoding.GetEncoding(1252))

Option 1 is great if you need to work on the data as, more or less, strictly byte type info. But it’s a real pain if much of the data is string type stuff.

Option 2 is MUCH easier to work with for mostly string data (you can use INSTR, MID, LEFT, RIGHT, cutting and chopping much more easily than with byte arrays), BUT you have to have read the data in via the right encoder or it will be “altered” during the loading process and won’t contain the same bytes that were actually in the source file.

Doing this won’t work:

Dim Buf as String= My.Computer.FileSystem.ReadAllText(MyFileName)

Because the ReadAllText routine uses, as its default, the UTF8 encoder.

Hopefully, putting all this down in writing now will keep me from forgetting about it the next time I’m mucking with funky file formats!

posted on Monday, February 22, 2010 9:29:42 PM (Central Standard Time, UTC-06:00)   •  # •  Comments [0] • 
Kick it •  Add to del.icio.us •  View blog reactions; 
 Tuesday, February 09, 2010

image A while back, I wrote up a short post about calling C function pointer style interfaces with VB.net. When I started into that, what I was really wanting was a pure VB.net solution for calling the amBX API interfaces. There was already a library out to do the job, but that would have required including a separate dll, and, well, it’s not VB! It was C++ and C#.

But what’s amBX? Well, the basic system looks like this:

image

That box in the middle is actually called a “wall washer.” It contains several banks of lights that shine up onto the wall behind the unit. The speaking looking things are exactly that: LED lights that look similar to speakers.

You can also get an extension pack:

image which consists of 2 fans, and a rumble bar (basically just a bar with two vibration motors in it).

In action, it looks like this:

Anyway, flash forward to now and my VB version of that library is ready for an initial release.

I call it amBXLibrary (catchy eh?)\:\-\) .

amBXLibrary

The whole thing is in one ambx.vb source code file, and there’s no external references necessary, so, literally all you do is drop that source file into your project and you’ve got support for the amBX device set. Yes, it could  have been broken up into a separate file for each class, and, normally, that’s how I approach things. But in this case, knowing I was planning on making this code publicly available like this, I opted for the simplest distribution form possible. If you must have it split up, feel free!

One more important note: You will need to have the ambxrt.dll file somewhere accessible, either in the same folder as your application or on the path. This file is installed with the amBX system, but won’t normally be on the path.

General Usage

All the internal classes are part of the amBXLibrary namespace. You’ll need to add an imports for that or set it in the project properties (or remove the Namespace line from the source) before you can use it.

The root class is amBX. To start up amBX and connect to its drivers, you’ll need to call the Connect method:

amBX.Connect(1, 0, "My Application", "1.0.0")

The first 1 and 0 are the required major and minor version of the amBX library. Since there’s only a version 1.0, that’s the only possible value to those arguments at this point. The next args are the string name of your application and a string version of the version number of your application. As far as I can tell, these values can be anything you want.

When you’re finished with amBX, be sure to call the Disconnect method (although this is not strictly necessary).

amBX.Disconnect()

The amBX class is a static class, which means you can’t instantiate instances of it. All its methods are Shared. It exposes several collections, into which you can add new amBX objects. Those include:

  • amBX.Lights
  • amBX.Fans
  • amBX.Rumbles
  • amBX.Events
  • amBX.Movies

Create a new amBX light like this:

Dim LeftLight = amBX.Lights.Add("Left", amBXLibrary.Locations.East, amBXLibrary.Heights.AnyHeight)

Technically speaking, since the newly created light is automatically added to the Lights collection, you don’t absolutely need to keep a local reference to it. But doing so makes it easier to work with your objects. Further, generally speaking, in amBX applications, you create the objects you need up front, when your application loads, and you use them until the application quits, so it tends to be more convenient to keep local references.

The first argument, the name, is simply an arbitrary descriptor of the object you’re creating. That is not part of the underlying amBX library. I added it more for convenience than anything. That said, you don’t have  to give names to your objects. You can also create a light like this:

Dim RightLight = New amBX.Light(amBXLibrary.Locations.West, amBXLibrary.Heights.AnyHeight)

Notice, no name, and I just created the object directly with New. Note however that the new Light object is still added to the Lights collection and you can still reference it my index or via an enumeration.

Threading

amBX has several different options for multi-threading. This library only uses one. When you initially Connect, a background thread is started internally which calls the amBX.Update method 20 times per second. You can alter the timing however you want, and even turn it off by settings UpdatesPerSecond to 0. If you do turn it off, you’ll be responsible for calling the amBX.Update method periodically yourself.

Changing Objects

All the amBX objects are fairly simple. The lights have a Color; the fans, an Intensity; and the rumbles, an Intensity, Waveform, and speed. You simply set the properties however you want. The next time the amBX.Update method is called, the changes will be sent to the amBX drivers and the hardware updated.

Events and Movies

Event and Movie objects operate a little differently from the other amBX objects. Events are usually for short event sequences that can’t be stopped or paused. Movies are for longer sequences where you may want to stop or pause the sequence arbitrarily.

With Events, you generally create them during your application Load process and then simply call the Play method anytime you need the event sequence to play out.

Since Movies tend to be much longer sequences, you’ll generally create them right before you need to play them, Play the movie, and then dispose of the object.

Disposing of Objects

All of the effects objects in the library implement the IDisposable interface, so it’s usually best to explicitly Dispose the object once you’re done with it. Usually, this is easiest to do by using a Using Block:

Using Evt = New amBX.Event("c:\SomeEffectFile.ambx_bn")
        Evt.Play()
End Using

Enabling and Disabling

You’ll notice that several of the Enable/Enabled/Disable members are seemingly arbitraryly properties or methods. For instance, Light.Enabled is a boolean property, whereas Fan.Enable is a method, and fan.Enabled is a readonly property. This is because the different objects deal with enabling in different ways. This is the nature of the amBX drivers, not an arbitrary decision of mine!

In the case of a fan, the Enabled property will return which state the can is currently in, which can include Enabled, Disabled, Enabling or Disabling. However, in the case of a Light, the light can only be Enabled or Disabled.

Also note that although the amBX documentation indicates that disabling an object will “cause it to retract itself from the user experience”, I’ve found that doesn’t appear to be the case. When I Disable objects, it simply means that they no longer react to any property changes to the them.

For instance, if you set a fan intensity to .5, then disable the fan, it continues to spin. But, setting the intensity to 0 will no longer alter the fan speed. You must Enable the fan again in order to change its intensity again.

Rumble objects are particularly troublesome in this respect, since there doesn’t appear to be a way to turn one off once it’s turned on. I’ve found that releasing the object and then recreating it will turn the rumbler off, but that causes more problems. So, as currently implemented, you MAY have problems with rumble effects (at least, problems getting them to stop!).

From what I’ve seen online, this is described as a known bug in the amBX drivers, but I’m not completely sure.

The Tricky Parts

I’ve really already covered (in the post referenced at this top of this post) what was the most difficult aspect of getting this library operational. All of the amBX interfaces are C style function pointer structures. These are easy to deal with in C, but more difficult to work with in VB.net. However, pleasantly, they are, in fact completely interoperable with VB.net (or C# for that matter). You just have to use the right combination of IntPtr, and Marshalling to convert those C function pointers to .net Delegates that can be called from managed code with no problems at all.

If you want to know more, check out my previous post here, and pay special attention to the Generate methods in the source code. For instance, here’s the one for the Event object:

 Public Sub Generate(ByVal IamBXEventInterface As IamBXEventInterface)
   Me.Play = Marshal.GetDelegateForFunctionPointer(IamBXEventInterface.PlayPtr, GetType(PlayDelegate))
   Me.Stop = Marshal.GetDelegateForFunctionPointer(IamBXEventInterface.StopPtr, GetType(StopDelegate))
   Me.Release = Marshal.GetDelegateForFunctionPointer(IamBXEventInterface.ReleasePtr, GetType(ReleaseDelegate))
End Sub

It uses the GetDelegateForFunctionPointer method of the Marshal class to create the necessary delegate from the function pointers passed back by amBX. Then, it’s just a matter of retrieving those function pointers correctly, managing the whole mess efficiently and calling the delegates when you need them.

The Caveats

This is a very “in flux” library at this point. In reality, I don’t even have any amBX hardware to test on. Everything I’ve done so far has been using the Virtual amBX Test Device, a program that simulates all the various amBX hardware that’s out there at this point.

I’ve implemented all the various methods and properties of the C amBX interfaces, but I have not tested them all out at this point (specifically, the RunThread and StopThread methods of the amBX object).

I also have noticed the above mentioned problem with disabling rumble devices (it just doesn’t seem to work right), and the only workaround seems to completely kill the rumbler, such that you can’t turn it back on at all without disconnecting from amBX and reconnecting.

However, I’ve noticed similar issues when working with the “amBX Test Tool” that comes with the amBX SDK, so I’m not completely sure whether it’s something in my code, or with the drivers themselves.

That said, the lights, fans, events, and movies all seem to work spot on, and I’m not much concerned about the rumble effects myself anyway\:\-\) .

My Intentions…

I’ve got some very specific things I intend to use amBX for, but mainly, once I find a set for a reasonable price, I’ll be disassembling it and mounting the various pieces in a purpose built cabinet. My hope is to use all the elements (lights, fans and rumblers) but I’m not completely sure that’ll make sense.

I’m also working on a general purpose “screen color tracker” that will drive the amBX lights based on whatever happens to be onscreen, not use amBX enabled DirectX windows. But that’s a whole other project in and of itself!

The Code

I’ve made this project Open Source via CodePlex. Check out the project page at ambx.codeplex.com.

Alternately, you can download the test project (with the ambx.vb library source) here.

And Finally…

Let me know what you think! Have suggestions? Ways to improve the library? Things you would have done differently? Fixes?

By all means let me know. I’ll do what I can to get improvements and suggestions implemented.

posted on Tuesday, February 09, 2010 11:09:06 AM (Central Standard Time, UTC-06:00)   •  # •  Comments [0] • 
Kick it •  Add to del.icio.us •  View blog reactions; 
 Friday, February 05, 2010

imageOk, so it’s completely unrelated to VB in every conceivable way \:\-\) .

I just came across a very nifty way to tie your shoes. It’s called the Ian Knot and there’s a very good pictorial writeup (and video) about it here.

I’m not going to repeat his pictures here, but it’s essentially, just:

  1. make a crossover knot, the way you would normally start to tie your shoes.
  2. In the right hand, make a loop exactly like you normally would, with the string going up, over your finger and down.
  3. In the left hand, make the same loop, but with the string starting below your finger and coming up over your finger towards you.
  4. then just push the two loops through each other and tighten.

Check out the site above for pictures. It’s easier to see it than describe it.

But, it IS amazingly fast, and easy.

posted on Friday, February 05, 2010 9:13:17 AM (Central Standard Time, UTC-06:00)   •  # •  Comments [0] • 
Kick it •  Add to del.icio.us •  View blog reactions; 
 Tuesday, February 02, 2010

image I’ve been playing recently with the amBX ambient effects library and devices.

Essentially, it’s an effects platform that allows you to easily create light, wind and rumble effects to coordinate with what’s going on on-screen, in a game, in media players, or what-have-you. The lighting effects are nothing short of fantastic. The rumble and fan effects…. meh. They’re interesting, but I’m not sure where that’ll go.

Regardless, the API for amBX is all C style objects, which means essentially an array of function pointers to the methods of the object; not really an API that VB.net likes to consume. Be sure to grab the amBX developer kit here. You’ll also need to core amBX software available from the main website. Finally, play around with the “Virtual amBX Test Tool”. It’ll allow you to experiment with all the amBX features and functions without having to buy anything at all. Of course, eventually you’ll want to get at least the starter kit, with the lights. But it’s not necessary to begin experimenting.

Hats off to Philips for making this possible!

image

Here’s an example of the structure definition from the amBX.h header file that comes with the API (I’ve clipped out comments and other bits):

struct IamBX {
    amBX_RESULT (*release) (struct IamBX * pThis);
    amBX_RESULT (*createLight) (struct IamBX * pThis,
                                amBX_u32 loc,
                                amBX_u32 height,
                                struct IamBX_Light** ppLight);
....

As you can see, each element in the structure is made up of a pointer to a function. The various functions all take, as their first argument, a pointer back to this structure. Under the covers, this is how virtually all object oriented languages function, it’s just the the compiler usually hides all this nasty plumbing so you don’t have to deal with it regularly.

But this presents a problem. VB.net is “managed” code, and as such, it likes things to be wrapped up in nice “managed” bits. There are plenty of good reasons for this, but these function pointers are decidedly not nice and tidy managed bits! So, what to do?

One solution is the approach Robert Grazz took here. It’s a solid solution, no doubt, and I learned a lot from looking at his approach, but, this being VBFengShui, I wanted that same functionality in native VB.net with no additional dll files hanging around!

Delegates to the Rescue!

A delegate in .net is essentially a managed function pointer. In VB.net, they’re most commonly used to handle events, but you wouldn’t really know it, because VB’s compiler does a good job of hiding all that plumbing from you. However, unlike VB6 and earlier, in VB.net, all the plumbing can, if you’re willing, be “brought into the daylight” and used however you want.

There are many, many discussions about delegates for VB.net out on the web. A really good Introduction to the concepts by Malli_S is on codeproject, so I won’t rehash the basics here.

The problem is, delegates in VB.net tend to be generated by using the AddressOf operator, and I already had the function addresses (they’re in that C structure). I just needed to get a delegate that would allow me to call it.

Some Googling turned up several good posts that provided pointers, including this one on StackOverflow. But it wasn’t exactly all the steps necessary.

Getting the C Structure

The first step toward getting something working with amBX is to retrieve the main amBX object. You do this through a standard Windows DLL call.

<DllImport("ambxrt.dll", ExactSpelling:=True, CharSet:=CharSet.Auto)> _
        Public Shared Function amBXCreateInterface(ByRef IamBXPtr As IntPtr, ByVal Major As UInt32, ByVal Minor As UInt32, ByVal AppName As String, ByVal AppVer As String, ByVal Memptr As Integer, ByVal UsingThreads As Boolean) As Integer
        End Function

Assuming you have the ambxrt.dll file somewhere on your path or in the current dir, the call will succeed, but what exactly does that mean?

Here’s an example of a call to it in C:

    if (amBXCreateInterface(
            &pEngineHandle, 
            majorVersion, minorVersion, 
            (amBX_char*)cAppName.ToPointer(), (amBX_char*)cAppName.ToPointer(),
            nullptr, false)
        != amBX_OK)

Essentially, you pass in the Major and minor version numbers of the Version of amBX you need, and two strings indicating the name of your app and the version of your app. No problems with any of that. But that &EngineHandle is the trick.

It means that this call will return a 4 byte pointer to a block of memory that contains the amBX object structure, which is, itself, an array of 4 byte function pointers to the various methods of the amBX object. Therefore, in VB.net, that argument is declared ByRef IamBXPtr as IntPtr.

Now, we need a place to store that “structure of pointers.” Going through the ambx.h file, I ended up with a structure that looks like this:

        <StructLayout(LayoutKind.Sequential)> _
        Private Structure IamBX
            Public ReleasePtr As IntPtr
            Public CreateLightPtr As IntPtr
            Public CreateFanPtr As IntPtr
            Public CreateRumblePtr As IntPtr
            Public CreateMoviePtr As IntPtr
            Public CreateEventPtr As IntPtr
            Public SetAllEnabledPtr As IntPtr
            Public UpdatePtr As IntPtr
            Public GetVersionInfoPtr As IntPtr
            Public RunThreadPtr As IntPtr
            Public StopThreadPtr As IntPtr
        End Structure

That StructLayout attribute is particularly important. It tells the compiler that the structure should be layed out in memory JUST AS it’s declared in source code. Otherwise, the compiler could possibly rearrange elements on us. With Managed Code, that’d be no problem, but when working with unmanaged C functions, that would not be a good thing!

And finally, we need a way to retrieve that function pointer array and move it into the structure above, so that it’s easier to work with from VB.net. That’s where the System.Runtime.InteropServices.Marshal.PtrToStructure function comes in. This routine will copy a block of unmanaged memory directly into a managed structure.

Private _IamBX As IamBX
Private _IamBXPtr As IntPtr
...

amBXCreateInterface(_IamBXPtr, 1, 0, “MyAppName”, “1.0”, 0, False)

_IamBX = Marshal.PtrToStructure(_IamBXPtr, GetType(IamBX))

And presto, you should now have the _IamBX structure filled in with the function pointers of all the methods of this C “Object”.

Calling the C Function Pointer

At this point, we’ve got everything necessary to call the function pointer. Take the CreateLight function. The C prototype for this function is shown at the top of this page. As arguments, it takes a pointer back to the amBX structure, 2 32bit integers describing the location and height of the light source, and it returns are pointer to another structure, in this case, an amBX_Light structure, which contains another set of function pointers, just like the amBX structure described above.

First, we need to declare a delegate that matches the calling signature of the CreateLight C function we’ll be calling:

<UnmanagedFunctionPointer(CallingConvention.Cdecl)> _
Private Delegate Function CreateLightDelegate(
         ByVal IamBXPtr As IntPtr, _
         ByVal Location As Locations, _
         ByVal Height As Heights, _
         ByRef IamBXLightPtr As IntPtr) As amBX_RESULT

The key points here are:

  1. Make sure you have the CallingConvention attribute set right. Most C libraries will be CDECL, but some libraries are STDCALL.
  2. Make sure your parameter types match, especially in their sizes. Not doing this will lead to corrupted called or system crashes.

Now, create a variable for the delegate and use the Marshal.GetDelegateFromFunctionPointer function to create a new instance of the delegate, based on the applicable function pointer. Since the function pointer for the CreateLight function is stored in the CreateLightPtr field of the _IamBX structure, we pass that in as the pointer argument.

IMPORTANT NOTE: There are 2 overloads for the Marshal.GetDelegateFromFunctionPointer  function. Be sure to use the one what requires a second argument of the TYPE of the delegate to create. Using the other one will fail at runtime because it won’t be able to dynamically determine the type of delegate to create.

Next, call the function via the delegate, just as if it was a function itself.

Finally, use Marshal.PtrToStructure again to copy the array of function pointers returned into another structure, this one formatted to contain the function pointers of the Light object that just got created.

Dim d As CreateLightDelegate = Marshal.GetDelegateForFunctionPointer(_IamBX.CreateLightPtr, GetType(CreateLightDelegate))
Dim r = d(_IamBXPtr, Location, Height, _IamBXLightPtr)
_IamBXLight = Marshal.PtrToStructure(_IamBXLightPtr, GetType(IamBX_Light))

The amBX library is much, much larger than just this little bit I’ve shown here. Once I get the entire thing coded up, I’ll be presenting it here as well.

But in the meantime, if you have a need to interface with C style function pointer objects, don’t let anyone tell you it can’t be done in VB.net

Final Note

As you may or may not have guessed, amBX is a 32bit library and its interfaces, functions and arguments all live in 32bit land. If you’re working with VS2008, BE SURE to set your project to the x86 platform, and NOT “Any CPU” or “x64”! The default, for whatever reason is “Any CPU”, which means things will work properly when run under 32bit windows, but things won’t work well at all if run under a 64bit OS.

posted on Tuesday, February 02, 2010 10:37:20 AM (Central Standard Time, UTC-06:00)   •  # •  Comments [1] • 
Kick it •  Add to del.icio.us •  View blog reactions; 
 Thursday, January 28, 2010

At one point a while back (while I was still working for my previous company), we had “support for x64” handled down as a request for an interim version.

I thought, “No sweat”. Grab a few alternative prerequisite MSIs, determine the bitness of the processor you’re on in the install (InstallShield has the functionality built in), and just fire off the appropriate preqs. Our actual application is 32bit, and we had no intention or need to compile as 64bit.

Well. A few clicks later and the install was built and deployed to a test machine.

Crash.

Initial sample database didn’t get deployed properly.

Ok, why not. Well. Long story short, the application couldn’t find a registry key setting. But I hadn’t changed anything about the registry.

Lots of digging through verbose install logs later, and I discovered that the installer was, on a 64bit OS creating registry keys under the key  HKEY_CURRENT_USER\Software\Wow6432Node whereas when my application when to get the registry key, it was looking in the normal HKEY_CURRENT_USER\Software\ key.

Huh?!

First, what the hell was this Wow6332Node? Obviously it’s some kind of “compatibility” bit for running 32bit apps under a 64bit OS. And that’s exactly what it is.

Ok, my Installer is InstallShield, and it’s a 32bit app (even if it can install 64bit packages), so that explains why it was writing the key to that Wow6432Node, but why wasn’t my application reading it from there?

A little digging later, and I found this option buried in the “Advanced Compiler Settings” panel of the “Compile Options” tab of the Project’s properties.

image

See that AnyCPU setting? When set to AnyCPU, the JIT compiler will dynamically compile your .net dll as either a 32bit or 64bit dll, depending on the process that loaded it.

Obviously, on a 32bit OS, all the processes will be 32bit, so everything’s 32bit.

BUT, on a 64bit OS, things get nastier.

If the DLL runs under a native code 32bit process, it’ll get compiled as 32bit x86 code and run under the Wow32 (Windows On Windows) layer. This explains why the DLL that acts as an AddIn to Word worked just fine. Word is a native 32bit process, so the DLL was ending up executing as 32bit too.

However, the little utility app that creates our initial database was a .net application, and it was set to AnyCPU.

That meant that when IT loaded our DLL, the DLL ended up JITed to 64bit code (because the utility app was set to AnyCPU, so it was JITed to 64bit code because it was a base process and was running under a 64bit OS.

Case closed.

Short version of the story. Since tracing all this down, I’ve learned that for VS2008, the .net team decided to change the default of that option from x86 to AnyCPU, and then, in general, that has been regarded as a bad thing to have done.

The default will be changed BACK to x86 in 2010 apparently, but until then, unless you REALLY need to compile code for AnyCPU, be sure to switch this option back to x86!

posted on Thursday, January 28, 2010 2:06:36 PM (Central Standard Time, UTC-06:00)   •  # •  Comments [0] • 
Kick it •  Add to del.icio.us •  View blog reactions; 

I was working on a server issue this morning when I ran into something strange. I could no longer access a server that had been running for quite some time without any problems.

I tried a PING and got back an IP address for the server that made no sense at all. It wasn’t even part of my local IP range!

So I did all the normal stuff:

  1. Checked my HOSTS file
  2. ran IPCONFIG /FLUSHDNS
  3. ran IPCONFIG /REGISTERDNS
  4. ran IPCONFIG /RELEASE
  5. then IPCONFIG /RENEW

No joy. A ping was still returning the same bogus address.

So I checked my server’s DNS service. Not even an hit of that address.

Hmmm. So, where the heck was it coming from? A little googling didn’t turn up much, but eventually, I read a blog post that made an offhand mention of WINS.

Now, I don’t really know all that much about WINS. Just never had a reason to, I suppose. Mostly, I’ve always relied on and stuck with plain DNS. But, Ok, I’ll check it.

Go over to my server, and load up the WINS app (it’s under Admin tools)

image

The left hand window was completely blank. It took a second to realize I had to “query” to retrieve the WINS records, they aren’t automatically just shown.

image

And AHA! There, in the result list of “Active Registrations” was the bogus address for my server. (I’ve already removed it in the image below, but it was in the highlighted column).

image

Case closed. I’m still wondering what changed that suddenly, WINS was being used to resolve the server name when it must have not been before. The only thing I can think of is changing internet providers to Verizon FIOS from Time Warner Cable, and the resulting swap out of the main incoming router.

Granted, for a seasoned network guy, this is likely old hat. But for a software dev who only moonlights as a network guy, it might be some useful information!

posted on Thursday, January 28, 2010 2:04:42 PM (Central Standard Time, UTC-06:00)   •  # •  Comments [0] • 
Kick it •  Add to del.icio.us •  View blog reactions; 
 Sunday, January 24, 2010

I had a need over the weekend to do a little PHP work. Now, I’m no expert in web anything, most of my time has been spent building nice happy fat client apps \:\-\) . But, when I’ve needed to do a little web tinkering, my host (www.ServerGrid.com) pretty much supports everything, so I’ve just uploaded my files and had at it.

However, this time, I wanted to get things running locally, to avoid all the upload/download hassles.

A few google searches turned up the Microsoft Web Platform Installer.

Wow! Something other than Office, VS and SQLServer that Microsoft has done right!

It took a few minutes to run through, and I had to tweak the PHP.INI file a bit (using the instructions here), but, all told, I had a PHP 5.2 installation fully operational under a local IIS7 server in, oh, 10 minutes.

It the Web Platform Installer can install a lot of other stuff too. CMS, SugarCRM, DasBlog, and a bunch more.

Definitely worth the download!

posted on Sunday, January 24, 2010 9:35:44 PM (Central Standard Time, UTC-06:00)   •  # •  Comments [0] • 
Kick it •  Add to del.icio.us •  View blog reactions; 
 Tuesday, January 19, 2010

image Recently, I ran into a need to make use of the Mono.Cecil.dll library from a .net application I was working on. Cecil is a fantastic little project under the Mono project that allows you to interrogate an existing .net assembly (EXE or DLL file) and retrieve all kinds of information about the assembly, from the resources embedded within it to the classes and methods defined, and much more. You can even alter the contents of the assembly and write the new version back out to disk!

The thing is, Cecil comes prebuilt as a C# assembly (a DLL file), and I really did not want to have a second file required for this particular application (it’s just a little command line utility).

My first take was to use Oren Eini’s excellent concept of an assembly locator. My idea here was to embed an assembly as a binary resource, then, when requested, read that resource into a stream, load the assembly from the stream, and resolve references to it via the assembly locator.

I’m still working on that concept, because I think it’s a clever and convenient solution to the problem, but, in researching that, I happened to remember the even easier (as in, no code required at all!) solution of using ILMerge.

ILMerge

If you haven’t already discovered it, ILMerge is a Microsoft research project in the form of a single command line EXE utility, that can “merge” any number of .net assemblies with a “target” assembly, and produce either a .net DLL or EXE output file.

There’s a really good article on CodeProject describing the general use of the program. There’s even a GUI (Gilma) for it.

Automating ILMerge

What the article doesn’t go into is automating the ILMerge process. After all, you won’t want to manually run that command line utility every time you build your application!

The good thing is, it’s trivially easy to automate as long as you take care of one critical step.

  • First, download and install ILMerge from the link above.
  • Once it’s installed be sure to copy the ILMerge.exe utility to somewhere on your path (or add the folder it’s in to your path).
  • Then, grab the Mono.Cecil.dll file (or whatever DLL it is you want to merge into your main project EXE). Put it in the root folder of your project.
  • Go ahead and set a reference to that file, so you still get all the .net intellisense goodness, but be sure to set the Copy Local property for the reference to FALSE (after all, you don’t want to copy this DLL to the output folder along with the application if you don’t actually need it, right?)

    image

  • With that done, you MAY want to mark the DLL you’re embedding as “included in project” from the Solution Explorer.

image If you do this, however, make sure you also set the Copy to Output Folder to “Do not copy” (that’s the default though so it should already be set).

The Tricky Part

One limitation of ILMerge is it that it can’t alter the target assembly “in place”. This means that, for instance, if you want the final resulting executable file name to be called GenerateLineMap (my utility), you can’t have VS compile the assembly to that name. You’ll need to use some other name for the initially compiled assembly.

On the Application tab of the project properties you can change that name, like so:

image

I just added “-Interim” to the Assembly Name.

Now, go to the compile tab of the project properties and click Build Events

image

Insert this as the POST BUILD EVENT

ilmerge /target:winexe /out:"$(TargetDir)$(ProjectName)$(TargetExt)" "$(TargetPath)" "$(ProjectDir)Mono.Cecil.dll"

Notice that the OUT parameter specifies the output file name via the $(ProjectName) variable (which is still “GenerateLineMap”) while the first assembly to merge is specified using the $(TargetPath) variable (which is the full filename of the output assembly, including the “-Interim”).

image

EDIT: Important note: Notice the /target:winexe option. You’ll need to change that as appropriate depending on the type of exe you’re building. In my case, I had a console app where this needed to be set to just /target:exe. Setting it to /target:winexe caused all of the console output functions to just do nothing, which threw me for a bit!

Now, just rebuild the solution and you should see two resulting EXE files in your output folder, one with the “–Interim” (which is the version WITHOUT the embedded Mono.Cecil.DLL file or whatever DLL you’ve chosen) and one WITH the embedded file. As a final cleanup, you may want to add an additional Post build step to remove the “*-Interim” files.

To test, just make sure you DO NOT have the embedded DLL anywhere on the path or in the same folder as the exe and run the exe. If everything went right, your app should work exactly the same as if the embedded DLL was included externally with the app!

Now, your application is back to being a single EXE to distribute, and it was built completely automatically by Visual Studio.

Caveats

You knew there had to be some, right?

The first is that if the dll to embed contains licensing information, it might not work properly after being embedded. I don’t have any DLLs like that to test with, but I’ve read reports about the problem at various sites on the internet. Just something to be aware of.

Second, trying to replace the originally named exe with the newly built one results in VS not being able to debug the exe in the IDE (it throws a message about the assembly manifest being different from what was expected). I haven’t worked that issue out yet. What this means is that you might need to leave any references set to “Copy to Output Folder” while debugging, and not replace the original compiled assembly, just ILMerge it into a new assembly name.

posted on Tuesday, January 19, 2010 12:54:37 PM (Central Standard Time, UTC-06:00)   •  # •  Comments [0] • 
Kick it •  Add to del.icio.us •  View blog reactions;