Mr Andersson

Posts Tagged ‘.net

WordWrap function in c#

leave a comment »

Today I worked on a piece of code at RemoteX and needed a pretty simple word wrapping function in C# which:
1) breaks between words, if possible
2) breaks words, if they’re too long to fit on one line

I used the almighty code snippet resource but couldn’t find a quick fix for my need without digging further into the different solutions, so here is my contribution to the long list of word-wrapping functions posted around the web.
Just like I tried to use several of the code snippets I found on the web, you are free to use mine.

I take no responsibility for any bugs you may find in this code snippet may include. Please let the tests guide you!

https://github.com/anderssonjohan/snippets/blob/master/wordwrap/WordWrapTests.cs

Written by anderssonjohan

November 3, 2010 at 12:51

Posted in programming

Tagged with ,

Deploying applications to Windows and Windows Phones which supports dynamic modules

leave a comment »

Many .Net applications being developed today are leveraging the greatness of dependency injection using some sort of inversion of control-container. So do we at RemoteX when we develop the product called RemoteX Applications. The product has two client applications which roughly adresses the same use cases. One is targeting desktop computers and the other one is targeting Windows Phone (you can read more here and here).

As you can tell by the name, the product consists of several applications (or rather modules). Using frameworks like Prism or Caliburn we can, in code, easily manage each part of the product. And the deployment is taken care of using ClickOnce technology using mage.exe (the MAnifest GEnerator).
But that’s for the desktop client targeting WPF.

So the big question is, how are we going mobile with this?

What regards an inversion of control-container we are “almost there”. We have a home-grown container in place which have been around for a while now, even though it lacks some basic features you would expect an ioc container of year MMX to have.
Speaking of deployment to the Windows Phone you probably know you are kind of locked to using CABinet files. If you are using the tools Microsoft brought to us, you probably also use their Device Setup projects in Visual Studio.
They are good, but you must use Visual Studio to choose the contents of and create/build your CAB file.
What this basically means is that we need to use devenv.exe to build each customer’s customized CAB file.
So up til now we have not had per customer customized CAB files.

All I wanted was ClickOnce technology and a manifest generator for the Windows Phone. So what’s the solution on that?
Say hello to the PowerShell script New-CabWizInf.ps1:

.\New-CabWizInf.ps1 -path .\myapp.inf -appName “My Application” -manufacturer “RemoteX” -fromDirectory .\MyApplication\bin\Release

It works like mage.exe with its -fromDirectory switch and creates the necessary .inf-file (like an Visual Studio Device Setup project would). All needed from that point is to call CABWIZ.exe and Set-AuthenticodeSignature in PowerShell to create and sign the CAB file.
The real power is the -fromDirectory switch which allows us to create custom CAB files on the fly.

So here is a peek of what our setup package scripts now looks like:

Setup Package for Windows using ClickOnce
mage -new deployment -tofile MyApp.application -fromdirectory bin\Release -name “My App” -publisher “RemoteX”
mage -sign

Setup Package for Windows Phones using CAB files
.\New-CabWizInf.ps1 -path MyApp.inf -fromDirectory bin\Release -appName “My App” -manufacturer “RemoteX”
cabwiz MyApp.inf /dest .\
Set-AuthenticodeSignature .\MyApp.CAB

So right now I’m a very happy camper since our packaging tools for Windows AND Windows Phone have equal capabilities which allows us to use dependency injection with dynamic module selection.

Next stop, Prism and Silverlight for the Windows Phone?

Written by anderssonjohan

January 20, 2010 at 23:28

Posted in software

Tagged with , , , , ,

Switching component implementations in Castle Windsor

leave a comment »

Problem: Test suite for a system for which I need to replace (inject) the behavior of a certain component. The system is using Castle Windsor with an XML configuration file.

In this system integration test I want to use the real container configuration except that I want to switch out a component that does authorization using a database.

The replacement for the real component is as simple as:


public bool IUsernamePasswordVerifier.VerifyPasswordFor( string username, string password )
{
return true;
}
Solution: Tried this, which failed on me. But with a little help from a tiny facility used by the test suite I can now “re-wire” service implementations in the container.
There are probably several other solutions on how one could accomplish the same thing, but this one worked out very well for me.

ComponentRewriterFacility.cs:


using System;
using System.Collections.Generic;
using Castle.Core;
using Castle.Core.Configuration;
using Castle.MicroKernel;

namespace ServiceTests.Service
{
public class ComponentRewriteFacility : IFacility
{
readonly IDictionary<Type, Type> _rewrites;

public ComponentRewriteFacility()
{
_rewrites = new Dictionary<Type, Type>();
}

public void AddRewrite<I, T>() where T : I
{
_rewrites.Add( typeof(I), typeof(T) );
}

public virtual void Init( IKernel kernel, IConfiguration facilityConfig )
{
if( kernel == null )
throw new ArgumentNullException( "kernel" );
kernel.ComponentRegistered += ComponentRegistered;
}

public void Terminate()
{
}

void ComponentRegistered( string key, IHandler handler )
{
if( !ShouldRewrite( handler.ComponentModel ) )
return;
handler.ComponentModel.Implementation = _rewrites[handler.ComponentModel.Service];
}

protected virtual bool ShouldRewrite( ComponentModel componentModel )
{
return _rewrites.ContainsKey( componentModel.Service );
}
}
}

