Archive

Archive for November, 2009

F# Webcasts

November 24, 2009 Leave a comment

F# is an interesting addition in Visual Studio 2010. I watched this excellent webcast series today from Tomas Petricek (to be honest I only watched part 3 and 4). I really liked his example of asynchronous workflows.

Categories: Uncategorized

Powershell syntax highlighting

November 23, 2009 Leave a comment

Just another small note on posting code snippets. This time for powershell scripts. Gaurhoth solved this problem nicely using his powershell to html syntax highlighting script, Get-SourceAsHTML.ps1. Great stuff. I just added “[Reflection.Assembly]::LoadFile( `’C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll’)` | out-null” at the top and it saved my day.

Categories: Uncategorized

Fun with powershell: Copy modified subversion files

November 23, 2009 Leave a comment

Sometimes it is nice beeing able to simply copy all the modified files to a backup directory when working with a larger changeset (even though diff/patch files does more or less the same thing I think this can be nice simply because the files are not crunched and packed into one single chunk). I wrote this little powershell script as an exercise:

# usage: copy-modified.ps1 c:\mysvnprj c:\backup
param([string]$source, [string]$target)

push-location $source

[xml]$x = svn st –xml
$files =$x.status.target.entry | select -expandproperty path | ? { test-path $_ -pathtype leaf }
foreach($fn in $files)
{
    $d = split-path $fn
    $f = split-path $fn -leaf
    $td = join-path $target $d
    if (!(test-path $td))
    {
       md $td | out-null
    }
    copy $fn $td
}

pop-location

Categories: Uncategorized

Free powershell book

November 21, 2009 Leave a comment

Master Powershell is a free book written by Tobias Weltner. It is not only free, it is good too. Go read it!

Categories: Uncategorized

WPF listbox grouping problem

November 21, 2009 1 comment

I had an interesting (and frustrating) problem with WPF the other day. A colleague of mine was using a simple lisbox to display a bunch of items and the sun was shining and the birds were singing…

A simplified version of the application is given below along with its xaml definition;

clip_image002

<Window x:Class="ListboxGrouping.SampleWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="SampleWindow" Height="300" Width="300">
    <Window.Resources>
        <CollectionViewSource x:Key="MyCVS" Source="{Binding MyItems}">
 
        </CollectionViewSource>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Source={StaticResource MyCVS}}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Margin="5">
                        <TextBlock Text="{Binding Name}" Margin="5"/>
                        <TextBlock Text="{Binding Status}" Margin="5"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>
 

The problem arose when my colleague started to try and group them by adding a group description and a group style: 

<Window x:Class="ListboxGrouping.SampleWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="SampleWindow" Height="300" Width="300">
    <Window.Resources>
        <CollectionViewSource x:Key="MyCVS" Source="{Binding MyItems}">
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="Status"/>
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Source={StaticResource MyCVS}}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Margin="5">
                        <TextBlock Text="{Binding Name}" Margin="5"/>
                        <TextBlock Text="{Binding Status}" Margin="5"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.GroupStyle>
                <GroupStyle>
                    <GroupStyle.HeaderTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Name}" FontWeight="Bold"/>
                        </DataTemplate>
                    </GroupStyle.HeaderTemplate>
                </GroupStyle>
            </ListBox.GroupStyle>
        </ListBox>
    </Grid>
</Window>
 

The result is displayed below (and it was not satisfactory…)

clip_image002[4]

Only the headers showed up and no items! What was going on? First I though we had some bug in our code since the real application had a lot of other things going on behind the scenes but after going through it for quite a few times I could not find anything strange. So, I extracted the code into a simple test application and, to my great disbelieves, the test application worked like a charm. Darn, something was lurking in the real application and I could not find it. I tried to google for other people having the same problem but no luck. After poking around for quite a while (including a lot of cursing, swearing and knocking my head against the wall) I finally realized that the real application was styled. The listbox was not really plain vanilla (god damn it!) – it was styled! After realizing this, the solution was just work. I extracted the standard control template for listbox by using the following helper code:

public static void Dump(Control ctrl)
{
    StringBuilder sb = new StringBuilder();
    using (TextWriter writer = new StringWriter(sb))
    {
        System.Windows.Markup.XamlWriter.Save(ctrl.Template, writer);
    }
    Debug.WriteLine(sb.ToString());
}

Then I could compare the standard listbox template to the template we were using. Our template looked something like below (which is very similar to a sample listbox template given on MSDN which also has the same problem):

