Thursday, February 24, 2005

Ok, I'm kind of a sucker for these kinds of tests - it's always interesting how people compare and, with a little introspection, see how accurate or off-base the results are.  In my case, I'd say it's pretty close, at least after one take.

Cattell's 16 Factor Test Results
Warmth |||||||||||||||||||||||| 74%
Intellect |||||||||||||||||||||||||||| 86%
Emotional Stability |||||||||||||||||| 54%
Aggressiveness ||||||||||||||||||||| 66%
Liveliness ||||||||||||||| 50%
Dutifulness |||||||||||||||||||||||||||| 86%
Social Assertiveness |||||||||||||||||||||||| 78%
Sensitivity ||||||||| 30%
Paranoia ||||||||||||||| 50%
Abstractness ||||||||||||||| 50%
Introversion |||||||||||||||||| 54%
Anxiety ||||||||||||||||||||| 62%
Openmindedness ||||||||||||||||||||| 66%
Independence ||||||||||||||||||||| 70%
Perfectionism ||||||||||||||||||||| 70%
Tension |||||||||||| 34%
Take Cattell 16 Factor Test (similar to 16pf)
personality tests by similarminds.com
Thursday, February 24, 2005 5:10:00 AM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Wednesday, February 23, 2005

Maybe it's late or I'm just giddy...this struck me as hilarious.  I almost fell out of my chair.

Maybe I'm due a nice, smooth, refreshing cup of Nescafe Granulated FoodService Blend myself...then again, maybe not ;)

Wednesday, February 23, 2005 4:10:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Tuesday, February 22, 2005

I am inspired by a post by Bill (William?) Ryan.  I responded to his post with a quick comment, but since submitting my response I have been somewhat introspective into the types of music I listen to and how productive I am.  Some music really grates on me while I'm working, whereas when not coding it's perfectly acceptable.  I have about 13 GB of WMA files on my media server (all ripped from CDs that I legitimately own) and it's quite a mix of songs.  While I have playlists and such, I'll often stream down songs randomly.  It gets weird sometimes to listen to one song with a pretty heavy beat to suddenly switch to Julie Andrews singing a song from Camelot and switch over to some dance beat and then a Latin ballad.  I love all the music, but I find that I'm substantially more productive if I a) don't listen to anything so I can focus on the code or b) listen to a certain genre of music or c) I forget, I'm listening to music right now and I'm distracted.

Anyhow, here's a sampling of some of my favorite music to code to.  I'd be interested in your comments and what kind of music gets you going during a code-jam session.

Favorites (preferred highlighted):
   Alanis Morrissette
   ABBA
   Alicia Keys
   Alison Krauss
   Avril Lavigne
   Barry Manilow
   Bon Jovi (especially from the 'Slippery When Wet' era)
   Cesaria Evora (enchanting voice)
   Depeche Mode
   Enigma
   Enya
   Eurythmics
   Faith Hill
   John Denver
   Josh Groban
   Julie Andrews
   Laura Pausini
   Lucero
   Luis Miguel
   Mana
   Maroon 5
   Norah Jones
   Peter Gabriel
   Ricardo Montaner
   Rick Wakeman
   Sarah Brightman
   Sheryl Crow
   Tears for Fears
   The Carpenters
   The Doors
   They Might Be Giants
   U2
   Weird Al Yankovic

There's a wide range of music I'm not mentioning here (such as classical music, Broadway (e.g. Les Miserables, Jekyll & Hyde, etc), and showtunes) because the list it too long and kinda all falls into the category of 'I love to listen to it anytime' anyway.

What music do you do your best work to?

Tuesday, February 22, 2005 2:59:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [2]  |  Trackback

Ok, this may be old hat and I'm the last on the planet to discover this, but I'm pretty excited!

Since my induction into the .NET world (which was graceful and without incident) I have had a beef with one aspect of it - Type visibility.  If I create a Class Library (aka DLL) and create public types, I really can't designate who can use those classes. - they're open to the world.  Ok, ok, there are ways to enforce this such as by applying the StrongNameIdentityPermissionAttribute to the type.

