Posts Tagged ‘Design’

Awhile back I wrote a series of posts about WPF From PowerShell From PowerShell” which were about how you could load XAML in previous PowerShell 2 CTPs to create WPF user interfaces … a few people have mentioned loading XAML in PowerBoots, and a couple of people have posted other samples showing XAML even since I published the most recent release, so I figure it’s time to point out that you really can load that XAML into Boots, and get all the threading and other support.

Just for fun, I’m going to rehash an earlier post about updating windows to show how you can go about this using PowerBoots, and hopefully show that it’s a little easier (and a lot more async). Compare and contrast the code in this article with that one, just for fun.

This works with any version of PowerShell

Unlike the original article, most this code (except where explicitly mentioned) works on either PowerShell v2 with PowerBoots, or PowerShell 1.0 with PoshWPF, a snapin that is part of the PowerBoots module but is also released separately… Also, unlike those previous posts, this does not require you to be running PowerShell.exe with the -STA switch, since the New-BootsWindow cmdlet takes care of threading for us.

Read the rest of this entry »

So we found a problem recently with a certain scripting language’s argument parsing:


function Test-Argument($a) {
   $a.GetType().FullName
}

[Test 1]: Test-Argument 4
System.Int32
[Test 2]: Test-Argument .5
System.Double
[Test 3]: Test-Argument "hello"
System.String
[Test 4]: Test-Argument Goodbye
System.String
[Test 5]: Test-Argument -42
System.String
[Test 6]: Test-Argument (-42)
System.Int32
 

Why can’t it properly parse -42 as an integer, when it can parse .5 as a double? Well, according to the development team of a certain Fortune 100 company, this behavior is by-design ... Apparently, “.” can be a number, but “-” can’t.

When you know you’ve got it all wrong, but you can’t be bothered to get it right, document it — make it look intentional, and most people won’t question you.

I’m sorry folks, but I’ve had it up to here with the “it’s by design” excuse. I don’t care who you are, and I don’t care who wrote the design spec — when something is as obviously wrong as this, you need to fix it, not just give us platitudes.

I had the same thing happen recently with a bug I filed about the way wildcard behavior impedes matching file-names with square brackets in them in PowerShell. They told me this was by design, and that I could use the -LiteralPath parameter. Well, if any of you have tried this, you already know what I’m going to say: it’s broken.


## This works if the file already exists
## But fails completely if it doesn't exist
set-content -LiteralPath "logs [www.example.com].txt" -Value " help "
 

And yet, I was initially told it was supposed to be this way. Now, in this case, I happened to have the email address of the software architect, and they’ve reopened my bug after I sent him an email with lots of examples of how this bug defied the behavior that a user expects.

We software developers need to be very careful about saying “that’s by design” ... because it sometimes makes us sound stupid. When a user says “this is broken,” and your reply is “that’s by design,” what the user hears is “we broke it on purpose.” We should not be willing to excuse bad design.

Listen up: If you want to be a successful software developer, you need to learn this, and learn it well: the fact that it was DESIGNED WRONG is NOT AN EXCUSE for shipping broken software. Regardless of whether it’s your design, or someone else’s, even if it was designed this way by your manager’s boss. When you create software that doesn’t behave the way the user expects it to, you need to consider the possibility that you’re doing it wrong.

Imagine if architectural engineers were to behave in a similar manner … Suppose the original architect of the golden gate bridge had left a gap in the middle of the bridge, with a little ramp: you could drive up the bridge, but you couldn’t get across unless you were comfortable jumping your car across a four foot opening.

When you complained about it, the engineers would say: it’s by design — if you don’t like jumping your car (and yes, we know that jumping is bad for maintainability), there is a workaround: just wait for the ferry we put in last year. There are several boats, running continuously, so the wait is at maximum about 20 minutes, and it only takes a little longer to cross by boat than it would on the bridge.

That analogy is obviously not perfect, but the point is: just because someone decided it should be done a certain way doesn’t mean that’s the right thing to do — sometimes the design is just wrong. Perhaps the designer and architects overlooked something, or perhaps the circumstances have changed, but in any case, if the software doesn’t work the way people expect it to work, or requires different workarounds depending on the situation … you need to question the design.

All I’m asking is this: don’t turn your brain off: when someone complains about the way something works (or doesn’t work), think about what they’re asking, and if the complaint makes sense, don’t say “this misbehavior is by design” until you’ve reconsidered the design.

