Posts Tagged ‘C#’

LINQ Raytracer written in 1 statement.

August 14th, 2008

OMFG.

I think that just about sums up the Fully LINQified Raytracer….I missed this when it hit the blogosphere back in October last year, but wow i’m just gobsmacked….

I found this while reading about Mono’s 100% compliance with .NET 3.0

I feel so suddenly inadequate in what I do…..

This action is invalid when the mock object is in verified state

August 13th, 2008

I’ve long been noticing the following errors come up at the end of our NUnit testrun, but never had a chance to look into it in detail until now…They’ve never resulted in a broken build, and they do clearly look like something happening outside the scope of our unit test (even if it was caused by our test)

Unhandled exceptions:
1) : System.InvalidOperationException: This action is invalid when the mock object is in verified state.
at Rhino.Mocks.Impl.VerifiedMockState.MethodCall(IInvocation invocation, MethodInfo method, Object[] args)
at Rhino.Mocks.MockRepository.MethodCall(IInvocation invocation, Object proxy, MethodInfo method, Object[] args)
at Rhino.Mocks.Impl.RhinoInterceptor.Intercept(IInvocation invocation, Object[] args)
at ProxyInterfaceSystemSystemObject_System_DataIDataReader_Rhino_Mocks_InterfacesIMockedObject_System_Runtime_SerializationISerializable.Close()
at ExternalDataComponent.Data.DataRecordEnumerator.Dispose()
at ExternalDataComponent.Data.DataRecordEnumerator.Finalize()


Any obvious names have been masked to protect the innocent/stupid.

The error message quite is quite obvious in what the problem is, and leaves little doubt as to where it’s originating from….But the difficulty in this problem is finding out what causes the exception in the first place.

After attaching the VS debugger to NUnit, and turning on “Break On Exception” for the System.InvalidOperationException exception, All i would get is a debugger breaking into a location which was not relevant to any executing code, and the entire call stack consisted of non-managed code.

After a lot of thought, and with a little luck, i realised that what’s happening is that some of our tests are creating a stub object and passing it into the ExternalDataComponent during testing. The ExternalDataComponent is assuming that it is safe to call dispose on the object and thus doing so. The Rhino.Mocks framework then throws an exception when it intercepts the Dispose() method of the mocked interface, because the mock object “is in [the] verified state”.

My GoogleFu is in good form.

Unfortunately, we aren’t able to make changes to the ExternalDataComponent i’ve so eloquently disguised, as it’s a dependency library we’re using, so the “solution” is to reset all mocks to the original Record state before calling dispose (which additionally the tests weren’t doing).

DateTime.Parse() is locale sensitive

August 13th, 2008

The DateTime.Parse() method (and all its derivatives, i assume) are locale sensitive and will assume that the string you provide it is in the standard ISO date format, or in the format for your locale.

The buggy implementation I found in our system was calling DateTime.Parse() with a value of “23-07-2007″, which threw an exception citing that the string was not in the correct format. I dug around a bit with the code and tried different implementations with different results. It was only after i provided it a US date value (which it did not baulk at) I realised that my system’s locale was set to English (US).

The code was wrong to assume the current system locale is the expected input data format, in the first place, but this one tripped me up for a little while.

Some LINQ and WPF Basics

August 12th, 2008

This evening I wanted to get back to my old habits of creating silly spike projects which just test out a particular piece of functionality/feature.

Tonight I have mixed together some WPF forms and binding with some LINQ queries i was learning.

Part 1 – WPF Forms and Binding
What I wanted to learn from this was to create my own ListBox with a custom drawn ListItem, and bind it to a simple List<String>. The catch was I wanted to do this without looking it up on the net thereby forcing myself to learn the framework and in particular the syntax around the Binding interpreter because there’s no IntelliSense for any Binding properties. The result XAML is below:

   1:  <StackPanel>
   2:      <Button Click="Button_Click">Find With Vowels > 5Button>
   3:      <Button Click="Button_Click_1">Find Specific FileButton>
   4:      <Button Click="Button_Click_2">Find with GroupingButton>
   5:      <TextBlock>TextBlock>
   6:      <ListBox ItemsSource="{Binding}" Height="326">
   7:          <ListBox.ItemTemplate>
   8:              <DataTemplate>
   9:                  <Label Content="{Binding Path=.}" />
  10:              DataTemplate>
  11:          ListBox.ItemTemplate>
  12:      ListBox>
  13:  StackPanel>