The StrongNameIdentityPermissionAttribute (SNIPA, affectionately) is a pretty slick attribute that you can apply to a variety of things: assemblies, classes, structs, constructors, and methods.  This attribute effectively marks the item as useable only by a client with a given strong name.

Demonstration of how to use the StrongNameIdentityPermissionAttribute:

1.  Create your strong name (e.g: sn -k KeyFile.snk) for your client application.

2.  Sign your client assembly with the strong name (e.g: [assembly: AssemblyKeyFile(@”..\..\KeyFile.snk”)])

3.  Set a reference to the DLL (class library) in the client (note, it will have to also have a strong name so follow steps 1 and 2 for the DLL, possibly reusing the .snk file if you want)

4.  Identify the class / method / etc that you only want to be callable by the client application.  This is the item to which you will apply the SNIPA.  A simple way to identify the strong name for the calling client is to retrieve it's public key.  This is done against the compiled client .exe/.dll (e.g:  secutil -hex -s ClientApp.exe or sn -Tp ClientApp.exe) [Updated 02/23/2005 - Didn't want to forget the sn.exe utility].  This will output the public key in hex format.  Copy and paste it into your code:

using System.Security.Permissions;

namespace ClassLibrary1 {

   [StrongNameIdentityPermission(SecurityAction.Demand, PublicKey=”......”)]
   public sealed class Class1 { ... }

}

There really isn't much more to it than that.  Only clients signed with the specified strong name will be able to create instances of the designated type and call its methods.  Pretty slick stuff.

There are a few caveats and restrictions, however, with using the SNIPA.

1.  Firstly, SNIPA applies only to one type.  That is, if you have multiple types that you want to share with a designated strong-name-signed application, you must mark each and every type individually, otherwise they're public to the world.

2.  Secondly, the items flagged with the SNIPA must be public.  They cannot be internal types.

3.  You can designate only one SNIPA per element; you cannot identify two different strong names.  You have one friend and that's it.

Today, I made a great discovery that I thought worth sharing, and this brings me back to the original purpose of the post in the first place.  In the Whidbey timeframe you will be able to designate friend assemblies with a fantastic attribute called InternalsVisibleToAttribute.  This attribute can be applied to your assembly thus:  [assembly: InternalsVisibleTo(”...”)].  One nice and enabling characteristic of this attribute is you can apply it multiple times to your assembly to designate multiple 'friends' unlike the SNIPA with which you can only designate a single category of friends: those with a given strong name.

The coolness behind this is you can create types that are internal to your application, and now internal can actually extend beyond the scope of your DLL and into your 'family of products' without exposing unnecessary objects and types to the public world.  I am SO excited for this feature as I was wanting to take advantage of such functionality since the beginning.

Way to go .NET team!

Tuesday, February 22, 2005 2:13:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [4]  |  Trackback
 Saturday, February 19, 2005

[Updated 06/22/2006 - fixed typo in code]

Lately, I've been debugging an issue in an application that I wrote that was a bit frustrating, though until today I've pretty much ignored the error.  I decided to bite the bullet and dig in and try to figure out the problem.

I have an application that creates some datagram (UDP) endpoints using the Socket class found within the System.Net.Sockets namespace.  As it turned out, there were times during my application's execution path in which the sockets would suddenly stop responding, though the port was still open (this could be ascertained via netstat or TCPView).  To make the situation more perplexing, I had another application that used the exact same objects and it didn't exhibit the same behaviors - it continued to run as expected.

So I dug in a bit and within about 30 seconds figured out the problem - at least what was causing the problem:  the point at which the application always had this problem of stopping to respond it would always send a datagram packet to localhost (127.0.0.1) to determine if it could find a particular listener/host.  Well, if I had a listener at localhost there was never a problem, but if no socket was bound to that endpoint my UDP socket would throw a SocketException during the EndReceiveFrom().

