November 2006 - Posts

Managing un-managed Resources

Yesterday Chuck posted a cool example of using GDI from .NET.  One thing that was missing was the call to ReleaseDC.  You should *always* call this when finished painting with a DC obtained via GetWindowDC.
 
   DeclareFunction ReleaseDC Lib"user32" (ByVal hwnd As IntPtr, ByVal dc As IntPtr) As Int32
 
So Chuck's code on first iteration would then become:
 
Dim g As Graphics = Me.CreateGraphics()
'Get the Graphics context to blt into
Dim Desktop_Hwnd As IntPtr
Dim Desktop_HDC As IntPtr
Desktop_Hwnd = GetDesktopWindow()
Desktop_HDC = GetWindowDC(Desktop_Hwnd)
Debug.Print(StretchBlt(g.GetHdc, 0, 0, Me.Width, Me.Height, Desktop_HDC, 0, 0, Me.Height / 2, Me.Width / 2, SRCCOPY))
'Slam the super sized desktop into graphics context of your form.
 
ReleaseDC(Desktop_Hwnd, Desktop_HDC)
 
 
 
Okay so far we have released the unmanaged resource (DeviceContext).  Problem two is the graphics object itself should be disposed of by calling Dispose on it rather than waiting for a GC collection to call its finalizer .  So with the graphics object, we should probably use a Using block.
 
And with our DC, we probably want to ensure that Release gets called, so we'd need to wrap that in a Try Finalize block.  We can't use a Using block for the DC as it doesn't implement IDisposable.
 
Using g As Graphics = Me.CreateGraphics()
'Get the Graphics context to blt into
     Dim Desktop_Hwnd As IntPtr
     Dim Desktop_HDC As IntPtr
     Try
       Desktop_Hwnd = GetDesktopWindow()
       Desktop_HDC = GetWindowDC(Desktop_Hwnd)
       Debug.Print(StretchBlt(g.GetHdc, 0, 0, Me.Width, Me.Height, Desktop_HDC, 0, 0, Me.Height / 2, Me.Width / 2, SRCCOPY))
'Slam the super sized desktop into graphics context of your form.
    Finally
        ReleaseDC(Desktop_Hwnd, Desktop_HDC)
    End Try
End Using
 
 
 
Alternatively we can get all OO, and encapsulate the DC in a class that does implement IDisposable. Our code would then look like:
 
Using g As Graphics = Me.CreateGraphics(), _
        nDC As NativeDC = NativeDC.GetDeskTopDC
       Debug.Print(StretchBlt(g.GetHdc, 0, 0, Me.Width, Me.Height, nDC.DC, 0, 0, Me.Height / 2, Me.Width / 2, SRCCOPY))
End Using
 
We've now made the DC have a managed wrapper to make managing the unmanaged resource a lot easier and more in keeping with .NET memory resource management.
 
The next thing you might want to consider is moving the StretchBlt methods into the NativeDC class, allowing you to move all the win32 API calls into one class so as you can later easily look at adding declarative security assertions etc.

 

Public Class NativeDC
   Implements IDisposable
 
 
   Private m_DC As IntPtr
   Private m_Hwnd As IntPtr
   Private m_NeedsDispose As Boolean
 
   Public Sub New(ByVal dc As IntPtr)
      m_DC = dc
   End Sub
 
   Public ReadOnly Property DC() As IntPtr
      Get
         Return m_DC
      End Get
   End Property
 
 
   Public Shared Function FromWindow(ByVal hwnd As IntPtr) As NativeDC
      Dim nDC As New NativeDC(GetWindowDC(hwnd))
      nDC.m_Hwnd = hwnd
      nDC.m_NeedsDispose = True
      Return nDC
   End Function
 
   Public Shared Function GetDesktopDC() As NativeDC
      Return FromWindow(GetDesktopWindow())
   End Function
 
 
 