Part 2 – LINQ Basics
Although I was watching the video, I went off and did my own thing for the most part, and was playing around with using LINQ to select a list of directories which matched a certain criteria. This sample demonstrated how to add any method as part of the filter condition for a LINQ query, and a brief touch on ordering.

   1:  private void Button_Click(object sender, RoutedEventArgs e)
   2:  {
   3:      var files = from d in new DirectoryInfo(@"C:\Program Files").GetDirectories()
   4:                  where d.Name.Contains("Microsoft")
   5:                  && NumberOfVowels(d.Name) > 5
   6:                  orderby d.Name.Length descending
   7:                  select d;
   8:      this.DataContext = files;
   9:  }
  10:   
  11:  private int NumberOfVowels(string directoryName)
  12:  {
  13:      char[] vowelArray = new char[] { 'a', 'e', 'i', 'o', 'u' };
  14:      var vowels = from ch in directoryName.ToLower()
  15:                   where vowelArray.Contains<char>(ch)
  16:                   select ch;
  17:      return vowels.Count<char>();
  18:  }



Part 3 – LINQ Objects

This idea is to use LINQ to return an anonymous type which is defined inline of the LINQ query itself. (ignore the bad naming convention, here ;) )

   1:  private void Button_Click_1(object sender, RoutedEventArgs e)
   2:  {
   3:      var files = from d in new DirectoryInfo(@"c:\program files").GetDirectories()
   4:                  from f in d.GetFiles()
   5:                  where f.Name == "readme.htm"
   6:                  select new { fileName = f.Name, dirName = d.Name };
   7:   
   8:      this.DataContext = files;
   9:  }



Part 4 – LINQ Grouping
This exercise was to play around with grouping of LINQ queries and the ways that you can select out of the grouped query result. I still haven’t got the knack of this one, just yet….

   1:  private void Button_Click_2(object sender, RoutedEventArgs e)
   2:  {
   3:      var files = from d in new DirectoryInfo(@"c:\program files").GetDirectories()
   4:                  from f in d.GetFiles()
   5:                  group f by new { ext = f.Extension, fullName = d.FullName } into items
   6:                  orderby items.Count() descending, items.Key.ext ascending
   7:                  select new { ext = items.Key.ext, dirName = items.Key.fullName, Count = items.Count() };
   8:   
   9:      this.DataContext = files;
  10:  }


That just about wraps it up for tonight….Not a bad way to spend my time offline

WPF And Animation Basics

August 10th, 2008

I’ve recently been getting my hands dirty with WPF as a successor to WinForms, and one thing is for sure – its like i’m starting from ground zero, all over again…

What I’ve recently wanted to do was to learn the details of animation in WPF. I’ve read a lot about the animation frameworks built into WPF, and the fact that they can be programmed directly into the XAML is quite interesting. Seems that it XAML is a whole lot more than a mark-up language. It’s so expressive it is almost like code.


<window x:Class="WPFAnimatingPath.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
</window><window .Resources>
<storyboard x:Key="pointAnimation">
<pointanimation From="55, 10" To="55, 150" RepeatBehavior="Forever" AutoReverse="True" Storyboard.TargetName="seg1" Storyboard.TargetProperty="Point1" AccelerationRatio="0.5" DecelerationRatio="0.5" Duration="0:00:10" />
<pointanimation From="105, 150" To="105, 10" RepeatBehavior="Forever" AutoReverse="True" Storyboard.TargetName="seg2" Storyboard.TargetProperty="Point1" AccelerationRatio="0.5" DecelerationRatio="0.5" Duration="0:00:05" />
</storyboard>
</window>
<grid>
<button Name="btnAnimate" Margin="0,37,0,0" Click="btnAnimate_Click">
<stackpanel Height="200" Width="160">
<textblock TextAlignment="Center" Height="40" VerticalAlignment="Bottom" FontSize="16">Click me</textblock>
<path Stroke="BlueViolet" StrokeThickness="2" Width="160" Height="160">
</path><path .Triggers>
<eventtrigger RoutedEvent="Path.Loaded">
<beginstoryboard>
<storyboard>
<doubleanimation Storyboard.TargetName="rotation" Storyboard.TargetProperty="Angle" From="-30" To="30" Duration="0:0:05" RepeatBehavior="Forever" AutoReverse="True" AccelerationRatio="0.5" DecelerationRatio="0.5" />
</storyboard>
</beginstoryboard>
</eventtrigger>
</path>
<path .RenderTransform>
<rotatetransform x:Name="rotation" CenterX="80" CenterY="80" Angle="0" />
</path>
<path .Data>
<pathgeometry>
</pathgeometry><pathgeometry .Figures>
<pathfigure StartPoint="0, 80">
<linesegment Point="30, 80" />
<quadraticbeziersegment x:Name="seg1" Point1="55, 10" Point2="80, 80" />
<quadraticbeziersegment x:Name="seg2" Point1="105, 150" Point2="130, 80" />
<linesegment Point="160, 80" />
</pathfigure>
</pathgeometry>

