Tech Tock

Time is of the essence.

Functional Homework

MejerTShirtAs I mentioned last month, I want to learn a functional programming language.  Lucky for me, Dr. Erik Meijer (and his electric t-shirt) gave a course on Haskell in October and its posted on Channel 9.

I watched the first lecture over a week ago but haven’t had time to do the homework till now.

Here it is in C#.  Its quicksort written as he described it in Haskell.  It doesn’t feel that different from the programming I usually do, but it is recursive (which I generally avoid), so maybe that’s something.  At least I did my homework, now I can go on to the second lecture :).

As long as I was making a program, I figured I’d expand my WPF horizons and used an attached behavior for the button.  Of course its MVVM which is just a habit now.

Attached Behaviors

It wasn’t obvious how to link the static attached behavior to the instance properly.

A guy on StackOverflow recommended getting the DataContext from the sender in the event:

private static void ButtonOnClick(object sender, RoutedEventArgs args)
{

var fxElem = sender as FrameworkElement;

var vm = (VM) ((FrameworkElement)args.OriginalSource).DataContext;

Most other explanations of attached behaviors are limited to working with the control itself and not the ViewModel:

http://eladm.wordpress.com/2009/04/02/attached-behavior/
http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

You can download the code here.

image

Here’s the homework code:

public  IEnumerable<IComparable>
    Sort(IEnumerable<IComparable> listToSort)
{
    if (listToSort == null)
        throw new InvalidOperationException
            ("Cannot sort a null list.");
    if (listToSort.Count() == 0)
        return listToSort;
    var result = new List<IComparable>();
    var start = listToSort.First();
    //smaller on left
    result.AddRange(Sort(listToSort.Skip(1)
        .Where(e => e.CompareTo(start) <= 0)));
    //val in middle
    result.Add(start);
    //larger on right
    result.AddRange(Sort(listToSort.Skip(1)
        .Where(e => e.CompareTo(start) > 0)));
    return result;
}

Here’s some highlights of the attached behavior class:

public static class SortStarter

{

// // RegisterAttached for attached behaviors

public static readonly DependencyProperty SortBehaviorProperty =

DependencyProperty.RegisterAttached(“SortBehavior”, typeof(bool), typeof(SortStarter), new UIPropertyMetadata(false, SortBehaviorChanged));

// Get/Set Methods for the attached behaviors:

public static bool GetSortBehavior(DependencyObject obj){

return (bool)obj.GetValue(SortBehaviorProperty);}

public static void SetSortBehavior(DependencyObject obj, bool value){

obj.SetValue(SortBehaviorProperty, value);}

// Method to hook the event

private static void SortBehaviorChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs args){

var button = dpo as ButtonBase;

if (button != null){

if ((bool) args.NewValue)

button.Click += ButtonOnClick;

else

button.Click -= ButtonOnClick;

}

// Button Click Handler:

private static void ButtonOnClick(object sender, RoutedEventArgs args){

// Don’t process calls from up the visual tree

if (!Object.ReferenceEquals(sender, args.OriginalSource))  return;

//get VM from DC

var fxElem = sender as FrameworkElement;

var vm = ((FrameworkElement) args.OriginalSource).DataContext as VM;

// process with VM and new Sorter class

}

Hooking up the button in XAML is simple:

<Window x:Class=”WpfApplication1.Window1″

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

xmlns:local=”clr-namespace:WpfApplication1″

Title=”Window1″ Height=”129″ Width=”300″>

<Button local:SortStarter.SortBehavior=”True” >Sort</Button>

December 26, 2009 Posted by | Uncategorized | , , , | 1 Comment

ThreadCount

I’m reading Concurrent Programming on Windows since everyone @Lab seems to know more about threading than I do.  Like most of the books I’ve been reading lately, this one weighs in at about 1,000 pages.  I’d recommend it for anyone who knows a bit about the concurrency infrastructure but wants to know it all.  Even so, there were some places where I felt a detail was missing, but 1,000 pages is plenty.

Here’s some interesting things I learned in the first couple hundred pages.

New threads in .Net will allocate 1MB for the stack on creation.

The total processor limit (including logical processors) of 32/64 in windows is mostly because of the CPU affinity mask which is 32 or 64 bits depending on windows version.  This paper (Windows Support for Hyper-Threading Technology) supports that statement for Windows 2003 server.  I can’t find a good reference to support this for Windows Server 2008.

The native (OS) limit for waitable objects (WaitForMultipleObjects) is 64, but .Net supports more.

December 24, 2009 Posted by | Uncategorized | , , , | Leave a comment

@Lab This Month

There was plenty going on at lab in the last few weeks, but hey, I’ve been busy too, so December gets a monthly installment.

Die Region Die

Very few of us like Visual Studio Regions.  A dozen spoke up within minutes when the topic came up.

This VS Macro was recommended to help control regions.

If you have any love for regions you’ll want this automagic regionator.

Using regions to organize by functionality instead of type of members or access modifiers got some support.  Also, using regions to hide boilerplate code like copyrights and imports sections could be acceptable to some.

WPF In Your Inbox

<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat=”Date: {0:MM/dd/yyyy}, Percent: {1:P}”>
<Binding Path=”BeginDate” />
<Binding Path=”Percent” />

</MultiBinding>

</TextBlock.Text>
</TextBlock>

This code was shared without comment a couple weeks ago and looking again now, I could have used it several times lately instead of the ugliness I committed.

Miscellany

Again charting came up and ChartFX was recommended for its rich features and stability.

TeamCity 5.0 adds Amazon EC2 cloud integration, boosts scalability and further enhances user experience.  Sounds good to me.

A Cloud Computing in Finance focus group is starting @Lab – I can’t wait till they hold a seminar.

Folks are trying out Google Wave.

Your abomination is my clever hack

This is getting a lot of discussion, but I haven’t had enough time so I’ve been willfully ignoring it, but constantly feel drawn to review it nonetheless – maybe over vacation. I’ll read up on it.

Hiring Continues @Lab

You may have noticed that financial companies are hiring.  On the one hand, I think they’re hiring like crazy and I’ve gotten a few recruiter emails each week lately – on the other, you can never tell with these recruiters.  I know people at companies that are hiring and companies that are still laying off.  Some companies are doing both at once.  Lab49 is Hiring, so if you’re a senior engineer just send your resume to jobs@lab49.com and tell them your read it here – hey couldn’t hurt, might help.

December Madness

December has been a bit too busy for me so I missed the UX Group Seminar and the .Net Meetup:(

Happy New Year

Can’t wait for the new year, when all us Lab Newbies will be taking 8 weeks of Finance 101. New projects are coming. And lots of new tech.

See you next year @Lab.

December 23, 2009 Posted by | Uncategorized | , , , , , , , , , | 1 Comment

Happy Holidays @Lab 12/4/09

PAR-T!

The highlight of the week was probably a highlight of the year.  An awesome Holiday party.  It looked like most of the NY office was there along with many spouses and significants.

image Lots of tech talk and geek speak.  I would wager Futurama is a company favorite.  I heard something unexpected: a female expounding on the humor of Zoidberg.

imageThe liquor was flowing so my wife was happy too (not a Futurama fan). I had as many as possible myself, which unfortunately is only 2.  Mojito was the preferred drink.  It’s too bad there’s no mixed drink sampler.  Most people, myself being the prime example, don’t know what’s out there or what they like…  Even this list wasn’t really much help.

imageCraft Bar is great.image The food was excellent.  I was surprised how much I liked the salmon.  Its not your regular salmon, it was more like a cross between lox and sashimi. Even after eating a ton of appetizers – fantastic.
image The appetizers were interesting and plentiful – every time I turned around there was something to try or retry. The bar was free flowing and as far as I could tell a good time was had by all.
imageAll that and iPod Nanos too.  The dinner was really awesome, so I was blown away by the gift.  Thanks Lab.

This is a beautiful device.  It plays and records audio, video and stills.  What’s not to love?

My wife and son keep asking for mine, but after playing with it a little, I want it.

Regular Stuff

image It seems not everyone is aware there are four Futurama movies.  They’re all awesome.  You should watch them.

It’s news to me that new Futurama episodes are coming in 2010.  Woo-Hoo!

image

Regular Stuff — Really

We’re still talking about testing.  Its getting very instructive with use cases and scenarios being hashed out.

Great laugh here.

Some idiot sent a support request to the whole company – more laughs ensued.

Lots of interest in (pivot) Grids for WPF.  I didn’t follow it too closely, but I got an honorable mention for my charting work as the subject expanded.

This post on diverse Software Engineering  topics seems to underpin everything we do and everything we’re talking about.

Soda Days are Toast

I just noticed that there’s an order of magnitude (probably 2) larger portion of water being drunk at Lab49 than soda.  I personally rarely drink soda.  I recommend the sparkling water which is always cold and refreshing in the fridge.  Wow, we’re just so health conscious.  :)

Regular Stuff

image

December 5, 2009 Posted by | Uncategorized | , , , , , , , , | 1 Comment

Insanely Cool Video Effects – In WPF!

Here’s a video on Channel 9 from last year showing the incredible things you can do with hardware accelerated graphics in WPF.  I found it totally awesome and was amazed by the incredible performance.

Here’s a textbox on a waving cloth.  I can see somebody doing something with a flag with this effect:

Here’s a 3D window.

I don’t know what the practical applications are in my line of work, but it sure is cool.

The original video includes some more effects that I would describe as more normal video effects such as morphing and color transforms, but with great performance and some extra goodies and it all seems to work with video.

December 4, 2009 Posted by | Uncategorized | , , , | Leave a comment

A Free Database You’ll Hate (At First?)

I’m doing a small project that could use some local caching persistence, so I picked my old buddy SQL Server.  SQL Server Compact Edition (SSCE, CE) to be precise.

I’m finding it to be SQL Server with all the fun removed.  At least it supports multiple database connections.  But there’s no database diagrams, you can’t make a PK clustered, and Linq2SQL refuses to make a diagram in Visual studio among other indignities.

You can’t even generate scripts from a Compact DB schema :(.  An MVP recommended this commercial utility (what, pay for a utility?) and the guy with all the points on StackOverflow got it wrong, Management Studio won’t let you generate a script for a Compact DB.  But the answer is down in the list of responses (the first time I saw a correct answer ignored on StackOverflow).  This CodePlex tool does a good job of scripting the database.  Its a convenient Management Studio plug-in.

Strange thing that the same MVP recommends the same company for making database diagrams in SSCE. My Spidey Sense is tingling.

Since the project is so small and the database part is so trivial, I can justify Linq2SQL even though its on its way out, but try to drag a table into a Linq2SQL dbml designer and Visual Studio complains:

image

Since my project only needs a couple quick and dirty tables and SQL Server any version is acceptable to the client, I’m going to forge ahead.

Since Visual Studio UI won’t create a Linq2SQL dbml for a SQLCE database, this blog, pointed me to SQLMetal.exe, which is included with Visual Studio 2008.  Why Visual Studio should be so picky is beyond me.

On the other hand I could use a typed dataset, which I’ve found brittle in the past and hardly as user friendly as Linq2SQL.  This is created automatically when you create a CE file database in Visual Studio.  No thanks.

the SQLMetal worked on the first try, so alls well that ends well.  Its easy to keep the command window open and just delete the dbml and rerun the SQLMetal command anytime you update the schema.

Once it was all setup I was back in Linq Heaven.

So, it seems the moral of this story is that with the right collection of utilities, SQL Server Compact Edition is a workable persistence store for a small application.

December 3, 2009 Posted by | Uncategorized | , , , , , , , , | Leave a comment

“Throwing exceptions can negatively impact performance” – Believe it.

I was parsing a ton of strings (don’t ask) and catching FormatException (a lot).  By a ton, I mean several hundred thousand parsed into dates and doubles. By a lot of exceptions, I mean 90% of the data was blank.  Let’s just call it sparse.  The process was taking about 30 seconds.  I changed the code to avoid the FormatException:

    if (!string.IsNullOrEmpty(value))
    {
        o = double.Parse(value);
    }

Performance improved by at least 10 times to under 3 seconds.  Problem solved.

Turns out this is a bona fide pattern.  The tester-doer pattern.

December 1, 2009 Posted by | Uncategorized | , , , , , , | 3 Comments

SlashDon’t. ComputerWhat?

This post on Slashdot completely mischaracterizes a PDC panel discussion.  The post seems to rely exclusively on this article from ComputerWorld which also has a questionable slant on the session.  I was even taken in by this misinformation.

The CW Headline was:

Microsoft’s top developers prefer old-school coding methods

The Slashdot Headline was more pointed: 

Microsoft’s Top Devs Don’t Seem To Like Own Tools

You can watch the session and decide for yourself here.

I watched the session and thoroughly enjoyed it.  Here’s my rebuttal.  Times for the quotes are in parenthesis.

I would agree with CW that the panel was “often humorous”.  With the intro question “What problem is the most important that we face today”.  Don Box said with a wide grin (3:20):

I spend every night wondering how I’m going to make developers fall in love with the database.  There’s man-millennia worth of value in there that we keep wanting to put a prophylactic over so that we don’t get tainted by it.

This great Jim Gray quote related by Butler Lampson (7:50):

Transactions are like fairy dust.  A Cobol programmer writes a piece of business logic.  Its a sequential program, it does some relatively simple state transformation, and then you sprinkle transaction fairy dust on it, and automatically it becomes parallel, it becomes fault tolerant, and it becomes load balanced.

Jeffrey Snover had the audience in stitches unintentionally when he said (10:50):

Software tends to work when it works and fail when it fails.

Butler Lampson (26:16): “The net contribution of RPC to human welfare has been negative.”

Jeffrey Snover’s quote on managed code was much in favor (40:00):

Managed code is like antilock brakes. You used to have to be a good driver on ice or you would die. Now you don’t have to pump your brakes anymore.

Though when you read the slash/world articles it seems like he’s against it.  Like most people he’d rather drive faster with less risk of dying.  Or code faster with less risk of crashing. He’s not some old coot saying kids today have it too easy.

There were lengthy conversations on transactions, memory management, pointers, parallel programming, state, reliability, expression trees, etc.

When the text topic was introduced Don Box declared “Text f***g rocks!” in exaggerated glee (51:38).

The quote that CW latched onto was from Jeffrey Snover (53:20):

Graphical programming environments are usable when they are useless, but unusable when they would be useful…  When there are five things on the screen, you can burp that out [in text]. But when there are 500 things, [graphical programming] is completely unusable. You zoom in and zoom out and you lose all context. I think it’s just smokin’ dope.

He’s not running down Microsoft tools here, he’s dishing on all Graphical Programming tools.  Funny enough, WPF in Visual Studio has the least usable graphical environment, but the best text environment for creating graphics since the UI is defined in XAML, a type of xml like html and the IDE gives a lot of help when editing the XAML and the graphical representation updates as you edit the text.  Working directly with the graphics is near impossible, but that’s ok since building graphics with text is quite workable.  I don’t know any tool that can really help you with 500 graphical elements.

While this was a joke from Snover as noted by CW:

programming is getting so abstract, developers will soon have to use Microsoft’s in-air motion sensor game controller for the Xbox, dubbed Project Natal, to “write programs through interpretative dance.”

It was not an offhand joke or part of the conversation.  It was in response to the question “What do you think we’ll be talking about in 5 – 10 years.” (57:20)  In context it’s still funny, but makes a lot more sense.

I think the entire session went over the head of the reporter for CW.

December 1, 2009 Posted by | Uncategorized | , , , | Leave a comment

   

Follow

Get every new post delivered to your Inbox.