#Region " IDisposable Support "
 
   Public Sub Dispose() Implements IDisposable.Dispose
      Dispose(True)
      GC.SuppressFinalize(Me)
   End Sub
 
   Protected Overrides Sub Finalize()
      Dispose(True)
   End Sub
 
   Protected Overridable Sub Dispose(ByVal disposing As Boolean)
      If Me.m_NeedsDispose Then
         ReleaseDC(Me.m_Hwnd, Me.m_DC)
      End If
      Me.m_NeedsDispose = False
   End Sub
 
 
#End Region
 
 
 
#Region "win32 API"
 
   Declare Function GetDesktopWindow Lib "user32" () As IntPtr
 
   Declare Function GetWindowDC Lib "user32" (ByVal hwnd As IntPtr) As IntPtr
 
   Declare Function ReleaseDC Lib "user32" (ByVal hwnd As IntPtr, ByVal dc As IntPtr) As Int32
 
#End Region
 
 
 
End Class
 
 
Posted by bill | with no comments
Filed under:

What's that at the fires ???

yesterday at the Casterton fires, I took a picture of our truck. Look closely at the passenger window !!
 
 
 
Thanks Frank and Dave and all the DPE guys for your support !!  :)
 
 
Posted by bill | with no comments
Filed under:

Office 2007 or not ?

Today I downloaded and installed Office 2007 from MSDN :)  The install went fantastic, taking my Office XP settings.  I did have an issue with the online activation of OneNote.. for some reason it was telling me I had exceeded my activation number, yet I had only installed it once.  Perhaps it is something to do with the same key being used for all the Office 2007 products (other than Office 2007 professional ) such as InfoPath, OneNote et al ?  Anyway, I used the over the phone activation and after pressing many numbers and then talking to a person who gave me more numbers to type in, it's activated :)
 
Still, after just a few hours I am feeling very much like un-installing it.  Everything works, I can adapt to the new ribbon etc, but the damn screen fonts they use are rendered using clear type or similar and it is just really hard on my eyes on my Toshiba M200.  I have good eyesight but this is really causing me eye strain. I can feel my eyes trying to change focus to interpret those blurry regions as smooth lines (that's the concept of clear type: optical illusion).

why the f*ck has Microsoft decided to ignore user settings in this regard, and force this upon people is beyond me.  I'll give it a couple more days, but at present I think the plan will be to try to recover my data, rollback to XP until there's a fix or service pack that does actual observe the user's system preferences for font rendering.  :( 
 
Okay, shortly after posting the above I found the option to turn off clear type in Office :) 
It's more obvious when using other office products than Outlook.  From Outlook you can get to the clear type setting via Tools --> Options --> Mail Format -->Editor Options.
 
Oh, and you can also change the colour of Outlook form blue to silver or black :)
 
So I'm happy again.  :)
 
 
Posted by bill | 2 comment(s)
Filed under:

IE7 Musings

 
I've been using IE7 almost from the day it was released, and for the most part it's been good.  The UI took a little to get use to, but nothing requiring me to look up the help file (phew)<g>  Performance seems good, and tabbed browsing can be handy.  But there's a few improvements I would like to see:
 
  1. Search in the current page.  Why bring up an extra dialogue window, instead surface the forward and next buttons on the search in the menu bar.
  2. Allow customisation of ALL the menu bar area's.  At present you can't move that "Home"… "Tools" bar, and I want to.  It just feels wrong where it is, I would prefer to have my Links menu bar there.  I definitely want to move my Links menu bar from having to sit in-between the address bar and the tabs.  At present it's "instance (page specific)", "static", then "page specific".  Let me choose what feels comfortable there for me
  3. Allow me more flexibility when opening new tabs.  I have links open in new tabs without switching to that tab, but sometimes I would like to switch to that tab. It'd be nice if the context menu allowed a "go to" or another way to let me choose
  4. Give me greater flexibility in security without a zillion annoying prompts.  I don't want to be prompted to allow activex controls all the time (I only allow a set of admin approved ones by default), yet I do want an easy way to let a given site use other activex. At present I have to either submit to being always prompted or change the zone for a site.  Very much an all or not at all kind of feeling.  I'd much rather an un-obtrusive icon in the status bar I can right click on, see what activeX a page has requested, and check which ones I want to allow, a and/or allow all for on a page by page basis.
  5. Similar to 4, by this time on privacy.  I'm tired of the ridiculous number of cookies sites want to store on my machine.  But I want to allow other sites to add cookies, yet I don't want to be prompted. It'd be nice if this was easy to change per site when a page loads
  6. Adding a site to a different zone shouldn't require so many clicks as it does today
  7. It'd be nice if that notification area between the tabs and the actual page could be hidden by default if I have the status bar displayed, instead showing up as an icon in the status bar.