I put together some tests and found that the WinSock error being thrown was WSAECONNRESET; in other words the socket was forcibly closed by the remote host.  This was disconcerting for a little while, but I found that if I simply called BeginReceiveFrom() again, it would be up and running - but this wasn't necessarily the right fix.

Microsoft made some changes to their WinSock implementation between Windows NT 4.0 and Windows 2000.  One of these was that the Recvfrom() function would return WSAECONNRESET instead of continuing to block or time out if the sendto() function resulted in an “ICMP port unreachable”.  In other words, if you sent a datagram to a listening port all was cosher and behaved normally, however, if you attempted to send a datagram to an endpoint without a listening application, a pending/blocking call to Recvfrom() would throw.  Previously, my SocketException handling code would simply return without attempting to re-listen, assuming that if the error were received the socket was closing down.

It is possible, fortunately, to achieve Windows NT 4.0 behavior rather than having the socket return an error result.  This is accomplished by calling the WSAIoctl() function in Ws2_32.dll.  Well, if you're writing code using the .NET framework, it's not necessary to dip down into P/Invoke to call the function, but rather you can use the IOControl() method on the Socket class.  The key lies in passing in the control code of SIO_UDP_CONNRESET and a value of False (0) to turn off the 'new', Windows 2000 behavior - thus restoring the expected Windows NT 4.0 behavior.

const uint SIO_UDP_CONNRESET = 0x9800000C;

It's interesting, and I feel unfortunate, that the IOControl() function accepts control codes of type Int32.  Many of the control codes are UInt32 values.  So instead of taking the default value for SIO_UDP_CONNRESET and passing that in (which we can't because it's out of the range for an Int32), we must take the same value and convert it to a signed value.

// 0x9800000C == 2440136844 (uint) == -1744830452 (int) == 0x9800000C
const int SIO_UDP_CONNRESET = -1744830452;
byte[] inValue = new byte[] { 0, 0, 0, 0 };     // == false
byte[] outValue = new byte[] { 0, 0, 0, 0 };    // initialize to 0
_socket.IOControl(SIO_UDP_CONNRESET, inValue, outValue);

Simply make that call during the initialization of the socket and the WSAECONNRESET error will not be raised when a datagram is sent to a closed/invalid end point.

Happy coding!

Saturday, February 19, 2005 5:22:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [2]  |  Trackback
 Thursday, February 17, 2005

I found this brief essay online today and it's definitely worth the read.  I've mentioned some of the tenets in past posts, but I whole-heartedly agree with Michael's assessment of the life and lifestyle within Microsoft.  Granted, though I was not on a product team or working on-campus as I was in our Salt Lake City branch office, much of what he said was directly applicable.

Individuals within the halls at Microsoft have a passion and a focus for software.  Software is the bread and butter of everything.  There is very little paperwork at all - pretty much everything besides the periodic reviews and printed expense reports (which simply provide a backup to the electronically filed expense reports) is done via software.

The two downsides that Michael mentions that stood out to me are Work/Life Balance and Managers.  He's spot on.  It seems that while the mantra is that one should strike a good, healthy, working balance between work and family life, it is the tendency of managers to judge that work is more important if you had to make a decision (of course it didn't help that my managers were in the Denver office).  Any decision to the contrary is detrimental to your review scores.

He mentions that 'most of lower management should be tossed'.  I'm behind him there.  In fact, I feel that's a big part to my being disillusioned in some respects.  Don't get me wrong, I love the leadership (BillG, SteveB, etc) and a select few of middle/upper management, but my direct managers left a lot to be desired and are probably the primary reasons and catalysts as to why I left in the first place.  I strongly feel that I'd work for MS again if I were to have different (and local) management.

All in all, a very good post.

Thursday, February 17, 2005 5:31:00 AM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Tuesday, February 15, 2005

Frequently, when developing applications we go out of our way to be considerate to end users.  We pop up nice dialogs, use friendly colors, provide keyboard shortcuts as necessary, sometimes we even write help documentation.  But how often do we go out of our way to consider those that run our applications over a terminal session?