And in our test suite initializer we add the “re-write rule” like this:


IWindsorContainer container = new WindsorContainer();
container.AddFacility<ComponentRewriteFacility>( f => f.AddRewrite<IUsernamePasswordVerifier, AnythingGoesUsernamePasswordVerifier>() );
container.AddFacility<WcfFacility>();
container.Install( Castle.Windsor.Installer.Configuration.FromXmlFile( "Windsor.xml" ) );

Like it? Not? Have a better solution? Please let me know!

Written by anderssonjohan

October 28, 2009 at 19:34

Posted in programming

Tagged with , , , ,

Castle Windsor 2.0 RTMed

leave a comment »

Oh yeah! Castle Windsor 2.0 is RTMed!

I just can’t wait ’til we upgrade RemoteX Applications.

Written by anderssonjohan

May 5, 2009 at 12:05

Posted in programming

Tagged with , ,

How To Make the Firefox/YouTube Wait Symbol In WPF

with 2 comments

Recently I thought about doing one of those trendy animated “hour glasses”, the “wait” symbol which appears when that computer of yours is waiting or working on stuff in the background.

So what do I mean by “doing one”.. In HTML? with jQuery UI perhaps? No and no.

About 3-4 months ago we started to get WPF into production in our product at work and now we’re doing all our new features based on WPF and XAML.
So this animated “hour glass” (or “spinner” which is the word I will use from here) must of course be created in WPF.

I believe that you guys and girls out there who have worked with XAML, since the spec came out in 2006, probably just say “Say hi to XAML, my friend”. For me however, I’m quite proud of how easy it was for me to create this animated little thing.

When I brought this up during lunch a couple of days ago I discussed what the least CPU consumtive design would be.
My first design thought I came up with was based on 8 circles with ColorAnimations which would make the circles look like the were rotating.
After a quick discussion with my fellow collegues Morten and Wilhelm I got interested about the idea of using a rotating (using RenderTransform) Canvas instead. This idea worked out very well and here is the result (you must have .Net installed to view it in your browser).

So the XAML required to achieve this is quite simple, here is a summary:

  1. A Canvas is used to distribute the 8 circles on
  2. Each circle has its fixed position and its own transparency (which makes the “tail” effect)
  3. We add a trigger to the FrameworkElement.Loaded event for the Canvas, in which we…
  4. …add a DoubleAnimation targeting the Angle property of the RotateTransform we also added to the Canvas
  5. We use a ViewBox as the parent of the Canvas which lets us scale the animation to fit in i.e. a TabPage header control (like the tabs in Firefox)

And here is the XAML:


<Viewbox>
<Canvas Width="80" Height="80" Name="canvas">
<Canvas.RenderTransform>
<RotateTransform Angle="0" CenterX="40" CenterY="40" />
</Canvas.RenderTransform>
<Canvas.Triggers>

<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="canvas"
Storyboard.TargetProperty="(Canvas.RenderTransform).(RotateTransform.Angle)"
To="360"
Duration="0:0:0.7"
RepeatBehavior="Forever"/>
</Storyboard>

</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Canvas.Triggers>
<Ellipse Canvas.Top="0" Canvas.Left="30" Width="20" Height="20" Fill="#08000000"/>
<Ellipse Canvas.Top="10" Canvas.Left="50" Width="20" Height="20" Fill="#15000000"/>

<Ellipse Canvas.Top="30" Canvas.Left="60" Width="20" Height="20" Fill="#38000000"/>
<Ellipse Canvas.Top="50" Canvas.Left="50" Width="20" Height="20" Fill="#55000000"/>
<Ellipse Canvas.Top="60" Canvas.Left="30" Width="20" Height="20" Fill="#88000000"/>
<Ellipse Canvas.Top="50" Canvas.Left="10" Width="20" Height="20" Fill="#aa000000"/>
<Ellipse Canvas.Top="30" Canvas.Left="0" Width="20" Height="20" Fill="#cc000000"/>
<Ellipse Canvas.Top="10" Canvas.Left="10" Width="20" Height="20" Fill="#ff000000"/>

</Canvas>
</Viewbox>

Pretty easy, or what do you think?

Written by anderssonjohan

March 12, 2009 at 21:00

Posted in programming

Tagged with ,

A fluent interface and the Builder pattern

leave a comment »

My former collegue Thomas Lundström blogged about fluent interfaces quite a while ago, which he followed up in a comment to Johan Lindfors’ post “A small DSL to order coffee” (in Swedish).

