Posts Tagged ‘.net’
WordWrap function in c#
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
Deploying applications to Windows and Windows Phones which supports dynamic modules
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?
Switching component implementations in Castle Windsor
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.
The replacement for the real component is as simple as:
public bool IUsernamePasswordVerifier.VerifyPasswordFor( string username, string password ){ return true;}
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" ) );
Castle Windsor 2.0 RTMed
Oh yeah! Castle Windsor 2.0 is RTMed!
I just can’t wait ’til we upgrade RemoteX Applications.
How To Make the Firefox/YouTube Wait Symbol In WPF
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:
- A Canvas is used to distribute the 8 circles on
- Each circle has its fixed position and its own transparency (which makes the “tail” effect)
- We add a trigger to the FrameworkElement.Loaded event for the Canvas, in which we…
- …add a DoubleAnimation targeting the Angle property of the RotateTransform we also added to the Canvas
- 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?
A fluent interface and the Builder pattern
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.
Bye bye Debug.WriteLine!
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
Tail call recursion with C#
An e-mail landed in my mailbox at work. It was a discussion which ended up in the following statement by my collegue Morten:
“- In theory you could also write that method using tail call recursion and in that way avoid eating up space on the call stack“.”
One of the brilliant guys I have the opportunity to work with is Morten. If you would put him in a movie, he would definitely play the role of the crazy scientist! He’s a guy which I love to discuss computer science with, when time allows for it.
So this time he made me dig deeper into how one could practially make our little recursive method “tail call recursive”.
I started out with two questions:
1) What the h-ck is tail call recursion? (no, I have no degree in CS)
2) Why is the temperature minus 26 degress celsius here in Rättvik, Sweden which makes me dig deeper into question 1 and prevents me and the kids go out dig deeper/play in the snow?
IF you now would try to do tail call recursion with our recursive method, would it be possible with C#?
Well, sure it is POSSIBLE. But it requires a bit more than Ctrl-Shift-B in Visual Studio. As we all know, in C#, we have little control of the native code being executed. For example we have the JIT compilator, which depends on which platform you are on. Code can also be inlined, something which now also applies to value types on the x86 platform (introduced in .NET 3.5 SP1). But except the jitter and the inlining we also have the seems-to-be-spot-on-target-at-first-look MSIL tail prefix…
Looking at a stack trace convering a call to a recursive method we can find the typical characteristics of a non-tail call recursive method:
at WaitForRunningThreads()at WaitForRunningThreads()at WaitForRunningThreads()at WaitForRunningThreads()at WaitForRunningThreads()at WaitForRunningThreads()…
By using tail call recursion it would look something like:
at WaitForRunningThreads()
Since there is no way I can make a tail call recursive method in C# produce such a stack trace by modifying the C# code, I need to patch the Release-compiled (using Visual Studio) IL code to make it use the MSIL tail prefix.
Suppose we have the following program:
class Program{static void Main(){ WaitForRunningThreads( 42 );}
static void WaitForRunningThreads( int n ){ System.Console.WriteLine( n ); System.Threading.Thread.Sleep( 100 ); if ( n < 2 ) throw new System.Exception(); WaitForRunningThreads( n / 2 );}}
With the following IL code output generated by csc.exe:
.class private auto ansi beforefieldinit Programextends [mscorlib]System.Object{.method private hidebysig static void Main() cil managed{ .entrypoint // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: call void Program::WaitForRunningThreads(int32) IL_0007: ret} // end of method Program::Main
.method private hidebysig static void WaitForRunningThreads(int32 n) cil managed{ // Code size 32 (0x20) .maxstack 8 IL_0000: ldarg.0 IL_0001: call void [mscorlib]System.Console::WriteLine(int32) IL_0006: ldc.i4.s 100 IL_0008: call void [mscorlib]System.Threading.Thread::Sleep(int32) IL_000d: ldarg.0 IL_000e: ldc.i4.2 IL_000f: bge.s IL_0017
IL_0011: newobj instance void [mscorlib]System.Exception::.ctor() IL_0016: throw
IL_0017: ldarg.0 IL_0018: ldc.i4.2 IL_0019: div IL_001a: call void Program::WaitForRunningThreads(int32) IL_001f: ret} // end of method Program::WaitForRunningThreads
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret} // end of method Program::.ctor}
When we execute the program it produces the following output:
422110521 Unhandled Exception: System.Exception: Exception of type 'System.Exception' was thrown.at Program.WaitForRunningThreads(Int32 n) in Program.cs:line 13at Program.WaitForRunningThreads(Int32 n) in Program.cs:line 14at Program.WaitForRunningThreads(Int32 n) in Program.cs:line 14at Program.WaitForRunningThreads(Int32 n) in Program.cs:line 14at Program.WaitForRunningThreads(Int32 n) in Program.cs:line 14at Program.WaitForRunningThreads(Int32 n) in Program.cs:line 14at Program.Main() in Program.cs:line 5
As mentioned before, we have no option giving the C# compiler a hint nor optimization option which will make it emit the MSIL tail prefix. What we can do for sure is patching the IL code using ILDASM/ILASM to include the tail prefix in WaitForRunningThreads():
.method private hidebysig static void WaitForRunningThreads(int32 n) cil managed{// Code size 33 (0x21).maxstack 8IL_0000: ldarg.0IL_0001: call void [mscorlib]System.Console::WriteLine(int32)IL_0006: ldc.i4.s 100IL_0008: call void [mscorlib]System.Threading.Thread::Sleep(int32)IL_000d: ldarg.0IL_000e: ldc.i4.2IL_000f: bge.s IL_0017
IL_0011: newobj instance void [mscorlib]System.Exception::.ctor()IL_0016: throw
IL_0017: ldarg.0IL_0018: ldc.i4.2IL_0019: divIL_001a: tail.IL_001b: call void Program::WaitForRunningThreads(int32)IL_0020: ret}
The following is executed from a Visual Studio Command Prompt in the output directory:
> ildasm RTail.exe /out=rtail.il
> copy rtail.il rtail_modified.il
> notepad rtail_modified.il
(add the tail prefix as illustrated above)
> ilasm rtail_modified.il /out:rtail_modified.exe
..and the results are:
> rtail_modified.exe422110521 Unhandled Exception: System.Exception: Exception of type 'System.Exception' was thrown.at Program.WaitForRunningThreads(Int32 n)at Program.Main()
Voila!
The MSIL tail prefix pops the call stack BEFORE the call instruction and makes our stack trace look like we are using tail call recursion. Nice, huh?
But, if we dig deeper into the differencies of the platform dependent JIT compilators we can find that this is done by the jitter on 64-bit platforms:
“In fact, on 64-bit platforms, the CLR tries to do tail calls even if the tail. prefix is not specified. This is because platform-independent IL programs will get the same amount of stack space reserved for them by the OS, even though the 64-bit process will consume stack at a faster rate. Hence, we try to reduce stack usage by doing tail calls.“
Which part do I not get here?
Why can’t the C# compilator do this optimization?
Why rely on the JIT compilator to do such an optimization?
Luke Hoban (nowadays on the F# team) gives me some answers in a feedback response:
“1) There is actually a non-trivial overhead cost to using the .tail instruction in the CLR (it is not just a jump instruction as tail calls ultimately become in many less strict environments such as functional language runtime environments where tail calls are heavily optimized).
2) There are few real C# methods where it would be legal to emit tail calls (other languages encourage coding patterns which have more tail recursion, and many that rely heavily on tail call optimization actually do global re-writing (such as Continuation Passing transformations) to increase the amount of tail recursion).
3) Partly because of 2), cases where C# methods stack overflow due to deep recursion that should have succeeded are fairly rare.“
Also this statement (and the code in context) makes me think this is something closer to functional programming languages like F# rather than C#:
““I would have to assume the C# compiler team is using every trick in the book to make highly performant IL”
Are you kidding? The C# compiler does far less stuff, as you just saw right here. The F# compiler determined the code was a loop, and compiled it so. (It didn’t need to use the tail prefix ’cause it did even better.) I’m not saying the C# compiler doesn’t optimize, but it tries to keep a direct mapping from source to IL. (I think this is even sort of a goal for the C# compiler).“
More knowledge is brought to me by Jomo Fishers (also member of the F# team) with his post Adventures in F# – Recursion in Three Languages:
“This tradeoff frees up the C# team to focus on things like LINQ.“
=)
After reading the web pages linked from this post and a numerous of other about this topic, I believe I can stop bother about tail call recursion in my C# code.
Unfortunately I could not solve the problem of avoid having a recursive C# method eat up stack space, but at least I learned something about jitters, compiler optimization, the CLR and I definitely can say I now know the answer to my first question!
ReadOnlyDictionary
Since I started using .NET 2.0 I’ve been wondering why Microsoft didn’t provide a ReadOnlyDictionary<k,v> class in the BCL. I just stumbled upon some info where I found this:
| internal class ReadOnlyDictionary<K, V> : IDictionary<K,V>, ICollection<KeyValuePair<K, V>>, IEnumerable<KeyValuePair<K, V>>, IDictionary, ICollection, IEnumerable |
| Name: | MS.Internal.Utility.ReadOnlyDictionary |
| Assembly: | WindowsBase, Version=3.0.0.0 |
This is an internal class in one of the libraries that is shipped with .Net Framework 3.0. But why didn’t that class make it into the System.Collections.ObjectModel namespace?
Probably the developers on the team developing the BCL didn’t have the time required to push this into the release. However, this suggestion has been on Microsoft Connect for a while.
I wonder if we can expect such a class for the next release…
Debugger visualizer for MethodInfo
In his preparations on his talk “Reflection 2.0″, Roy writes about a debugger visualizer for the MethodInfo class.
Neat stuff.