Sure, it's cool to have the fancy dialog that fades in and out, but over a terminal session that can be horrendously slow.  As a courtesy, our applications should check to see if they are running in a terminal session environment and, if so, degrade the graphics output gracefully.  But how do we check?  It's amazingly simple.  Dipping down to the GetSystemMetrics() function in the Win32 API is the key.

[DllImport(”user32.dll”)]
public static extern int GetSystemMetrics(int nIndex);

public const int SM_REMOTESESSION = 0x1000;

public static bool IsTerminalSession() {
   return ( 0 != GetSystemMetrics(SM_REMOTESESSION) );
}

The GetSystemMetrics() function will return a non-zero value with a SM_REMOTESESSION parameter value if the application is associated with a client terminal session.

Interestingly, the vast majority of the GetSystemMetrics() functionality was ported over to the .NET Framework to the System.Windows.Forms.SystemInformation class, but the SM_REMOTESESSION is missing (unless I'm just blind).  It actually makes sense to be missing from the standpoint that it really doesn't have anything to do with the Forms namespace.  Is it somewhere else in the Framework and I just don't know about it?

For the time being, however, that one-liner is all it takes!

Tuesday, February 15, 2005 8:04:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [7]  |  Trackback

Let's face it...we're all accustomed to them by now; they're pretty much everywhere.  I'm talking about irregularly-shaped windows, of course.  For a few years it seemed that every new application that came out had to take advantage of the ability to create windows that weren't the same ol', standard, boring rectangular windows that were so commonplace.

I believe that the first application I ever saw to leverage this capability of creating non-rectangular windows was a Norton Anti-Virus - it had a 'shield-shaped' dialog...or maybe it was McAfee.  I was blown away at first by it.  How on earth did they do that!?  Then, predictably, almost every 'cool' tool and application had to have it - especially those in the multimedia arena.  Well, there can be too much of a good thing, but I feel that they have their place.

This capability is made available by Windows via a GDI object known as a Region.  Regions come in a variety of geometric shapes: rectangular, elliptical, polygonal.  Once a region has been established, it can be assigned a window handle (hWnd) such as a Form, Button, etc via SetWindowRgn().  Regions, when applied to an hWnd determine which parts of the window are to be visible and which parts are transparent.

Not to be outdone, this capability is not lost on the .NET framework.  In fact, it's alarmingly easy to create windows with non-rectangular borders.  By using the TransparencyKey property of a Form you're pretty much there.  However, this isn't without it's costs.  When you create a Form that relies on a transparency key for this effect, the system recreates the region at runtime everytime the form loads.  This can impact load time significantly.  It would be much better if we could know before hand exactly what the region was and apply it without having to regenerate it repetitively.

And, as luck would have it...there is a way!  We simply need to dip down into the Win32 using P/Invoke.  Once a region is created (via any of the prescribed methods such as CreateRectRgn, CreateEllipticRgn, CombineRgn, etc), you can call the GetRegionData() GDI function.  This function will return to the buffer that represents the region.  The inverse of GetRegionData is the ExtCreateRegion function, which simply takes the buffer and creates a GDI Region object.  This region object can then be applied to an hWnd via SetWindowRgn and we're off the races.

Back in my VB days about 5-6 years ago I had created a utility which I dubbed the 'Region Generator'.  This utility would accept as parameters a bitmap image and a color to be treated as transparent.  It would cycle through the pixels of the image and generate a complex Region via CombineRgn and the XOR flag which would effectively mark all pixels of the given color as transparent.  Then it would output a binary file containing the buffer from GetRegionData.  I would use this file by embedding it within an application's resource file to be read out and applied at runtime.  It was pretty slick and pretty easy to use.

Unfortunately, I've since misplaced the tool (I know I have it somewhere), but rather than digging up the fossil, I thought I'd recreate the dinosaur.  It only took a couple of hours and some excursions back into the long under-utilized recesses of my mind to remember how to do it.  I have plans to add some other features to it (such as manually entered RGB/Web color values, a color tolerance so you don't have to get the color exactly right which might be especially useful for .jpg images, etc).

Once you have a region saved, it's a pretty simple task of taking the region data and loading it up to assign it to a window.  This example demonstrates how to load the data from a file and applying it (reading it from a resource file is just as easy):

[DllImport("gdi32.dll")]
public static extern IntPtr ExtCreateRegion(int lpXform, int nCount, byte[] lpRgnData);

[DllImport("user32.dll")]
internal static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);

// read the data from disk into a byte array
byte[] regionData = null;
using ( FileStream fs = new FileStream(@"C:\MyRegion.rgn", FileMode.Open, FileAccess.Read, FileShare.Read) ) {
   BinaryReader reader = new BinaryReader(fs);
   regionData = reader.ReadBytes((int)fs.Length);
}

// create the region from the byte array and assign it to the window
HandleRef hWnd = new HandleRef(this, this.Handle);
IntPtr hRgn = ExtCreateRegion(0, regionData.Length, regionData);
SetWindowRgn(hWnd.Handle, hRgn, true);

Of course in true .NET form, we can use the Region property of the Form rather than having to use SetWindowRgn thus:

this.Region = Region.FromHrgn(ExtCreateRegion(0, regionData.Length, regionData));

Feel free to download and use this tool and let me know what you think.

Tuesday, February 15, 2005 6:51:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [3]  |  Trackback
 Monday, February 14, 2005

An application that I'm writing relies on a Sql Server database.  This database is readonly for users of the website that feeds off of the data.  However, the application utilizes two roles: Publishers and Readers.  Web users fall into the 'Readers' role.  Publishers, however have read/write access to the database in order to push changes to it.  This is not an uncommon scenario by any stretch.

As the Publishers push out their content, the database log file grows, and grows, and grows.  Well I don't need the log file at all, especially since the database can be replaced at anytime simply by dropping it and recreating it.  It never ever has need of being backed up either.

Today, my good friend, Scott Golightly, reminded me of the stored proc sp_dboption.  Using this stored proc upon creating the database I can avoid more complicated commands later on:

EXEC master.dbo.sp_dboption 'dbName', 'trunc. log on chkpt.', 'TRUE'

rather than the following which also carries the byproduct of requiring that the user be a member of the db_backoperator and db_owner fixed roles:

BACKUP LOG dbName WITH TRUNCATE_ONLY
DBCC SHRINKDATABASE(dbName, TRUNCATEONLY)

Monday, February 14, 2005 8:12:00 AM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Friday, February 11, 2005

If you happen to ever create ASP.NET UserControls (e.g. .ASCX files) then this might be of interest.  Oftentimes, in an attempt to create useful, dynamic pages, developers will, via code, load control instances rather than rely solely on <tagPrefix:tagName /> declarations on the .ascx page itself.

Instead, we'll frequently call this.LoadControl(”...ascx”) to load the control and then add it to the .Controls collection of the parent .ascx.  This is all well and good and works remarkably well.  However, if you start to do anything fancy in the child .ascx files you may be greeted with the all-too-helpful HttpException: “External component has thrown an exception”.  This can be somewhat disconcerting because the error throws on the call to LoadControl and doesn't provide any feedback as to the cause of the error.

It's time to investigate the child .ascx's HTML.  More often than not, you have some malformed HTML that the server just cannot process.  A situation that I frequently encounter is that the developer created a server-side HTML table control that contains malformed child controls.  The following exemplifies this:

<%@ Control language=”c#” AutoEventWireup=”false” Inherits=”...” %>
<%@ Register tagPrefix=“custom“ tagName=“MyDataRow“ src=“~/.../childcontrol.ascx“ %>
<table id=t runat=server>
   <custom:MyDataRow id=row runat=server />
</table>

While the MyDataRow class might render the contents within <tr><td>...</td></tr> tags that results in good client code, the server code is malformed and the HTML table cannot initialize properly within the UserControl on the web server.

Word to the wise, when dealing with UserControls (especially those that rely on runat=server controls), always ensure that the HTML is well-formed.

Friday, February 11, 2005 7:47:00 AM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [4]  |  Trackback