Archive

Posts Tagged ‘.NET’

References are not addresses

February 19th, 2009

Just read this excellent post by Eric Lippert about why it is incorrect to describe references in .NET as a pointer to a memory location

In the article he goes on to explain the differences between a pointer and a reference, and why they are not mutually interchangeable.

I have to admit, I’ve been incorrectly defining a reference. After reading this article from now on my definition of a “reference type” will be a type which contains a reference to an object held internally within the .NET GC. This reference is not *necessarily* a pointer and should be thought of more like a unique handle to the GC’s object than a pointer to a memory address.

Xerxes IT & Software ,

Mapping Database Tables To Objects

December 3rd, 2008

In my last article on the topic of database development, I covered performing database migration using MigratorDotNET.

Next, I wanted to look at the mapping process to the object model. I’d already decided I was going to use NHibernate as my ORM, but the detail was in hooking up NHibernate to the database. NHibernate’s XML syntax is pretty straightforward and incredibly powerful, but once again it’s another language i’m forced to deal with – i’m most efficient working in my primary language so the idea of slowing down when dealing with these mapping files by hand was really not in question.

Initially I looked into ActiveRecord (admittedly not into a whole lot of detail) but wasn’t excited by the framework. ActiveRecord performs it’s mappings from objects to database through attributes and it just seemed to me like an abuse of SoC. If i should want to change my ORM (unlikely, but i’m working within that constraint on this project), then it would have to support the same attribute syntax. Having said that however, there is a lot of momentum behind ActiveRecord, so i’m still reserving judgement on it’s applicability.

So apart from ActiveRecord, I went in search of another alternative to the XML mapping and recalled reading about Fluent NHibernate. In a nut-shell, Fluent NHibernate is a replacement for the XML mapping layer in NHibernate by defining the mapping in C#. Essentially the same benefits I got by using MigratorDotNet (type safety, compile-time checking etc) were available for defining my DB->OM mapping. Sweet!

A very quick spike with the project, and I immediately liked what I saw:

	public class NoteMap : ClassMap<Note>
	{
		public NoteMap()
		{
			Id(x => x.NoteId).GeneratedBy.Guid();
			Map(x => x.NoteTitle).WithLengthOf(64);
			Map(x => x.NoteData);
		}
	}

The equivalent XML mapping file (I won’t discuss it in detail in this post) would have been at least twice the size, and more importantly not refactor-friendly.

Because it’s in C# I was easily able to unit-test this mapping, with a little assistance. In fact it was so successful, it helped me discover a bug in my database migration script!

	[TestFixture]
	public class NoteMapping_Test : BaseTestMappings
	{
		[Test]
		public void TestCanAddNote()
		{
			Note note = new Note
			            	{
			            		NoteTitle = "Title",
			            		NoteData = "Data`"
			            	};
			Session.Save(note);

			Session.Flush();
			Session.Clear();
			Note fromDb = Session.Get<Note>(note.NoteId);
			Assert.AreNotSame(note, fromDb);
			Assert.AreEqual(note.NoteData, fromDb.NoteData);
			Assert.AreEqual(note.NoteTitle, fromDb.NoteTitle);
			Assert.AreEqual(note.NoteId, fromDb.NoteId);
		}
	}

	public class BaseTestMappings
	{
		protected SessionSource Source { get; set; }
		protected ISession Session { get; private set; }

		[SetUp]
		public void SetUp()
		{
			Source = new SessionSource(new TestModel());
			Session = Source.CreateSession();
			Source.BuildSchema(Session);
			CreateInitialData(Session);
			Session.Clear();
			Session.Transaction.Begin();
		}

		[TearDown]
		public void TearDown()
		{
			Session.Transaction.Rollback();
			Session.Close();
			Session.Dispose();
		}

		public class TestModel : PersistenceModel
		{
			public TestModel()
			{
				Assembly ass = typeof(NoteMap).Assembly;
				addMappingsFromAssembly(ass);
			}
		}
	}

