Category Archives: .NET

Nasty, Nasty x64 and the AnyCPU Option

0
Filed under .NET, VB Feng Shui

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!

Windows 7 and Vista GodMode

0
Filed under .NET, Vista, Windows 7

If you haven’t already checked it out, definitely head over to Tom’s hardware for their article on setting up “GodMode” in Windows 7 (apparently it works in Vista too, dang, wish I’d known that).

Basically, you create a folder somewhere, then rename it to

GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}

When you do, that folder becomes a “virtual folder” full of (on my system anyway) 278 links to virtually every administrator type function you might ever want to jump to on a Windows Machine. Here’s a sample screenshot:

image

Very, very cool indeed.

Flipping Video with DirectShow

11
Filed under .NET, Media, Troubleshooting, VB Feng Shui

If you haven’t checked it out already, DirectShowLib.net is pretty much THE way to get at direct show functionallity in VB.net (that is unless you want to spend $$$). Thing is, it’s only a paper thin wrapper over the DirectShow COM api stuff, so there ain’t no hand holding here.

I’d mucked with it for a while and with the help of some of the sample code, got video playing in a form in VB.net fairly easily, but, I needed to flip and/or rotate that video under some circumstances.

After many googles, I finally came across the IVMRMixingControl9 interface that the VideoMixingRenderer9 exposes, but, no matter what I did, I could not cast from a VMR9 to the MixingControl, like so:

Dim Mixer = DirectCast(VMR9, IVMRMixerControl9)

I kept getting an “Interface not implemented”. Then I happened across a post about a wholly different problem, but buried within it was a comment about needing to set the VMR into “mixing mode” in order for it to implement that IVMRMixingControl9 interface. Ugh! DirectShow is nothing if not interfaces. And odd dynamically implemented interfaces at that. Oh well.

A little more digging, and it turns out to be quite easy. Just obtain the IVMRFilterConfig9 interface from your VMR9 object, and call SetNumberOfStreams on it (with and argument 1 or more).

The end result is code that looks like this (remember, this is with a reference to DirectShowLib.net):

DIM FGM = New FilterGraph
Dim VMR9 As IBaseFilter = New VideoMixingRenderer9

FGM.AddFilter(VMR9, "Video Mixing Renderer 9")
Dim FC As IVMRFilterConfig9 = VMR9
FC.SetRenderingMode(VMR9Mode.Windowed)
FC.SetNumberOfStreams(1)

Dim Mixer = DirectCast(VMR9, IVMRMixerControl9)
Mixer.SetOutputRect(0, New NormalizedRect(1, 1, 0, 0))
Mixer.SetAlpha(0, 0.2)

Note that in this case, the SetOutputRect is reversing the output rectangle, so the video is going to end up flipped and upsidedown, exactly what I was needing. I’ve also set the alphachannel to .2, meaning the video is somewhat transparent.

Unfortunately, there doesn’t appear to be any way to rotate the video using the MixingControl, so that is my next topic of research.

VBScript in VB.Net

2
Filed under .NET, ActiveX, Languages, VB Feng Shui

A long (long) time ago, if you wanted your users to be able to enhance your product by add coding logic, you pretty much had two choices:

  • Dig into Lex and Yacc or….
  • Roll your own parser and scripting execution engine.

Then, around the time VB 6 was released, Microsoft introduced VBA. It worked, but it was expensive and a god awful complicated mess to integrate with your app, so outside of Microsoft Office (which even as of Office 2010, still supports it!), very few applications actually made use of it.

Around the same time, the Microsoft Scripting Control was released. This was an ActiveX control you could use from any COM compatible language to embed VBScript. Now, of course, this is VBScript, not a “real” language like C or even VB. But, it was free, easy to obtain, and very easy to use.

As the years have rolled by, .NET has steadily grown in capability and while the Windows Scripting Host exe is still shipped with Windows, the old VBScript and JScript scripting has largely been supplanted by either:

  • ASP and more recently ASP.NET
  • Powershell
  • Dynamically compiled .NET code
  • and likely lots more options I’m not familiar with