There are many desirable behaviors for Windows applications that are just much harder to do than they should be with the tools that Microsoft has provided in the .Net Framework. In WPF, many of these behaviors are even harder to create than in Windows Forms because the necessary hooks take a bit more work to write (thanks to the fact that there’s no window handles, so dropping down to “Native” code is harder. Luckily, WPF Attached Properties give us a whole new way to reuse these behaviors once they’re written.

I’ve started working on a few classes I’m calling NativeBehaviors, because they rely on intercepting the native Window Message processing, and I’ve put together a simple framework to let me write them, which I thought I would share. The first one I wrote is a SnapToBehavior, which implements a feature that people seem to be constantly re-implementing in apps. Basically, it makes a window snap to the screen edge when it gets close (and prevents them from being moved off-screen). I’ve also written a Global HotkeysBehavior which lets you register Hotkeys that work whenever your app is running (even if another app is active) so you can create a Hotkey to hide your app and show it, or whatever.

In the rest of this article I’ll show you how to achieve this in WPF using my base NativeBehavior class, and how to use it on a Window. Since some of you won’t really care how it works, let’s start with:

How to make your WPF Windows snap to screen edges in 3 easy steps:

Step 1. Add a reference to the Huddled.Wpf.Interop library.
Step 2. Add my Xml namespace to your root Window element
Step 3. Paste three lines from below….


<Window x:Class="GlobalHotkeys.DemoWindow" x:Name="DemoWindow"
   Title="GlobalHotkeys" Height="300" Width="300"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:huddled="http://schemas.huddledmasses.org/wpf"
   >
<!-- You just add a reference to the library, add the "huddled" namespace, and paste: -->
    <huddled:Native.Behaviors>
        <huddled:SnapToBehavior SnapDistance="20" />
    </huddled:Native.Behaviors>
<!-- The rest of your window can be whatever you like. -->
    <Grid>
        <Label Content="Drag this window near the screen edges"/>
    </Grid>
</Window>
 

I should point out the “SnapDistance” property of the SnapToBehavior is actually a WPF “Thickness” which lets you specify the distance from the screen edge as a single number to use on all sides, or as a separate number for each side: Left, Top, Right, Bottom. And that’s pretty much all there is to know.

How to implement a NativeBehavior.

The implementation of the SnapToBehavior is actually ridiculously simple, given the NativeBehavior framework. I simply created a SnapToBehavior class which derives from NativeBehavior, and implemented the single mandatory method:


/// <summary>
/// Gets the MessageMappings for this behavior:
/// A single mapping of a handler for WM_WINDOWPOSCHANGING.
/// </summary>
/// <returns>An enumerable collection of MessageMapping objects.</returns>
public override IEnumerable<MessageMapping> GetHandlers()
{
   yield return new MessageMapping(
      NativeMethods.WindowMessage.WindowPositionChanging, // the message
      OnPreviewPositionChange); // the delegate which will handle that message
}
 

When my new behavior is added to the Behaviors collection, my handler will be registered, and whenever the WM_WINDOWPOSCHANGING message arrives, it will be called. Now I defined a DependencyProperty for the SnapDistance, so that you could set that in XAML. It’s extremely simple, and VisualStudio has a built-in snippet for dependency properties, but here’s the code:


public static readonly DependencyProperty SnapDistanceProperty =
   DependencyProperty.Register(
      "SnapDistance",           // The name of the property (must match)
      typeof(Thickness),        // The type of the values
      typeof(SnapToBehavior),   // The type this property shows up on
      new UIPropertyMetadata(new Thickness(20)) // The default value
   );

public Thickness SnapDistance
{
   get { return (Thickness)GetValue(SnapDistanceProperty); }
   set { SetValue(SnapDistanceProperty, value); }
}
 

Once I have that, the last piece of the puzzle is to actually handle the window position changing message (think of it as an event, if you’re not used to Win32 message-based programming).

The basics of handling WM_WINDOWPOSCHANGING is that you get a structure passed in which has the proposed position of the Window, (including it’s z-index related to other apps) and you can basically tweak that however you like. Obviously there are lots of possibilities for this single message: always-on-bottom windows, undraggable windows, etc., but in our case we’re just concerned about how close we are to the edge.

We use the SystemParameters class to get the VirtualScreenLeft, VirtualScreenTop, and VirtualScreenWidth and VirtualScreenHeight which define the rectangle we’ll use for snapping. In the case of non-rectangular arrangements of multiple monitors this isn’t quite sufficient, but for our example anything more would be a distraction. Then we just check to see if the proposed position is within the “SnapDistance” of any of the edges, and if so, we change the position to be against the edge. That’s really all there is to it.

If you look at the code example below you’ll see I have to “Marshal” the WindowPosition structure in and out of an IntPtr which is passed in the WindowMessage … that’s the downside of intercepting window messages that the framework doesn’t already translate for us, but in this particular case, it’s actually fairly trivial.


/// <summary>lParam for WindowPositionChanging
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct WindowPosition
{
   public IntPtr Handle;
   public IntPtr HandleInsertAfter;
   public int Left;
   public int Top;
   public int Width;
   public int Height;
   public WindowPositionFlags Flags;

   public int Right { get { return Left + Width; } }
   public int Bottom { get { return Top + Height; } }
}  

      private IntPtr OnPreviewPositionChange(IntPtr wParam, IntPtr lParam, ref bool handled)
      {
         bool updated = false;
         var windowPosition = (NativeMethods.WindowPosition)Marshal.PtrToStructure(lParam, typeof(NativeMethods.WindowPosition));

         if ((windowPosition.Flags & NativeMethods.WindowPositionFlags.NoMove) == 0)
         {
            // If we use the WPF SystemParameters, these should be "Logical" pixels
            Rect validArea = new Rect(SystemParameters.VirtualScreenLeft,
                                      SystemParameters.VirtualScreenTop,
                                      SystemParameters.VirtualScreenWidth,
                                      SystemParameters.VirtualScreenHeight);

            Rect snapToBorder = new Rect(SystemParameters.VirtualScreenLeft + SnapDistance.Left,
                                     SystemParameters.VirtualScreenTop + SnapDistance.Top,
                                     SystemParameters.VirtualScreenWidth - (SnapDistance.Left + SnapDistance.Right),
                                     SystemParameters.VirtualScreenHeight - (SnapDistance.Top + SnapDistance.Bottom));

            // Enforce left boundary
            if (windowPosition.Left < snapToBorder.Left)
            {
               windowPosition.Left = (int)validArea.Left;
               updated = true;
            }

            // Enforce top boundary
            if (windowPosition.Top < snapToBorder.Y)
            {
               windowPosition.Top = (int)validArea.Top;
               updated = true;
            }

            // Enforce right boundary
            if (windowPosition.Right > snapToBorder.Right)
            {
               windowPosition.Left = (int)(validArea.Right - windowPosition.Width);
               updated = true;
            }

            // Enforce bottom boundary
            if (windowPosition.Bottom > snapToBorder.Bottom)
            {
               windowPosition.Top = (int)(validArea.Bottom - windowPosition.Height);
               updated = true;
            }

         }
         if (updated)
         {
            Marshal.StructureToPtr(windowPosition, lParam, true);
         }

         return IntPtr.Zero;
      }
 

Download it, or get the source code

If you’d like, you can download the current Huddled Interop for WPF library right now, or you can check out the source from CodePlex SVN or just download the most recent commit (You are only interested in the “Huddled” project which is in the “trunk”, not the “trunk-3.5”). The source is licensed freely under the BSD or GPL v2 (and a few other licenses, see the top of the source code files).

Either way you’ll get not just the SnapToBehavior but also the global HotkeysBehavior, and the Native Behaviors framework which I’ll write more about later, but for now, in case you want to try to use it, here’s an example using both the SnapTo and HotkeysBehavior (you can find this in the GlobalHotkeys demo project, which includes some sample code for handling hotkey conflicts). Enjoy.


<Window x:Class="GlobalHotkeys.DemoWindow" x:Name="window"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:huddled="http://schemas.huddledmasses.org/wpf"
   Title="Demo Window!" Height="300" Width="200"
   >
    <huddled:Native.Behaviors>
        <huddled:SnapToBehavior SnapDistance="80,20,80,10" />
        <huddled:HotkeysBehavior>
            <KeyBinding Command="huddled:GlobalCommands.ActivateWindow" Key="K"  Modifiers="Win" />
            <KeyBinding Command="huddled:GlobalCommands.CloseWindow"    Key="F4" Modifiers="Win" />
            <KeyBinding Command="huddled:GlobalCommands.ToggleWindow"   Key="S"  Modifiers="Win" />
        </huddled:HotkeysBehavior>
    </huddled:Native.Behaviors>
    <Grid>
        <Label Content="Drag this window near the screen edges"/>
    </Grid>
</Window>
 

So I’ve been asked to add a feature to one of the apps that I nominally took over when my former manager left … they want a management pane where certain authorized super users (to be decided later) can add data to the main lookup tables, and must be able to do clean up by deleting data which has been entered erroneously … including cleaning up any references to the now missing data.

I’m currently trying to figure out what database tables I need to be concerned with, and I just have to vent, because this system is the worst mess I’ve ever seen. [disgust]

  • There’s one database supporting five or more applications…
  • There are 87 tables (with names like tblAQ_DcSs, tblAQ_SwNw, tblSFM, and tblSW_PWSOS, tblTestCaseTestLayout )
  • There are three duplicate user tables: tblPeopleLookup, tblUser, and tblUser3 — tblUser2 is a view onto an external user database which is what is supposedly being used … and apparently, tblPeopleLookup is some sort of mapping from tblUser2 to tblUser3 … and tblUser1 is the original user table. I don’t know why these are all still here — I can only hope none of these others are still being used.
  • There are 144 stored procedures (with names like sp_Fix, sp_Fix2, sp_Fix3, spLeftToTestMulti, spLeftToTestMulti2, spLeftToTestMulti3, sp_Whatever, and the awesome spTestCaseTestLayoutTestsUpdate, spTestCaseTestLayoutTestsSelect, etc.)
  • There are no Foreign Keys. Yeah. None. [crazy]

Technically, there are lots of foreign keys — it’s just that none of them are declared as such, so there’s no referential integrity (did I mention that there’s an access database floating around out there with linked tables and a hard-coded login which the end-users pass around to each other so they can insert data into some of the tables by hand because the original developers didn’t get around to writing this management app that I’ve been asked to write now?)

You can tell that some of the columns should be Foreign Keys, because obviously a column in a “tblReq_Tag” table named “Feature_ID” must be an external lookup of some sort … but there’s 86 other tables … and at least two of them have Primary Keys called “Feature_ID” ...

So, I’m spending a lot of time searching the source code and the 144 stored procedures … An astonishing number of these stored procedures involve cursors and multiple nested case statements. I just picked one at random which I thought sounded simple: spEnterGroupResults ... it’s about 150 lines of SQL, and it uses a single cursor variable “crsUnit” which it redefines three separate times onto three different queries which it iterates over. Each of these queries involves joins onto nested subqueries, and I count myself lucky because the tricky part is actually enclosed in a transaction, and at least this one isn’t doing all of that just to dynamically generate a further SQL query to execute.

So yeah, I’m literally looking through source code to try to understand the database design. The problem is that there are more than five different applications, each using slightly different technologies.

  • One of them which has never been migrated from classic ASP ... with the business logic written entirely in Javascript, and the data handling performed entirely by sending huge XML files back and forth to a “do all” webservice.
  • One of them was written in VB.NET in VS 2003, and has never been upgraded.
  • The rest are in C# — with most in VS 2005, and at least one in VS 2008 and C# 3.0 — some are Asp.Net, some are rich client …

The tables I’m most concerned with right now (for this app) have some ahem ... impressive design decisions of their own. Of the 8 tables that I’m looking at directly (I think these are the only ones I need to modify as part of this app), five of them have multi-column primary keys that involve more than half the columns in the table, including columns which are, in fact, unconstrained foreign keys. And there are so far 5 foreign key looking columns which I haven’t been able to find the primary key column for … [pullhair]

[new] Edit: Oh yeah, and half of these tables have columns like [Enabled] [char](1) NULL … That’s a boolean value folks, stored in the database as a y or a n … and it’s nullable even though a null (or any value other than y or n, really) will most likely blow up some code somewhere. And no, there’s no script constraint or trigger to ensure that this doesn’t happen (I checked). For extra fun, the other half of the tables use ‘bit’ columns for things like this — because they were written after I started working with this team (on a different project) and happened across one of these char columns during our one and only code review ever and wondered aloud why we needed to pretend it was still 1992. Why they just switched, without changing the others, I’ll never know…

I have only one thing to say about coverflow.

The LOOK of coverflow, and it’s complete lack of integration into the LOOK of … well, anything else in finder, frankly…. just reminds me of Monty Python’s credits: “completed in an entirely different style at great expense and at the last minute.”

Search My Content