DCSIMG
October 2009 - Posts - Technicals and Technicalities

Technicals and Technicalities

Ariel's uneditable Bliki

October 2009 - Posts

A Locked File is Killing the Build

I read a nice post by Ron Gross (thanks for sharing, Ken) about how a file locked by the System process screws up a build.

I have only one thing to say to that:

What?! Only one file?!?

 

I’m a big FinalBuilder fan, and my build/deployment scripts usually have countermeasures for that sort of build-wrecking scenarios.

DepScript

Above is a short snippet out of a deployment script I wrote (those actions are part of the uninstallation of a previous version). After performing the mundane action of “stop the service” – we continue to the extremes: kill the process in case it decided to mutiny, kill all open file handles, kill all MMC session (which could screw up a service uninstallation) and so on, and so forth.

All these tasks are based on the wonderful PsTools by SysInternals, and provided out of the box as FinalBuilder actions.

Resharper 5.0! Hurrah!

http://blogs.jetbrains.com/dotnet/2009/10/resharper-50-overview/

 

Except for the ASP features (which I literally didn’t even skim through) - just about very new feature made me giggle with joy.

 

I think I can no longer live without the new 5.0 features, and I haven’t even tried them.

PCEH Invoker

(I just love Resharper’s CamelHumps.)

PCEH, if you’re lacking in the Resharper department (and/or don’t use WPF) is PropertyChangedEventHandler, and the simple invoker allows you to write cool code like this:

PropertyChanged.InvokeIfNeededX(sender, () => MyDataBoundProperty);

 

A simple extension method for PropertyChangedEventHandler class, and you get a wonderful syntax for safe invocations. Code below:

 

using System.Linq.Expressions;
namespace System.ComponentModel
{
    public static class PropertyChangedEventHandlerExtensions
    {
        public static void InvokeIfNeededX<T>(this PropertyChangedEventHandler source, object sender, Expression<Func<T>> prop)
        {
            if (source != null)
            {
                source(sender, new PropertyChangedEventArgs(GetName(prop)));
            }
        }
 
        private static string GetName<T>(Expression<Func<T>> expression)
        {
            var member = expression.Body as MemberExpression;
            if (member == null)
            {
                throw new ApplicationException("Cannot handle expression of type " + expression.GetType());
            }
 
            return member.Member.Name;
        }
    }
}

Unit Tests as a Performance Benchmark. And Then What?

I’ve noticed a pattern with me – often, when I need to do some performance optimizations – I start off by using my “create unit test” Resharper template, writing the to-be-optimized code in a stopwatch block in it, and using TestDriven.Net to run it a couple of time to see if the time measurements are consistent.

Then I’m off to optimizing, and checking the optimization helped, and having coffee, and re-optimizing and refactoring and whatnot. Life’s great.

Then I’m done.

But I have a perfectly good performance test all written, just orphaned of an assertion…

 

I don’t really have a suggestion here. I know that just adding an assert on the time it took it a bit problematic, because tests can run on an assortment of environments (hardware+software) and in an assortment of scenarios (right after a boot or during Office2007SP2 install), so they might fail “randomly”.

I usually just comment out the code, feel bad about that, and a couple of months later delete it. Oh ,and feel bad about that, too.

 

So, readers, have you got any ideas?

Build a Better Accordion (Someone? Please?)

I’ve realized I needed an Accordion control for my WPF application. Implementing one seemed like a hassle, so I’ve looked for one. Amazingly, I have found that Silverlight has one, but WPF does not. Moreover – all the major control vendors don’t have such a control. Strange.

Btw, if you do come across one – do let me know.

 

Then I’ve stumbled upon this blog post about a lightweight implementation for an accordion, based on a StackPanel with Expanders as children.

The accordion had one flaw – it didn’t resize the children when it was resized, only when one of them expanded.

Ariel’s Ugly hack: resize them on the MeasureOverride() method. Problem solved.

I hate myself.

 

So, if you also need an Accordion control and want to hate yourself (or me!) – here’s the code.

 

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
 
namespace TestGen2.UI.UIInfra
{
    public class Accordion: StackPanel
    {
        private const string ExpandSiteName = "ExpandSite";
        private const string HeaderSiteName = "HeaderSite";
 