Now, all these options are good, and each definitely has it’s place, but, for many purposes, good ol’ VBscript still fits the bit quite nicely.

But can you use it from .NET? And if so, how?

The Tempest in the Teapot

Before I continue, I should point out that any time you start talking about allowing users to add their own code into your application, you’re opening up a huge can of worms that you’ll need to deal with. Things like properly catching exceptions from badly written user code (yeah, that never happens), adding watchdog timers to deal with hung and infinitely looping user code, security concerns, and the like all will have to factor into the decision. You have been warned <g>.

So Simple It Hurts

I had a plugin project recently where I wanted to give the user the ability to write some very simple logic to expand the functionality of the application.

Of course, I wanted to build a full plugin API, but I also wanted to provide a lighter-weight option for those users that didn’t want to dive head-first into a full on .NET project. VBScript seemed like the obvious choice.

A few Google searches later and most everything I found was talking about how to dynamically compile .NET code, which is cool indeed, but not what I was really after. Other articles and posts insisted that users should convert their VBScript code to .NET (ok, yeah, but that’s not really the point now is it?).

Then I did a Google Desktop search of my own system and turned up some VB6 code I’d written ages ago to experiment with the Microsoft Scripting Control.

Now, I know that .NET languages support accessing ActiveX Controls and COM objects in general, but this was pretty old stuff. Would it actually still work?

I cobbled up a dirt simple VB.net project:

Public Sub Main()
    Dim Script = New MSScriptControl.ScriptControl
    Script.Language = "VBScript"
    Script.AddCode("sub Main" & vbCrLf & "MsgBox ""This is a Test"" " & vbCrLf & "End Sub")
    Script.Run("Main")
End Sub

Be sure to add a reference in the VB.net project to the COM object “Microsoft Scripting Control”.

Run it, and lo and behold, I get the “This is a Test” message box, straight from VBScript!

Obviously, there’s lots more to making use of the Scripting Control than just this, but, clearly, VBScript is still very much a choice for adding limited programmable logic to your application.

Creating Good ol’ Standard DLLs with VB.NET

0
Filed under .NET