<Style TargetType="{x:Type ListBox}">
    <Setter Property="SnapsToDevicePixels" Value="true"/>
    <Setter Property="Background" Value="{DynamicResource DarkWindowBackgroundBrush}"/>
    <Setter Property="BorderBrush" Value="{DynamicResource DarkSolidBorderBrush}"/>
    <Setter Property="Foreground" Value="{DynamicResource Silver}"/>
    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
    <Setter Property="ScrollViewer.CanContentScroll" Value="True"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBox}">
                <Grid>
                    <Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"/>
                    <ScrollViewer Margin="1" Focusable="false" Background="{TemplateBinding Background}">
 
                        <!-- The StackPanel is used to display the children by setting IsItemsHost to be True -->
                        <StackPanel Margin="2" IsItemsHost="true"/>
 
                    </ScrollViewer>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Background" Value="{DynamicResource DarkDisabledBackgroundBrush}" TargetName="Border"/>
                        <Setter Property="BorderBrush" Value="{DynamicResource DarkDisabledBorderBrush}" TargetName="Border"/>
                    </Trigger>
                    <Trigger Property="IsGrouping" Value="true">
                        <Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
 

I tried to mark the problem in bold letters. The custom template was using a simple stackpanel to display the items which worked fine as long as grouping was not enabled. The standard template, however, used an ItemsPresenter instead. Changing this closed the deal:

clip_image002[6]

Sweet! Wpf styling is powerful and like all powerful tools it can both rock your world and help you to shoot yourself in the foot.

Categories: Uncategorized

Uploading files to (and removing files from) Redmine using scripts

November 21, 2009 Leave a comment

At my work we are currently using Redmine and in particular we are using its wiki feature. Since we keep a lot of useful information on our wiki and since almost anyone that relates to our project have access to it, we though it would be nice to store the current release (nighly build) there too. Well, how hard can it be I though, asking my best friend google about it. It was not long until I found a guy who had solved the problem for me. He was using a python script to upload files to the redmine wiki. The script was leaning on a library called Mechanize and looked something like below:

import mechanize
import sys

if len(sys.argv) != 3:
  sys.exit("Usage: upload.py <directory> <filename>")
directory = sys.argv[1]
fileName = sys.argv[2]

url_fh = ‘http://redmine.corp.se/’
br = mechanize.Browser()
br.set_handle_robots(False)

# Fetching login page
page = br.open( url_fh + ‘login’ )

# Logging in
br.select_form( nr=1 )
br["username"]="buildagent¬-username"
br["password"]="buildagent-password"
#br["autologin"]=0
page = br.submit()

# Opening releases – New Files page…
page = br.open( url_fh + ‘projects/projectname/wiki/Releases’ )

# Registering the file
br.select_form( nr=1 )
#br["version_id"]= [ "44" ]
br.add_file( open( directory + fileName, ‘rb’ ), "binary", fileName )
page = br.submit()

Sweet! I installed python and mechanize on our build agent. Installing mechanize was not that straight forward as I had hoped (probably due to my lack of experience using python eggs etc) but that is another story. All was fine except that I was now uploading new files but never removing old ones. Well, someone must have solved that problem too I though, again turning to google for answers. However, this time I came back empty handed. Darn. Well, what can you do? I started poking around in the mechanize library trying to figure out how to write the script myself. The documentation was not giving me anything but luckily the source code was there and source code is also documentation, although slightly obfuscated. After a couple of attempts I came up with this solution:

import mechanize
import sys
import urllib, urllib2, time
from ClientForm import HTMLForm

url_fh = ‘http://sredmine.corp.se/’
br = mechanize.Browser()
br.set_handle_robots(False)

# Fetching login page
page = br.open( url_fh + ‘login’ )

# Logging in
br.select_form( nr=1 )
br["username"]=" buildagent¬-username"
br["password"]=" buildagent¬-password"
page = br.submit()

# Opening releases – New Files page…
page = br.open( url_fh + ‘projects/projectname/wiki/Releases’ )

# Remove files if above threshold value
msi_links = list(br.links(url_regex="destroy/\d"))
max_msi_links = 20
if len(msi_links) > max_msi_links:
    for i in range(len(msi_links)-max_msi_links):
       temp_link = "
http://redmine.corp.se" + msi_links[i].url      
       print "Removing " + temp_link
       try:
           br.form = HTMLForm(action=temp_link, method="POST")
           br.submit()
           br.refresh()
       except:
           # ignore exceptions, we always seems to get exceptions but the code works anyway.
           pass

Maybe not something that a python expert would be proud of but it certainly works and that was good enough for me. 

Categories: Uncategorized

Bloggs containing nicely formatted code

November 21, 2009 Leave a comment

This post is just an exercise for me. The purpose is simply to find a reasonably simple and nice looking way of posting code. So… this is a sample of some random c# code using the CopyAsHtml visual studio-addin available at the code project:

    1 using System;

    2 

    3 namespace GeneratorUtils

    4 {

    5     public class PropertyMetaData

    6     {

    7         public string Name { get; set; }

    8 

    9         public ClassMetaData Type { get; set; }

   10 

   11         public string TypeName { get; set; }

   12     }

   13 }

 

 

The indention did not work properly on wordpress. This is another random strip of python code:

import mechanize
import sys

if len(sys.argv) != 3:
  sys.exit("Usage: upload.py <directory> <filename>")
directory = sys.argv[1]

Allright, not too shabby.

Categories: Uncategorized