Tigraine

Daniel Hoelbling-Inzko talks about programming

The small things can cause the biggest troubles: List<T>.AddRange and GetHashCode

I just spent some hours performance optimizing an application I wrote a while back. The architecture was actually quite nice and I had implemented my own Lazy-Loading using DynamicProxy. Things worked great and performance was never an issue.

Fast forward 2 years: I left the company after the project was finished and development carried on. Additions to the code where made and after some time performance got a serious problem.

After hours of profiling I finally found the issue: Apparently List<T>.AddRange invokes GetHashCode on all items you add to the list.

Why is that a problem? Well: My Proxy objects where designed to return some key data that was eagerly fetched (stuff like Id, and some filter columns) and once the filter logic had narrowed down the list of thousands of items to the 2 or 3 that were going to be displayed, the Proxy transparently fetched the real data from the database and cached it. So every object in itself was doing a select once a method besides the prefetched data was requested.

I hadn’t thought of GetHashCode and any call to GetHashCode was not handled directly in the Proxy but caused a lazy load. And since .Add does not call GetHashCode but AddRange does, the bug never came up during development.

Imagine my face when I saw this profiler graph:

image

Needless to say that fetching 64 items from the database instead of 1 really brought the app down to a crawl.

Filed under net, programmierung

I&rsquo;m getting a new Virus Scanner

Just yesterday I was sitting around with some friends and telling them how great Microsoft Security Essentials works for me and how unobtrusive and easy to use this thing is. I’ve been using it for 3 years now on all of my machines and never had any reason to complain.

Until yesterday my CPU started running wild at 100%..

Noooooo[4]

I guess I have to consider myself lucky to be running Windows7 so the Trojan never managed to get full access to my system, doing stupid stuff like preventing me to access task manager or shutting me out of my system. That still didn’t prevent it from installing itself in my Registry for launch on System Startup (don’t ask how, as always I suspect I clicked one UAC dialog too many).

Well, here it is:

image

Obviously this is malicious code that is running when my system starts up. Nothing too malicious since it is not requesting Admin level privileges, but it’s still code that isn’t supposed to run and should be fairly easy to pick up.

Well Security Essentials doesn’t think so:

image

Even after a deep system scan of 6 hours, Security Essentials still mocks me:

image

Utterly unacceptable.

I still don’t have a clue how this got on my machine. I usually am pretty immune to stuff like that because I (on occasion) THINK while using my computer, and don’t click dialog boxes away without knowing what they were about. But somehow this thing seems to have made it past my usually pretty accurate instincts..

Damn, I really liked Security Essentials Sad smileAnd I really really really hate formatting my PC right now.

Update: I think I managed to kill this stupid virus. Since I’m just too lazy at the moment to pave my PC I’ll just keep an eye on this.

Filed under internet, personal

Powershell Functions are a different kind of beast!

When you look at functions in C style language there are some things always true:

  1. Return always terminates the function
  2. Return <something> returns a value/reference to the thing you return

Guess what: Powershell is no C style language! It may look like one with all the curly braces and the $ (reminding you of PHP) before variables. But it is no C language, rather it is a shell.. And shells seem to be working differently.

Care to hazard a guess what this will output?

function Test
{
    $a = "Hello World"
    "Sorry World is not available"
    return $a
}

$output = Test
Write-Host $output

If you’d expect it to return “Hello World” you are wrong. Actually the return value of the function Test is an array of 2 System.String:

Sorry World is not available Hello World

Madness I know. But fact is that all things that get written to the “output” (like Write-Host) inside a function is part of the function output. You don’t need to use return.

This also means if you run commands like –match inside a function

$v –match “regex”

–match will output true or false to the output. And thus your method output will include a True somewhere you don’t need it. Like this:

function Test
{
    $a = "Hello World"
    $a -match "World"
    return $matches[0]
}

$output = Test
Write-Host $output

Will output: True World

You can avoid this behavior through redirecting the “output” to $null or by adding the [void] attribute like this:

function Test
{
    $a = "Hello World"
    $a -match "World" > $null
    return $matches[0]
}

$output = Test
Write-Host $output

I never thought I’d have to revisit the workings of a return statement again, but obviously there is always the possibility for someone to come along and teach me something new. This person btw is Keith Hill who wrote an excellent article on Powershell Output that sheds some light on this topic and does a far better job at explaining it than I can possibly do.

Filed under programmierung

How to use different layout containers in WPF

WPF is different, that much I knew before I started learning it. But understanding really how different it is really takes a lot of time and effort. Especially when used to Windows Forms and HTML+CSS, WPF feels very alien in it’s way how to do layout. Here is what I learned:

StackPanel:

StackPanels are used to layout elements horizontally stacked onto each other.

image

By default the elements inside a StackPanel will take up their set height and you can make them fill the whole width by setting their VerticalAlignment to Stretch

They will however never fill the full height of the container when it is resized, no matter how your HorizontalAlign property is set. If the above container got resized in height the buttons would still stick to the top with their individual heights staying just the same.

WrapPanel:

They are the same as the StackPanel, just in vertical. They stack elements vertically and reorder them if there is no more space vertically. However they also don’t allow them to fill the vertical space available to the control.

image

The Dockpanel:

Where both WrapPanel and StackPanel don’t allow Elements to fill vertical space (even with HorizontalAlignment to Stretch) the DockPanel will do just that by default:

image

The trick here is that only the last child really fills the panel, so while resizing the height will resize all 3 buttons, a horizontal resize will only cause the third button to change size. This has to do with the LastChildFill property, where Button3 is considered the filling element.

Why am I telling you this? Well, turns out most UIs look something like this:

Some header, then one filling list that should resize and then some controls around the edges. Making the list resize with the parent container can’t be achieved by the other panels at all. You have to use a DockPanel and use the DockPanel.Dock attributes on your child controls:

<DockPanel Margin="0,0,0,0">
	<TextBlock DockPanel.Dock="Top" Text="Hello World" />
	<TextBlock DockPanel.Dock="Bottom" Text="Bottom" />
	<Button Content="Button3"></Button>
</DockPanel>

This will make the last element fill all available space left by the elements that where docked to the sides like this:

image

Once you understand these three layout concepts, you can build pretty much everything by nesting panels within each other. There is however also the GridPanel that lends itself very well to creating forms and other stuff that has to be aligned on a grid. But I won’t go into that in this post (and I think it’s markup is just awful. HTML4 tables were more intuitive to write)

Filed under net, programmierung, wpf

Good ideas worth spreading: SystemDateTime abstractions

I brought this example up a lot on this blog, but while looking at the code of Mark Nijhof yesterday I noticed a rather nice solution to my ongoing problem of abstracting away System.DateTime.Now calls for testing purposes.

As stated before: Don’t make your tests depend on external factors like the current time or Date, and I even had a solution until now that solved the problem rather nicely through a static factory that returns an instance to your DateProvider.
Why a global factory? Simple: having your IDateProvider be a mandatory dependency on all your objects and services will quite simply clutter up your design. IDateProvider is by no means a really important dependency, and modeling it the same way as say IImportantBusinessRule would not only require you to think about that DateTimeProvider in every test that you run against your object, but also reduce the readability of your constructors dramatically.

What I didn’t think about when writing my IDateProvider abstraction almost a year ago was that with C# 3.5 and lambdas, passing around a function is essentially the same as using a strategy class, but with a lot less ceremony. And obviously so thought Mark Nijhof when he wrote Fohjin (a very nice CQRS example you really should check out on GitHub).

public static class SystemDateTime
{
    public static Func<DateTime> Now = () => DateTime.Now;
    public static void Reset()
    {
        Now = () => DateTime.Now;
    }
}

So simple yet so elegant. In your tests you hardly have to think about this stuff, but if there is a test that depends on the date you can just go ahead and set it like this:

[Fact]
public void ctor_SetsDateAddedTo_CurrentDate()
{
    SystemDateTime.Now = () => DateTime.MaxValue;
    var orderLine = new OrderLine(TestData.Product, 1);

    Assert.Equal(DateTime.MaxValue, orderLine.DateAdded); }

It’s just a small touch, but it saves you 2 classes and still solves the problem nicely.

Git: Unstaging all changes and reset the working tree

When you commit something to git you first have to stage (add to the index) your changes. This means you have to git add all the files you want to have included in this commit before git considers them part of the commit. To some this added complexity feels like a burden, but to me it’s a blessing.

git working dir / index / repository diagram

Ever forgot that you just did 2 distinct features that really should be in 2 different commits? Well, just add the changes of the first feature, commit, repeat for the second commit and you have everything organized the way you want it to show up in your history.

But: You usually don’t do individual git add commands anyway, if you are anything like me you just hit git add –A (adding all changes in the working directory) and while writing the commit message you realize that there are two files that should not go into this commit. But how do you remove something from the index?

Since you used git add to put them in the index it would be logical to use git rm? Wrong! Git rm will simply delete the file and add the deletion to the index. Meet:

git reset

As with all things in git, git reset can be used in a number of ways. So here is the most common usage in day to day usage:

git reset : Clears your index, leaves your working directory untouched. (simply unstaging everything)

git reset --hard : Clears your index, reverts all changes in your working directory to the last commit. (the same thing as svn revert would do)

Filed under programmierung, git

Beware of &lt;Button IsDefault=&rdquo;True&rdquo;&gt; in WPF/Silverlight

I’ve spent the better part of my weekend finding this bug and thought I’d share it in case someone else is having the problem. I’m building a WPF user interface with a NServiceBus backend and started noticing that sometimes changing data on the client didn’t generate UPDATE statements in my Database. I first assumed it had to do with my backend code, then I started digging through the various libraries I am using (NHibernate and NServiceBus) to find the problem.

After 2 days debugging through the backend code I finally found out that it’s the WPF application that sometimes sent wrong data. The scenario is quite simple:

image

This very simple dialog uses a StringFormat to display the Price field. This prevents me from using any other binding than a UpdateSourceTrigger=”OnLostFocus” because otherwise it would reformat the field on every key-press. Rendering it unusable due to a jumping focus caret. 

The issue was that upon hitting Save, sometimes the Save method was executed before the data was bound to the model, sometimes the other way around. I genuinely thought I had a race condition until I noticed one little thing: Since it’s a decimal field I usually fill those in by using the number pad. That also led to me hitting the Enter quite often without thinking about it, thus invoking the Save method while still having the focus on the Price Textbox.

If you set a Button to IsDefault=”True” and hit Enter the Command will be executed without triggering the OnLostFocus Databindings in your Textbox, making your code act on stale model data. The only way around this is to either use UpdateSourceTrigger=”OnPropertyChanged” (not always applicable) or remove the IsDefault attribute from your form.

I still believe this is a bug in WPF, but at least now I know about it and can avoid it.

Filed under net, programmierung, wpf

Using Readability on the iPhone

Disclaimer: This is not a post about programming. No code was harmed during the creation of this blogpost.

As you may have guessed from the title, I got myself an iPhone4 some weeks ago and love it ever since. The browser in particular is great, yet sometimes even the best browser can’t change that a website is badly designed. Too often you can’t make the content out in between all the Google Adwords, the fonts are hideous or it’s a fixed width layout that’s way too wide.

On my PC I just hit the Readability bookmarklet and through magic all the ugly stuff goes away and only the content remains. Well, since Readability is just JavaScript you can do the same thing on the iPhone too, it’s just a bit trickier to install.

Here is how a badly readable site looks with Readability (note that it does not remove images that belong to the post!):

Before – After Readability

IMG_0119IMG_0121

As you can see, the width of the layout is too wide to be easily readable in portrait orientation.