Managed code (VB.net and C#) are great for a lot of things, but unfortunately, even as of VS2008, it’s still missing at least one. Standard DLL exports.

You see, way back in the olden days, virtually every DLL in Windows was written in C or assembler and exported functions via the standard DLL export table.

Then came COM and now .NET, providing much easier, object oriented export capabilities. Old style EXPORTS have been falling by the wayside ever since.

Unfortunately, if you program for Windows, eventually you’ll find yourself needing to either consume or provide exports. There’s just no way around it.

For consuming (ie simply “calling”) exported functions in a DLL, .net makes that almost trivially easy. All of the Windows API can be called in this way, simply by including the proper attributes (for VB) for the function declaration in your application. Here’s an example for the SENDMESSAGE Windows API function.

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
End Function

The Hard Part

However, exporting functions from a .NET DLL in the standard Windows API style is not near as easy.

Why would you need to do this? The main reason is to provide hooks that other applications can call. There are many, many applications out there that require addins or plugins to export standard DLL entry points. Being unable to do this in .net means either having to write a shell in C/C++ around those entry points (doable but cumbersome), or simply not providing that functionality.

The good news is that the .NET compiler designers didn’t completely forget about such down-to-the-metal tidbits as this. The bad news is that they didn’t provide any syntactic sugar to make it straightforward either.

Emilio Reale posted an excellent article on CodeProject that discusses the dirty IL (Intermediate Language in .net speak) mechanics of how to:

  1. compile your .net DLL
  2. disassembly it with ILDASM to IL source code.
  3. find the necessary bits in the disassembled output and what to change them to
  4. reassembly the IL source using ILASM into a DLL with the proper functions exported.

All fine and dandy till you look at what’s required. Needless to say, it’s an amazingly involved process to perform manually.

Fortunately, another CodeProject contributor tackled this problem and posted this article. In it, he presents a small utility and attribute definition dll that allows you to export a function (almost ANY function) from a .NET DLL simply by applying an attribute to it, like so:

<ExportDllAttribute.ExportDll("MyFunction", _
System.Runtime.InteropServices.CallingConvention.Cdecl)> _
Public Shared Sub EntryPoint_MyFunction()
     ...my code goes here....
End Sub

and then running the utility on the compiled DLL, which automates the above tasks.

It takes a little work to get things set up, but in the end, it worked flawlessly for me. Within just a few hours, I’d put together the shell of a plugin for an application that I’d had reservations about writing plugins for, simply because it looked like I’d have to do so in C++.

Now, the whole plugin is done, it’s all in VB.net (my language of preference currently), it’s a single DLL with no dependencies (other than the .net runtime <g>), and it can be deployed by simply copying it into a folder.

Can’t get better than that!

An Interesting Use of Generics

0
Filed under .NET, VB Feng Shui

I was working on some validation logic today, and was getting heavily into generics in several classes, when I stumbled across an application of generics that I hadn’t see before.

Take the following sample code (granted, it’s trivial, but it should get the idea :

Public Class Form1
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim s As String = "Testing"
        GenericTest(s)

        Dim i As Integer = 5
        GenericTest(i)

        Dim f As Single = 10.7
        GenericTest(f)
    End Sub
End Class


Public Module Generics
    Public Sub GenericTest(Of t)(ByVal Variable As t)
        Debug.Print(Variable.ToString)
    End Sub
End Module

Notice that the GenericTest function is early bound directly to 3 different variable types due to the use of generics. Just like using object type variables but without some of the stigma <g>.

Also note that GenericTest is defined in a module. I’d only seen generics as a way of defining classes before, never just a single function, and certainly not a function in a module.

Anyway, this may be old hat for many VB.net people, but I found it interesting, at the least. Not exactly sure how I might leverage it at this point, but it’s always good to have things like this in your toolbox.

DataContractSerializer is Not Necessarily Wonderful

0
Filed under .NET, VB Feng Shui, XML

Serializing objects in .NET is surprisingly easy, and there are a number of different ways to go about the process.

One method that was recently brought to my attention is the DataContractSerializer.

To use it, you’ll need to:

Imports System.Runtime.Serialization

Then create an new instance of a DataContractSerializer and a stream and finally, use the Serializer object to write a serialized version of some other object to the stream. I won’t delve into that code here, there’s plenty of examples on the web; even the Microsoft Help page for that object has a decent example.

But what you won’t find mentioned is how incredibly brittle the serializer can be.

First off, it doesn’t round trip the serialized XML, at least not completely. Say you serialize an object to an XML file, then EDIT that file and add comments. If you then deserialize and reserialize the object, you loose all your comments.

While this is somewhat understandable, it is rather unfortunate. Too bad that’s only the lesser of the problems you’ll face.

Another issue is one that plagues XML in general. It’s CASE SENSITIVE. This makes hand editing the files tricky at best. Now, I know a lot of you might say “Jeez, stop hand editing your XML!” but, let’s be realistic. Sometimes, that’s just flat the fastest way to deal with certain issues.

But the real stumper for me was when I recently discovered that the DataContractSerializer is highly dependent on the ORDER of the XML elements in the serialized XML! That’s right, get elements out of the order that the serializer expects them in (and yet still have perfectly legal and reasonable XML) and the serializer fails. But what’s worse is that it fails silently. It just simply fails to deserialize certain property values if their xml elements aren’t in the “proper” order (which happens to be alphabetic, but still, XML should not be order dependent).

There’s a short write up on it here, but even the author, Aarron Skonnard, doesn’t comment on the fact that if elements are out of order, they won’t deserialize properly.

From what I’ve read, that order dependency is partly why the DataContractSerializer is up to 10% faster than some other serialization techniques. And, if you know that your serialized objects will ONLY ever be touched by code that is intended to work with them, that’s probably ok.

But it’s something to be very aware of if you intend on the serialized XML being visible to (or editable by) actual people.

Finding the True File Location of an Executing .NET DLL

0
Filed under .NET, VB Feng Shui

image Say you’ve written a .NET DLL and you need to know from what folder that DLL was loaded (so you can find resources, config files, whatever).

There are any number of ways to skin that cat, but unfortunately, most won’t work in the general case, but only under certain special circumstances.

Matthew Rowan does a really good job of explaining the differences here, so I’m not going to repeat his post, but the short version of the story is, it takes code that looks like this:

Dim assemblyUri As Uri = New Uri(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase))
Return assemblyUri.LocalPath

Note that this is the VB version of Matthew’s clip. There a a number of other methods, but they all seem to return bogus results under various conditions.

.NET Interoperability with COM Office Apps, a Hidden Gotcha

0
Filed under .NET, ActiveX, Office, Troubleshooting, VB Feng Shui

image I’ve been working with .NET and Office interoperability for some time now, and, other than a few minor hiccups here and there, things have generally been very smooth.

But a colleague recently ran into a problem that required a good deal of hunting to resolve. Long story short, even though .NET interoperability with Office objects is virtually foolproof, releasing your references has some hidden dangers lurking amongst the weeds.

As a general rule, it’s safe to let the .NET garbage collector (GC) do it’s thing while your application is running.

BUT, when you’re app shuts down, you need to take a few extra steps to make sure everything’s cleaned up before quitting.

The details are laid on in this article on MSDN. It’s from 2005, but, from what I can tell, it’s just as applicable now as it was then.

Essentially, the trick boils down to this:

When you’re preparing to shut your application down, you need to make SURE you’ve released all your references to any Office objects. This means setting all your various references to Nothing, or, more typically, letting the GC do its thing.

Unfortunately, the GC doesn’t necessarily do its thing during a shutdown, so you have to force the issue. And that requires code essentially like this:

WordApp.Quit() 
WordApp = Nothing 
GC.Collect() 
GC.WaitForPendingFinalizers() 
GC.Collect() 
GC.WaitForPendingFinalizers() 

The article noted above doesn’t really go into why it’s necessary to call Collect and WaitForPendingFinalizers twice, but it does appear to be required. I’m guessing it’s due to the way the Finalizer sweeps object references; it could be possible for it to release objects in a certain order, causing it to skip some objects. But that’s just a guess.

And as a final note, if your .NET code uses any COM interoperability, it might be a good idea to do some final cleanup along these lines as well.

Problems with Microsoft.Sdc.Tasks.Tools.InstallShield

0
Filed under .NET, MSBuild

I’m trying to automate the building of an MSI file using InstallShield’s “Standalone Build Manager” via MSBuild, and one nicety I was hoping to implement was integrating the output of the InstallShield build log into the results of MSBuild.

Originally, I’d used an MSBuild EXEC task to fire up ISCmdBld.exe to perform the build, which works just fine, but which writes the log file to a more or less arbitrary location within the InstallShield project folder structure.

After a bit of Googling, I noticed that the Microsoft.SDC.Tasks MSBuild Extension Library had an InstallShield task as a part of it. Great! Just use that to perform the compilation, and I’m all set!

Unfortunately, that was not quite the case.

Once I’d downloaded the files, extracted them to the proper locations, and modified the Microsoft.Sdc.Common.Tasks file to point to the right place, I was still getting an error when I attempted a build:

Message              = Object reference not set to an instance of an object.

After some investigation, including browsing the source on the codeplex site, I figured out at least part of the problem:

        protected override void InternalExecute()
        {
            #region Execute code

            Directory.CreateDirectory(buildpath);

            RegistryKey installShieldKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\InstallShield\Developer\7.0");

The registry subkey referenced in the task points to an InstallShield 7 key, and I’m using IS 2009. <Sigh>

At this point, I’m back to using the EXEC task directly. Not optimal, but it does work.