Other than that everything seems to work, possibly better and faster than previous versions.  I don’t think the user is in control yet, but hopefully soon :)
 
 
Posted by bill | 1 comment(s)
Filed under:

Tooling up for .NET 3.0

With the release of .NET 3.0, I decided to clean up my machine a little and install the latest bits.  The first step was uninstalling all the beta and CTP bits I had on there including the Orcas bits, the previous WPF, WCF and WF bits, the previous windows SDK and associated installs. 
 
Next I tested Visual Studio 2005 before I preceded….    WHOOPS !!  It was broken.  I presumed the problem was some of the other CTP bits, most likely the LINQ bits, rolled it back into a state that was pre the SP1 beta bits.  So I had two choices, either go for a clean install, or try to re-install the SP1 bits.  I went with re-installing the SP1 bits and all went well.

I downloaded the .NET 3.0 runtime, and the entire Windows SDK ISO image, and the WPF and WCF designer CTP bits, and the WF extensions.
Installed all of it and all is good except there's no context help from the WPF designer.  Maybe I got the help integration messed up yet again.

All is good. :)
 
My advice is if you have beta bits installed, uninstall them, then check to see if VS is working properly before installing the new bits…. well, worked for me anyway :) 
 
Oh, and nero had trouble with the iso image but I renamed it to a shorter name winSDK.iso and it worked fine.
 
.
 
Posted by bill | with no comments
Filed under: , ,

Burning bale champions

At the local hicksville Colac (what did Chuckcall it ?) agricultural show in the weekend we had the usual burning bale competition.  One of the other brigades was short a couple of crew, so we teamed up with them, two of us from my brigade (myself included) and two form their's.  The rules were different this year, requiring us to jump on the truck, drive to the fire, dismount, start the pump, put out the fire, store all equipment, jump back on the truck and drive over the finishing line.   (yes images of keystone cops kind of shenanigans comes to mind ;) )
 
WE BLITZED IT !!!
 
We came in 5 seconds faster than our nearest competitor , and set a new course record !! (well that's because it was the first time this modified course was run <g>)  We were also the only team that wasn't disqualified !!!!
 
 
 
Posted by bill | with no comments
Filed under:

Of bikes and snakes

Today is the first anniversary of my buying my bicycle. I rode a bit over 2150 km this last year, that's 40 km a week or more which I'm pretty happy with considering I didn't ride much at all over winter ;) So for my birthday this year I bought myself new tyres and brakes. With the tyres I ended up getting bigger tyres, 2.2's instead of the old 1.95's, but they are semi slicks with a radial pattern on the side walls and very rounded. So I'm actually between 5 and 10% faster on them ! And the roundness of them makes them reasonably good when I do hit sand :)
 
With the brakes I bought a set of pads (V-brakes) for $10 for the 4, and was appropriately disappointed with them, so a 100km later (a week) I looked for better pads. I decided to try a multi pad, that's got white, grey and black pads in it. Nice !! They stop really well. And just to put them to the test as I rode down a red scoria hill on Sunday, a 3 foot tiger snake decided to slowly cross the track.. the brakes stopped me nicely :) I waited as the snake, seemingly oblivious to me, continued on it's way.

 
These fancier brake pads were about $40 for the set of four, but well worth it. I think they've already paid for themselves ;)
 