Step 1: Go to http://lab.arc90.com/experiments/readability/ on your iPhone

Select all the text from the textbox on the right and copy it:

IMG_0114

Next, just hit add bookmark on the site and save the Readability site.
Now go into your bookmarks and edit the readability bookmark.

Delete the previous address and paste the code we copied earlier.

IMG_0117

Et voila, whenever you want to see a page clearer, just open that bookmark and it will convert any ugly site into a rather pleasant read.

Filed under internet, personal, tools

WPF FormatString and it&rsquo;s localization bugs

As some of you may know, I am from Austria. That means that I get to pay my bills in Euro and we format our decimals with a comma instead of a period (yes I know I’m weird).

So naturally my culture setting is de-AT and I really expect to see my decimals formatted this way: € 19,99
Turns out, WPF doesn’t give a damn and if you use FormatString in a binding it will just go ahead and return en-US formats!

<TextBox Text="{Binding Path=Model.Price, StringFormat=\{0:c\}}"/>

This is a bug in WPF and has been there for more than 2 years now from what I can gather. There is a fix to it as suggested by Nir Dobovizki, who coincidentally also has a pretty cool CheatSheet on WPF Databinding that I now have taped to the wall.

For the sake of completeness here is the code you have to put in your App startup code (I’ve thrown it in my App constructor):

FrameworkElement.LanguageProperty.OverrideMetadata(
    typeof(FrameworkElement), 
    new FrameworkPropertyMetadata(
        XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

While at it I also found out another pretty cool thing that managed to save me a lot of markup in XAML: MultiBinding! You can apply StringFormat to single elements through the {Binding} blocks, but sometimes you want to show stuff like “Showing Page x of y” somewhere.
My naïve approach was to just create 4 elements and bind 2 of them to the appropriate values. As Brian points out in his post on WPF StringFormat you can just do stuff like this:

<TextBlock VerticalAlignment="Center" Margin="0, 0, 0, 10">
    <TextBlock.Text>
        <MultiBinding StringFormat="Showing Page {0} of {1}">
            <Binding Path="CurrentPage" />
            <Binding Path="NumberOfPages" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

The StringFormat attribute works exactly like the String.Format method whereas the <Binding> children are the parameters passed into it. Pretty cool to say the least.

Now if only someone explained to me why WPF Grids have this hideous way of cluttering up my markup with Grid.Row=”0” Grid.Column=”1” I may finally make my peace with WPF (aka the display technology I stayed away until now because learning it seemed like an impossible task)

Filed under net, programmierung, wpf

Untangling the dependency ball! Windsor + NServiceBus + Caliburn + Fluent Nhibernate in one package

confusing-road-sign-large-web-view

Unfortunately nu is still falling short on one thing: Making sure that all the stuff you install is actually compatible with the other stuff you have already installed. There is a ticket for this and I’m fairly confident this will get resolved (please vote the ticket up), but for now I was back to figuring out what version of what framework to use to make my app compile.

As always, the main problem was Castle.Core, being present in 3 different versions. (NSB used version 1.1, Caliburn 1.2 and the latest Windsor release targets 2.5)

I decided to back down and use 1.2 since there is a NHibernate gem for 1.2 and a Windsor gem for 1.2. I’m now using NHibernate 3.0 alpha so think about using this “stack”.

Anyway, this is a collection of:

  1. NServiceBus 2.0 .NET 4 (2.0.0.1219)
  2. NServiceBus.ObjectBuilder.CastleWindsor
  3. Castle.Windsor (2.1)
  4. Caliburn 2.0 (still unreleased from the trunk)
  5. NHibernate 3.0.0.1002
  6. FluentNhibernate 1.1 (Updated to NHibernate 3.0)
  7. AutoMapper

Disclaimer: The whole thing is built for .NET 4.0 and works on my machine. Don’t blame me if it’s broken for you.

Anyway. You can download the whole package of libraries here: castle-stack.rar

My Photography business

Projects

dynamic css for .NET

Archives

more