</path>

</stackpanel>
</button>
</grid>

What i’ve written here is a simple application which displays a button on the page. Like my last post about XAML and the mindset change, this code allows me to embed whatever i want into the content of the Button, and in this case, i have 2 bezier arcs which form a pseudo SINE wave. when you click the button, the arcs animate and flow in a throbbing fashion.

These are the basics which demonstrate:

  • Window Resources
  • Embedded Content
  • Drawing arcs/lines
  • Animating objects

MCMS: GetByGuid throws COMException (“Server Error”)

August 5th, 2008

In (the now famous) Project P, working with Microsoft CMS’s security model had me ripping my hair out.

Whenever I made a call to the context.Searches.GetByGuid() method, the system would throw a COMException, citing the quite unhelpful message “Server Error. Please contact your administrator”

For future reference (in case anyone comes across this themselves) the problem was caused because the GUID i was passing into the application was not formatted in the correctly for what CMS was expecting.

My code was doing:
string inputGuid = myGuid.ToString();

But it turns out it actually needed to be:
string inputGuid = myGuid.ToString(“B”);

The difference (according to MSDN) is that .ToString() with no overload assumes the format identifier of “D” which results in a GUID formatted without curly braces. Format “B” provides the same guid string but with curly braces.

Why this needed to throw a “Server error” exception, is beyond me. A simple ArgumentException would have sufficed, or better still it could take in a Guid as the parameter instead of a string.

For a blow-by-blow account of this problem, visit my newsgroup post about UserHasRightToBrowse Always Returns True

Covariance and Contravariance

August 4th, 2008

Covariance and Contravariance are terms used in programming languages and set theory to define the behaviour of parameter and return types of a function.

Yes, that’s a mouthful, but in a nutshell:

  • Covariance mandates that the return type and the parameters of a function must be a subtype of the original base class type for any superclass
  • Contravariance allows the return type and/or the parameter types to be super-types of the defined types and not necessarily sub-types

Nothing better than using an example:

   1:  public abstract class Animal
   2:  {
   3:      Animal CreateChild();
   4:  }
   5:   
   6:  public class Human : Animal
   7:  {
   8:      Animal CreateChild( return new Human(); }
   9:  }
  10:   
  11:  public class Dog : Animal
  12:  {
  13:      Dog CreateChild( return new Dog(); }
  14:  }

In this example:

  • Animal is a superclass.
  • Human is a subclass of Animal, with a covariant (no change) override to the CreateChild method to return the looser type Animal
  • Dog is a subclass of Animal, with a contravariant override to the CreateChild method to return the stronger type Dog

More reading on Eric Lippert’s blog series on Covariance and Contravariance in C#

EDIT: I thought it best prudent that I clarify that this is only one example of where variance is used. Method signatures, delegates and arrays are some more examples of where the theory of co and contra variance can be found.

Rhino vs Moq

June 26th, 2008

All i can start with at this stage is wow…..

I went through by feeds this morning and innocently picked up an article introducing mocking using Moq. I’ve read a little about it, followed the fact that it’s gathered quite a following, and figured it best I give it a spin to see for myself.

And then I followed the links in that article….
And then I read the links in that article…..
And i was shocked to learn about the bad blood between the very two opposing camps, which i’d never realised….

Incidentally, I started off trying to learn more about Moq, and now i’m reading up about TypeMock Isloator…all in a day’s work i suppose ;)

Head-Tracking for Virtual 3D Audio Environments – Part 1 (Research)

June 16th, 2008

Inspired by a colleague at work who was required to research an area of audio technology as part of his audio engineering degree, i’ve been dabbling over the last few weeks with a Nintendo Wii Remote and DirectSound.

Basically, what he needed was a piece of software which could simulate a audio-centric virtual environment. The audio simulation would involve a sound being modified based on the head-orientation of the user. If the user looks to the left, the sound “appears” to come from the right side of the head, and the same vice-versa. In order to perform the head-tracking we were going to rely on the capabilities of the Wii remote and all it’s IR camera glory. As with all clients, there really wasn’t anything much clearer specified, and I was left to kind of work out the rest ;)

The general concept behind the head-tracking is to use two points-of-reference on the user’s head to determine which side is left/right. Just like Johnny Chung Lee had done with his head-tracking exercise. With a little nudge forward from my old high-school electronics days, and $10 at JayCar, I’d soldered and constructed 2 purpose-built head-mounted IR LEDs. Blu Tack is an amazing product, and there’s nothing I found it won’t stick to. I won’t go into the detail of making one of these. It took me 20 mins, and the following article on making an IR LED pen was sufficient enough. As a tip, to check if your IR light is working correctly, you can use a digital camera and point the IR light toward the camera. Our eyes can’t pick up infra-red light, but the CCD on a camera can.