Posted by bill | with no comments
Filed under:

Iterators and functional programming

I’ve been meaning to blog about Iterators for sometime now but can never find the time to give the subject as it deserves. But rather than stay silent, I’ve decided to at least blurb some of my thoughts.
 
A couple of weeks ago Nick posted an example of what you can do with iterators in C#. The sample was a tree iterator, the tree being similar in nature to a file-system: each folder has Items which are files as well as a collection of folders. 
 
My first thoughts where that this is in fact a common thing to do, and that a case by case iterator was (and is) a bad approach.  Rather you should be able to simply return a generic tree enumerator.  Typically when working with collections you rarely need to use an iterator other than the standard ones, such as an array’s or a List’s.  That is, in 99.9% of cases, the iterators you want to return are common patterns, and the guidance of code re-use should steer us well away from custom iterators, especially inline ones.  This particular example however poses other problems. 
 
If we wanted to solve this problem with a generic tree iterator, we’d need to provide two bits of information, (i) the item property get, and (ii) the child nodes property get (or function).  We can solve (i) via the IList interface and it would be reasonable to expect that to be implemented, but for (ii) the list of folders we don’t have another interface to use. Given the framework doesn’t have such an interface, we can’t really expect an existing class to have already implemented an interface which we are yet to define ;).. Hence the need for functional programming…….
 
In this example we can’t simply pass the lists to an iterator because the iteration is recursive.. that is as each child node is traversed, the iterator needs to get a list of the child’s children (sub-folders) as well as the child’s items (files).  So one approach would be to pass in MethodInfo and the root object to the generic iterator’s constructor. The MethodInfo would be the function or property_get for the child nodes.  The problem with this approach is that all strong typing is lost.
 
What we really need here is a type safe way to work with what is essentially a delegate, but one in without the instance being fixed….. a “first class” way of dealing with function types, just as we can with class types.
 
Let’s say for example we introduced a GetMethod keyword, similar in nature to GetType in VB (or TypeOf in C#).  We might also want to simplify getting Property Get’s and Set’s by providing specific keywords for them, eg GetPropertyGet ;)
We’d also want a nice way to refer to these methods and an easy way to convert them to and from delegates. (similar to RuntimeMethodHandle, but castable to a delegate not just an IntPtr)
Now we should have enough to build our generic tree enumerator.
 
Class TreeEnumerator(Of T)
 
       Sub New( ByVal root As IList(Of T), ByVal method As Function()  returns IList(Of IList(Of T)) )
               …..
 
In the above constructor, I’ve used an inline way of defining the Function and instead of having the parameter read as: method As function As returntype, I’ve added a “returns” keyword to better inline describe what the function does rather than multiples As’s ;)
 
Now in the above example, “method” would in fact be a delegate already, and this would fit nicely to how we’d actually call it as the first method would in fact be on the root instance.  As we iterate this however we’d need to get from that delegate the MethodHandle and from that then get the Delegate for the next instance.
 
So in essence what is needed here to preserve the strong typing is to be able to have a derived MethodInfo, much like how we have derived Delegates, and to be able to create a Delegate easily from the derived MethodInfo specifying the Target, and have that nice design time checking in place.
 
The GetMethod, GetPropertyGet etc, would only be needed for static types, in the other cases we’d really be dealing with StronglyTyped delegates in a more flexible manner than what we can today.
 
But I have digressed, I was talking about iterators   (or was I ??? <g>) And the question has been raised is how important are iterators from a language point of view. 
 
From my view point I see iterators as focusing very much on the plumbing, not the end points.  They don’t encourage code re-use, in fact quite the opposite.. the solution rather than being descriptive becomes procedural.  And I do believe that in the vast majority of cases you can use standard enumerators.  Of course for those few cases where you do need to jump in between the pipes, having to actually write your own enumerator is very much like being inside the sewer pipe ;)
Posted by bill | 1 comment(s)
Filed under: ,