The blog post and its comments discusses two different approaches to fluent interfaces. The first approach is based on getters which mutates the instance when they are called. Some people think this is a very bad design – getters should not mutate the instance!
I agree on that. I strongly believe that a get operation should be idempotent and not mutate the object instance. This for the same reason a HTTP GET request should not mutate a resource and a HTTP POST/PUT should mutate a collection/the resource.
(That’s why I prefer RESTful web services more than SOAP over HTTP, but that’s a totally different blog post. 🙂

The second approach is the one that Thomas points out. It’s the classical Builder Pattern where you have a totally separate class which is used to build object instances. It differentiates itself among the creational OOD design patterns by targeting primarily mutable objects. It’s like a bunch of Factory methods which is used like a Factory, but instead of having thousands of different methods in one Factory (overloads for example), the Builder is used in several calls to create/configure the final object instance.

An approach which was recently used at work is a mix of the two approaches mentioned above. Instead of having a separate builder we have builder methods on the object instance itself, either directly or via extension methods. Separate from the builder methods we got some Factory Methods. These are the starting point to create a basic instance. The builder methods are then used to further shape the object instance to our needs.

Approach #1 – getters which creates/mutate the object instace:


Coffee myLatte = Coffee.OrderLatte.Double.FatFree.Vanilla;

Approach #2 – a separate builder


Coffee myLatte = CoffeeBuilder.Latte().Double().FatFree().Vanilla().Build();

Our approach – a mix of factory methods and builder methods on the object instance itself


Coffee myLatte = Coffee.Latte().Double().FatFree().Vanilla();

So what’s the pros and cons with the last two approaches?
I guess they are quite similar, but here is some pros:
– The separate builder seems a bit more aligned with the Separation Of Concerns principle
– The built-in builder methods via extension methods provides a lightweight class structure, even for classes in a third-party class library, such as the BCL.

(Please post a comment if you can think of more pros and cons or if you just totally disagree with me 🙂

So of course, the $10.000 question answer is… It depends on your context!
Anyhow, here is a sample how we tend to use this mix of Factory Methods and Builder methods at work.

The following code is used to build construct the collection of DataGridViewColumns used in a Windows Forms DataGridView control.
The CreateColumns() method is used to create an enumeration of the columns to use and TextColumn() is a sample Factory Method.


protected override IEnumerable CreateColumns()
{
yield return TextColumn()
.For( WorkOrderPresenter.Properties.Title )
.WeightedWidth( 100 );

yield return TextColumn()
.For( WorkOrderPresenter.Properties.Description )
.WeightedWidth( 200 );

yield return ComboBoxColumn( _activityBindingSource )
.For( WorkOrderPresenter.Properties.Activity )
.WeightedWidth( 100 )
.Width( 90, 130 );
....
}

///
/// Creates a textbox column with default behavior.
///

protected virtual DataGridViewTextBoxColumn TextColumn()
{
return new DataGridViewTextBoxColumn().WrapContents().WithDefaultBehavior();
}

The methods For(), WeightedWidth(), Width(), WrapContents() and WithDefaultBehavior() are Builder (extension) methods on DataGridViewColumn.

Written by anderssonjohan

March 12, 2009 at 18:03

Bye bye Debug.WriteLine!

leave a comment »

Recently I had the opportunity to deal with a couple nasty WM_PAINT handlers. Everyone who have been in a situation where you need to debug some broken paint operations knows that it can be really hard to debug using breakpoints, since you can’t break into the debugger. When you break into the debugger, the WM_PAINT event will trigger once again when you switch back to the program you are debugging. Of course you can overcome this by placing the debugger and the debugee on different areas of your screen, but mostly I don’t think it pays back to use breakpoints for these kind of scenarios.

So what do we do when we have a bug in a WM_PAINT handler? Write a unit test? Nope. At least I don’t, even if that would be my preferred way to go.
As long as I remember I think I have inserted alot of those Debug.WriteLine() statements all around my code, so I can get some kind of trace log for the program.
However, this requires modification and recompilation of the code.

So let me introduce to you something I started using recently: Tracepoints!
I read about them years ago and have tried to use them in earlier versions of Visual Studio. A week ago they became my new little helper… in Visual Studio 2008.

Here is a quick how to from MSDN on how you can use them:
How to: Specify a Tracepoint/Breakpoint Action

So now I don’t use Debug.WriteLine() anymore. Instead, I let a tracepoint print a message including the expression I need to evaluate and print.
However, even though this feature works great, you may run into trouble.
Today I discovered issues where the expression evaluation times out!
The timeout occurred when I had quite a number of tracepoint set in a piece of code I was debugging on my Windows Mobile device.

Every time I have to deal with UI components which implements a quite complex handler for WM_PAINT I always think “There must be some way to test this!”. So far I haven’t found a satisfactory design where UI components meets the requirements of my unit testing framework.
If you have ideas or links on how to succeed with automated testing and UI components, please let me know!

Update: Merrick Chaffer has a quite similar blog post with a nice screen shot on the dialog where you set up your tracepoint

Written by anderssonjohan

March 9, 2009 at 11:46

Posted in debugging, programming

Tagged with