        static Accordion()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(Accordion), new FrameworkPropertyMetadata(typeof(Accordion)));
        }
 
        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);
            InitializeAccordion();
        }
 
        private void InitializeAccordion()
        {
            foreach (Expander childExpender in Children.OfType<Expander>())
            {
                childExpender.Expanded += ChildExpanded;
            }
        }
 
        private double _PreviousHeight;
        protected override Size MeasureOverride(Size constraint)
        {
            var returnedSize = base.MeasureOverride(constraint);
 
            if (constraint.Height == _PreviousHeight)
            {
                return returnedSize;
            }
            _PreviousHeight = constraint.Height;
 
            var expandedExpander = Children.OfType<Expander>().Where(x => x.IsExpanded).FirstOrDefault();
            if (expandedExpander != null)
            {
                double totalCollapsedExpandersHeight = Children.OfType<Expander>().Where(x => !x.IsExpanded).Sum(x => x.ActualHeight);
                double accordionHeight = constraint.Height;
                var expanderContentPresenter =
                    (ContentPresenter)(expandedExpander.Template.FindName(ExpandSiteName, expandedExpander));
                var header = (FrameworkElement)(expandedExpander.Template.FindName(HeaderSiteName, expandedExpander));
 
                expanderContentPresenter.Height = Math.Max(0, 
                    accordionHeight - totalCollapsedExpandersHeight - 
                    (header.ActualHeight + header.Margin.Top + header.Margin.Bottom +
                    expandedExpander.BorderThickness.Top + expandedExpander.BorderThickness.Bottom));
            }
 
            return returnedSize;
        }
    
        private void ChildExpanded(object sender, RoutedEventArgs e)
        {
            var selectedExpander = e.Source as Expander;
 
            if (selectedExpander == null || !Children.OfType<Expander>().Contains(selectedExpander))
            {
                return;
            }
 
            double totalExpanderHeight = 0;
            foreach (Expander otherExpander in Children.OfType<Expander>())
            {
                if (otherExpander == selectedExpander)
                {
                    continue;
                }
 
                if (otherExpander.IsExpanded)
                {
                    var contentPresenter = otherExpander.Template.FindName(ExpandSiteName, otherExpander) as ContentPresenter;
                    if(contentPresenter != null)
                    {
                        totalExpanderHeight -= contentPresenter.ActualHeight;
                    }
                    otherExpander.IsExpanded = false;
                }
                totalExpanderHeight += otherExpander.ActualHeight;
            }
 
            if (selectedExpander.IsExpanded)
            {
                var contentPresenter = selectedExpander.Template.FindName(ExpandSiteName, selectedExpander) as ContentPresenter;
                if(contentPresenter != null)
                {
                    contentPresenter.Height = ActualHeight - totalExpanderHeight - selectedExpander.ActualHeight;
                }
            }
        }
    }
}

Extension Methods Coding Convention

Hey there. Me again. That annoying overexcitable programmer. An I sill LOVE Extension methods.

For the past couple of months I’ve experimented with a convention of placing the static class which declares an extension method in the same namespace as the extended type. I didn’t like having to look for extension methods when I wanted to use them (and even Resharpers “Add using” was less than perfect with extension methods). The fact is - if you have an extension – you need to be able to access it with ease. And what’s easier than always having it in Intellisense, just like any other method?

I’ve bounced this idea off my Israel Alt.Net peers, and Amir has noted that this is not future-proof, because someone could add a similarly-named method to the type, and on the next re-compile – invocations will go to it. If the methods would have been declared at another NS – at least I would have gotten a “redundant Using statement” warning from Resharper, and try to find out why.

1) What’s the deal with this lenient compiler? Why is this legal? Throw some compilation errors my way!

2) He’s right.

 

So I’ve come up with a naming standard that all extension methods will end with an X: the classic “string.IsNullOrEmpty(stringInstance)” will be “stringInstance.IsNullOrEmptyX()”.

This will solve the possible future naming conflict, allow me to declare extension methods in the same NS, and still wouldn’t really bother me when typing the methods name (since it is just a suffix).

I said I will try it out for a while and then decide.

 

A while passed and I like it.

 

The reflex-comment about “Hungarian notations are evil” bounces right off me. I think in this case – the fact that I know that some method is an extension does actually help me. Reading code (without an accessible F12 key) could be confusing if you see a method that “you don’t remember ever seeing before on that type”.

One exception to the rule could be extension methods for System.Object. I would not add those extension methods under System, because then they would affect everything. Even if you wrote a perfectly useful method (I had fun with a myObj.GetPrivateField<T>(“_MyField”) method once) – this would cause too much clutter for everyone else. This is the sort of method I would keep in the standard “YourProject.Infra.Extensions” namespace.

An exception to that exception is, of course, if you have a limited scope to begin with – this would not clutter anything: say you have (borrowed from SpecUnit) and assertion method like “myObj.ShouldNotBeNull()” – you could still declare it under System (in your tests project), because it will only be seen in the tests project, where it’s logical to have it everywhere.

Debug without a Debugger

Developer, know thy environment!

If you develop software and don’t have TaskManager (or some other CPU indicator) minimized at your task tray – you’re missing out. If you have the feeling that “whenever something goes wrong with your app – you’ll know and then debug it” – you’re just wrong.

taskMgr 

We need all the data you need, to save time on finding the bugs and performance issues. This trivial little 16X16 icon can tell you so much about your app – it’s amazing. When does you app spike in CPU? Does it have a constant “CPU overhead”? Does your normal environment have such overhead? When your app should be in 100% cpu – does it take less? Does it take exactly 50% (only one core is at full CPU, other is almost idle)?

Those questions are answered without even having to ask them.

And that’s just that lame TaskManager. Heard about ProcessExplorer?

A lot was said about this wonderful application, and I won’t glorify it further, other than to say that it’s probably the first thing I download and run on a new machine.

Now, as a developer – you should know the ins and outs of ProcessExplorer; again – for the information you can get. I/O graph and memory usage and physical memory usage, all at the tips of your task tray. This is how I work:

procExp 

You get the CPU graph (history, actually); memory commit history; I/O history and Physical memory usage history.

Well, actually, this is how I work:

DUMeter

The transparent graph is DUMeter, an application which monitors my network. I’ve used it for so long that I can’t properly work on a machine without it floating there.

 

//----- Part two

 

Now, the real gains you get form ProcessExplorer are the ever so simple readings you get on a managed app. The CLR exposes lots of performance counters, and ProcExp just collects them all in a great, readable format.

image

Periodically – look at the amount of exceptions in you app. Maybe it’ll surprise you. Look at the amount of marshaling. Look at the Managed Heaps. Maybe something’s off. Just look.

image

Btw, running on Vista and up, you may need to run ProcExp as Admin to see the .Net tab. You can re-launch it as admin right from the File menu:

RunAsProcExp