Post-hardware construction, the first phase of this project basically entailed a proof of concept, and an opportunity for me to learn about the two major components of this project i knew close to nothing about:

  1. Connecting and using the the Wii remote on a PC
  2. Using DirectSound to control audio

But first there would be more pressing matters. Like getting my Soleil Bluetooth receiver to work under VirtualBox on Linux. I don’t run any development software under my windows-boot partition. My windows partition has one intended purpose….To cut a long story short, it looked like it would be a bigger hassle trying to get the BT dongle to work under linux than to just install VS in my gamebox partition…So that’s that.

The BlueSoleil software worked like a charm, and within minutes I was hooking up the Wiimote to the laptop. no problems. The Wiimote is detected as just another HID, so it pretty much worked out of the box on XP.

At this point, I went out to find *how* to actually do each of the individual unknowns for this project. And it’s at this point I need to credit two articles which pretty much gave me everything I needed to get going. I was fortunate enough to find this article on CodeProject on using DirectSound, and an MSDN blog with a managed library for controlling the Wiimote. Too easy.

Hooked up the sample Wiimote library, turned on the Wiimote, turned on my IR lights and voila – worked a treat.

And that’s it for this post….next post, i’ll describe in a bit more detail the putting together of the software – certainly more interesting than all this drivel – and with pictures…..

C# Yeild Keyword

June 9th, 2008

Although i’d seen it, and knew of it, i never bothered reading about it until now.

Very cool. I can see myself using this in a few enumerable cases.

First Chance Exceptions in .NET

May 30th, 2008

short post…..

In some cases, the .NET framework will throw an exception internally, and then (using it’s own exception handling routines) re-throw something else based on that exception. if you’re getting an exception thrown from the Framework which you don’t really understand, and can’t work out what is causing the problem, try turning on the First Chance Exception for the .NET CLR in VS (Debug –> Exceptions).

This allows VS to catch any CLR exceptions when they are thrown, and will give you more insight into what’s the root cause of the problem.

Also, make sure you turn it off when you’re done otherwise you could end up constantly chasing your tail catching unnecessary exceptions ;)

Microsoft Source Code Analysis for C#

May 26th, 2008

Also known as a CodeSniffer, this tool analyses your source code and outputs statistics of whether the code fails key standards which should be followed across your entire codebase.

    Source Analysis is similar in many ways to Microsoft Code Analysis (specifically FxCop), but there are some important distinctions. FxCop performs its analysis on compiled binaries, while Source Analysis analyzes the source code directly. For this reason, Code Analysis focuses more on the design of the code, while Source Analysis focuses on layout, readability and documentation. Most of that information is stripped away during the compilation process, and thus cannot be analyzed by FxCop.

Sweet. I’m going to try and push it into one of our local projects here :)

[UPDATE]
….bugger. Looks like it is reliant on VS2005/.NET 2.0

why am i still stuck on this lousy 1.1 project? :(

Strongly-Typing Your Domain Values

April 21st, 2008

I love this one. I don’t know the name of the pattern, but i love using it.

Imagine your system uses strings to represent the value of a status field. potential values of this field are:

  • New
  • Requested
  • Open
  • Closed
  • Deferred
  • In Progress
  • More Information Required

…and you want to write a method (or webservice) called UpdateStatus, which takes in one of these values.

Standard signature would look something like this:

public void UpdateStatus(string newStatus)

The use of “string” for the static type has the problem that someone could pass through a rubbish value as a string, and the UpdateStatus method is now responsible for domain validation of the input.

However, following the pattern below, you’re able to statically define your domain (if known at design-time) and enforce the stronger type in subsequent method calls.

public class IssueStatus
{
	void IssueStatus(string description)
	{
		this.description = description;
	}
		readonly string description;

	public static IssueStatus New = new IssueStatus("New");
	public static IssueStatus Requested = new IssueStatus("Requested");
	public static IssueStatus Open = new IssueStatus("Open");
}

and you can then use the strong IssueStatus type in your signatures:

public SaveButton_Clicked(object sender, EventArgs e)
{
	bo.UpdateStatus(IssueStatus.New);
}

public void UpdateStatus(IssueStatus newStatus)
{
	if (newStatus == IssueStatus.New)
	{
	// do something here
	}
}

I learnt this one on the job a few years back, and think it’s fantastic.