What’s happening here is that Fluent NHibernate allows me to instantiate an NHibernate instance just by creating a Model. The model contains a list of all of the mappings applicable for my application and I pass that directly into the NHibernate session. Any of my tests which I want connected to a database will now have transaction management and a session for performing querying. I can use this in my application too with just about the exact same code, so instantiate a session and pass in the model.

It works very well and i’ve sucessfully removed the XML file with a type-safe C# mapping engine. The problem this poses, however is now I have two places where I have defined what my data structures look like. One in the MigratorDotNET framework, and the other in FluentNHibernate to map the data model. This means that to make any any change to the model would involve no less than 3 changes – the POCO, FluentNHibernate and MigratorDotNET.

Next time, I want to discuss ways of reducing this friction and streamline the refactoring process.

(There are some websites which i wish to attribute for some of the code and ideas i’ve expressed here but have since lost the links. If you see anything that’s yours, please let me know so I can appropriately credit)

Xerxes IT & Software , , ,

NUnit 2.5 Beta now supported in TestDriven.NET

December 3rd, 2008

http://weblogs.asp.net/nunitaddin/archive/2008/12/02/testdriven-net-2-18-nunit-2-5-beta.aspx

Jamie covers off some of the new things in NUnit 2.5 which are pretty cool, but the one thing he omitted (and I think is quite awesome) is the Assert.Throws<T>(); assertion.

Previously (NUnit 2.4 and below) you would either have to use the [ExpectedException()] attribute or implement the exception handling logic yourself in your test. Issues with using the ExpectedException attribute are well known. I’m doing this without VS at hand, so forgive me if parts are wrong, but for example:


[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void TestArgumentNullThrowsException()
{
    new MyObject(null);
}

[Test]
public void TestArgumentNullThrowsException()
{
  bool thrown = false;

  try
  {
    new MyObject(null);
  }
  catch (ArgumentNullException e)
  {
    // Check if the message is correct
    thrown = true;
  }
  catch (Exception e)
  {
    throw; // Any unexpected exceptions still get raised up
  }
  finally
  {
    Assert.IsTrue(thrown, "Expected exception should be thrown, but was not");
  }
}

Well with NUnit 2.5, you can lambda the entire thing and the testcase becomes so much simpler:


[Test]
public void TestArgumentNullExceptionIsThrown()
{
  Assert.Throws<ArgumentNullException>( () =>  new MyObject(null)  );
}

…And why is this good for TestDriven.NET? It means I can install NUnit 2.5 and actually use it with TD.NET, instead of using the GUI test runner.

Xerxes IT & Software , ,

Writing Tests to Catch Memory Leaks in .NET

November 13th, 2008

http://brian.genisio.org/2008/11/writing-tests-to-catch-memory-leaks-in.html

keeping for my own reference purposes.

Xerxes IT & Software ,

XBAP Is Cached When Running Without Debugger

October 19th, 2008

I’m digging deeper into WPF and learning more about XAML, web-XAML and XBAP. This evening i’ve stumbled across a nasty side-effect. When i’m creating an XBAP project in Visual Studio and run it without the debugger, the XBAP gets cached somewhere and any subsequent changes don’t show up – It keeps running the old XBAP file.

I’ve done a little digging and found out that the XBAP is cached by Click-Once when you run it outside the debugger. When executed, the application is deployed and run using Click-Once which (amongst other things) versions the assembly, checks for dependencies on the target machine and loads the application. If the application has been cached, then it will use the cached version instead. However you don’t have this problem when you’re running through the debugger because the process is launched by Visual Studio, and it will always run the latest assembly. This bugs me because I more frequently run my development apps outside the debugger and only attach when I need to. I know when my code is generally going to work, and most errors can be spotted without the need for attaching a debugger to the process.

Anyway the temporary solution is to add a pre-build event which clears the Click-Once cache and upon execution, the correct version of my app will be spawned. The command for the event is:

%windir%system32rundll32 %windir%system32dfshim.dll CleanOnlineAppCache

You can also run the command mage.exe -cc which is a CLI tool to do the same thing. More research is required into Click-Once and all this. Please note that this is a preliminary post, and I haven’t done much research in depth into the problem – if you know of a better way, i’d like to hear it!

Xerxes IT & Software , ,

Thread Safety and Locking

September 28th, 2008

I was recently reading a post about writing non-threadsafe code which talks about the main peril of multi-threading, and one way you can work around it.

I’ve long been a believer that doing anything multi-threaded is fraught with danger and you have to tread incredibly carefully when doing so. I say this with experience. What I learnt from reading that post wasn’t in the content, but in the comments, which talked about the Interlocked class for performing simple, thread-safe increments and decrements of operators.

So i decided to try it and see what the benefit really is, and i was surprised by by the results! I did my own profile against 3 scenarios:

  1. No thread safety (fast comparitively, though gave incorrect results)
  2. Locking using “lock” keyword (correct, but very slow by magnitude of nearly 10x)
  3. Locking using Interlocked class (correct, and fast – faster than no thread safety in some test runs)

Clearly these results aren’t scientific, but are quite good to give relative indicators of performance. I’ve reproduced the code below.


using System;
using System.Diagnostics;
using System.Threading;
using NUnit.Framework;

namespace ThreadingExample
{
	public interface IThreadTest
	{
		int Value { get; }
		void Debit();
		void Credit();
	}

	public class NonThreadSafe : IThreadTest
	{
		public int Value { get; private set; }

		public void Debit()
		{
			Value--;
		}

		public void Credit()
		{
			Value++;
		}
	}

	public class ThreadSafe : IThreadTest
	{
		public int Value { get; private set; }

		object lockSentinel = new object();

		public void Debit()
		{
			lock (lockSentinel)
			{
				Value--;
			}
		}

		public void Credit()
		{
			lock (lockSentinel)
			{
				Value++;
			}
		}
	}

	public class ThreadSafeUsingInterlocking : IThreadTest
	{
		private int value;
		public int Value
		{
			get { return value; }
			private set { this.value = value; }
		}

		public void Debit()
		{
			Interlocked.Decrement(ref value);
		}

		public void Credit()
		{
			Interlocked.Increment(ref value);
		}
	}

	[TestFixture]
	public class TestClass
	{
		[Test]
		public void TestNonThreadSafe()
		{
			NonThreadSafe nts = new NonThreadSafe();

			ExecuteThreadedTest(nts);

			Assert.AreEqual(0, nts.Value);
		}

		[Test]
		public void TestThreadSafe()
		{
			ThreadSafe ts = new ThreadSafe();

			ExecuteThreadedTest(ts);

			Assert.AreEqual(0, ts.Value);
		}

		[Test]
		public void TestThreadSafeUsingInterlocking()
		{
			ThreadSafeUsingInterlocking tsui = new ThreadSafeUsingInterlocking();

			ExecuteThreadedTest(tsui);

			Assert.AreEqual(0, tsui.Value);
		}

		private void ExecuteThreadedTest(IThreadTest threadTest)
		{
			int maxIterations = 99999999;
			DateTime start = DateTime.Now;
			Thread t1 = new Thread(() =>
			{
				for (int i = 0; i < maxIterations; i++)
				{
					threadTest.Credit();
				}
			}
			);
			t1.Name = "t1";

			Thread t2 = new Thread(() =>
			{
				for (int i = 0; i < maxIterations; i++)
				{
					threadTest.Debit();
				}
			}
			);
			t2.Name = "t2";

			t1.Start();
			t2.Start();

			t1.Join();
			t2.Join();

			DateTime finish = DateTime.Now;
			Debug.WriteLine(String.Format("Took {0}ms to complete", (finish - start).TotalMilliseconds));
		}
	}
}

Xerxes IT & Software , , ,

List of Technologies/Software I would like to try out from ground zero

September 16th, 2008

Reading an article about unit testing got me thinking about some of the tools i’d love to sink my teeth into.

I’m documenting them here in case i forget.

Backend
NHibernate (ORM)
SQLLite (DB)

Framework
Castle Windsor/Ninject (DI)
Lof4Net (Logging)
LINQ (Language Querying)
Tree Surgeon (Environment setup)

Testing
NUNit (Unit testing)
Rhino.Mocks/Moq (Mocking)
WatIn (UI testing)

Build Integration
Nant (Build tool)
CC.NET (CI server)

UI
WPF (GUI)
ASP.NET MVC /Monorail (Web engine)
PRISM (WPF App framework)
NHaml (MVC View Engine)

a lot of these i have or currently do use….some of them i have only ever played around with and a few i’ve never even touched.

At least me putting it down on paper (or bits, in this case) is a reminder of what i’m keen to try, and will get to it soon.

Xerxes IT & Software ,

MissingMethodException: ?

September 10th, 2008

Sometimes though when you’re changing interfaces across several projects, you can end up in a stink because a method reference is removed or a signature is changed, and you end up with the following error:

When i build in Visual Studio, in order to save time, I don’t always do a <ctrl><shift>-<b> (Rebuild Solution). instead, i do a <alt>-<b>,<u> in order to rebuild just the project, and its dependencies (faster build).

I’ve had this error come up a few times, and it’s easy to solve – in case i ever forget here it is:.

Server Error in ‘/’ Application.
——————————————————————————–

?
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.MissingMethodException: ?

When you get this problem, just re-build the entire project.

Xerxes IT & Software , ,

Making Assumptions About An Objects State

August 20th, 2008

I’ve seen this now twice in about 30 mins, and its bugging me.

One of the developers i work with is writing code like this:

string postingUrl = CmsHttpContext.Current.Posting.Url.ToLower(CultureInfo.InvariantCulture);

Whats bugs me with this code is that it shows no understanding or care for defensive programming.

Q1: Why do you assume that CmsHttpContext.Current is safe? Sure, within ASP.NET the framework creates a new Context for you upon request, and (in this case) Microsoft CMS wraps the HttpContext and guarantees you a copy of a context for you. Under these known conditions, the CmsHttpContext.Current is safe.

Now that’s been chained onto Posting, which throws the exception. Why assume that you’ve hit a posting? Why assume that there would be a posting at all? This kind of lack of thinking just demonstrates lazy programming, to me.

*grumble*

Xerxes IT & Software , ,

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.

Xerxes IT & Software ,

Where are the open-source Code Coverage tools for .NET?

August 12th, 2008

I posted the following message on a developer list. I’m so frustrated by the lack of alternatives to nCover…..

We’ve been using the free version of NCover in a number of our projects (v1.5.8), and for the most part, we’re happy with what it does.

However we’ve recently come to realise that the free download for nCover doesn’t work on x64 machines (incompatibility when it tries to register the profiling DLL). This prompted me to have a look for another free/OSS product which would work in the same or similar manner as nCover….and i’m coming back empty-handed.

Am i the only person who has questioned why i should need to purchase the enterprise version of the product, just for x64 support? And more importantly, how come there is a complete drought of alternatives for nCover? I’ve found PartCover, but haven’t used it and it doesn’t look to be as complete as nCover….

I’m shocked, given that the OSS community seems mad about creating alternatives and derivatives for toolsets (think NUnit vs MBUNit vs xUnit or NMock vs Rhino Mocks vs Moq …). There seems to be a number of alternatives for other TDD tools, but as far as coverage goes, is nCover really the only thing out there?

If you know any, i’d like to hear about it….

Xerxes IT & Software , ,

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

Xerxes IT & Software , ,

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.

Xerxes IT & Software , ,

Converting an ASP.NET Website to Web-Application

June 10th, 2008

I’ve had to do this so many times in the past, i ended up creating my own instructions and gotchas

Today I stumbled across an article on the MSDN explaining step-by-step how to convert a website project to a web-application project and am keeping record of it….One thing i didn’t know was that you can run the “Convert To Web Application” option to generate partials and code-behinds.

noted.

Xerxes IT & Software ,

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 ;)

Xerxes IT & Software , ,