4

Path resolution in ASP.NET

Posted in Asp.Net, C# at January 14th, 2010 by Gerrod / 4 Comments »

One thing I’ve always thought that ASP.NET doesn’t do a great job of is handling resource paths. For example, lets say on your development box, you have a website hosted under the virtual directory “MyProject”, such that you browse to http://localhost/MyProject/ to go to the home page. Lets also say that when you deploy the website to an external domain, it falls into the domain root, so instead you go to http://myproject.com/ to see your home page.

Sound familiar? The real problem then comes when you try and define a resource (e.g. a javascript file) using a relative path:

<script
    type="text/javascript"
    src="/Scripts/jquery.js">

This will work fine and dandy when you deploy the website, however on your local machine it will be looking for jquery at the path http://localhost/Scripts/jquery.js” – which more than likely isn’t going to work.

To get around this problem, I wrote a quick helper method called “Locate”, which I find myself reusing time and time again between websites. More often than not, I put it into a static class called “SiteManager” which basically just contains a bunch of helper functions relevant to the current website. Here’s the method:

/// <summary>
/// Resolves the path to a URL
/// </summary>
/// <param name="url">The path to be resolved, relative to the
/// application root</param>
/// <param name="formatArgs">String formatting arguments</param>
/// <returns>The URL</returns>
static public string Locate(string url, params object[] formatArgs)
{
    if (String.IsNullOrEmpty(url))
        url = "/";

    if (formatArgs != null && formatArgs.Length > 0)
        url = String.Format(url, formatArgs);

    HttpContext context = HttpContext.Current;
    return String.Concat(
        context.Request.ApplicationPath,
        !url.StartsWith("/") ? "/" : String.Empty,
        url);
}

To use the method, you simply change your script declaration (or whatever resource you’re trying to find) as follows:

<script
    type="text/javascript"
    src="<%= SiteManager.Locate("/Scripts/jquery.js") %>">
</script>

You’ll also notice that it supports string formatting – so even though it would be pointless in this particular example, you could, if you preferred, do something like this:

<script
    type="text/javascript"
    src="<%= SiteManager.Locate("/Scripts/{0}.js", "jquery") %>">
</script>

In both instances, this will resolve the URL in your output document using the current application path –

  • http://localhost/MyProject/Scripts/jquery.js on your local machine; and
  • http://myproject.com/Scripts/jquery.js on the web server.

Enjoy!

1

Quick WPF Performance Statistics

Posted in .Net, C# at December 23rd, 2009 by Drew / 1 Comment »
Just thought I’d put out some quick WPF performance statistics thanks to Microsoft. You can download the entire slideshow here.
  • DependencyProperty is x3 faster than INotifyPropertyChanged
  • ObservableCollection accesses single items 90 times faster than List
  • ObjectDataProvider is x20 smaller than XmlDataProvider

Microsoft also have some other good tips over here too.
I’d like to see some real world statistics on the differences between using static vs dynamic resources too. Anybody know of any?

2

Question of the day: Enums

Posted in C#, Daily Question at October 7th, 2009 by Gerrod / 2 Comments »

Some fun with enums! Assume you have an enum defined as follows:

enum Frequency {
    None = 0,
    Annual = 1,
    SemiAnnual = 2,
    Quarterly = 4,
    Monthly = 12,
    Weekly = 52
}

Now, given the following block of code:

Frequency myFrequency = (Frequency) 104;
System.Console.WriteLine("My frequency is: {0}", myFrequency.ToString());
bool is100Defined = Enum.IsDefined(typeof(Frequency), 100);
bool is52Defined  = Enum.IsDefined(typeof(Frequency), 52);
  1. What is written to the console?
  2. What is the value of is100Defined?
  3. What is the value of is52Defined?

First correct answer gets absolutely nothing (but think how great you’ll feel!)

0

Unit Testing DateTime.Now

Posted in .Net, C#, Unit Testing at September 7th, 2009 by Drew / No Comments »

I’m sure alot of you have come across a method that uses DateTime.Now at some point in your lives. Normally this is fine and nobody blinks an eyelid… until we need to unit test it.

Consider the follow code:

public class MyEntity
 {
   public DateTime Created { get; set; }
 }

 public class MyRepository
 {
   public void UpdateMyEntity(MyEntity entity)
   {
     entity.Created = DateTime.Now;
   }
 }

Unless you are one of one of those fancy pants with TypeMock and the ability to fake DateTime.Now, the rest of use must look elsewhere for a solution. Here are three different ways to solve this.

1. Wrap your DateTime calls with another class

Some people prefer using a static “Clock” class to handle this which can be easily faked out during your unit testing.

public static class Clock
{
    public static Func<DateTime> Now = () => DateTime.Now;
}

This approach, while decoupling your dependency on System.DateTime is a bit of overkill and requires all developers on the project to be aware of it and to use it.

2.Use an Interface and your favourite Isolation Framework

public interface IClock
{
  DateTime Now {get;}
}

public class SystemClock : IClock
{
  public DateTime Now { get { return DateTime.Now; } }
}

You can now use an isolation framework such as Rhino.Mocks to fake the call to Now();

3. Use a DateTime Comparer that accepts a range

While not 100% accurate to the millisecond, this approach is my prefered approach as you don’t have to change to your code just to unit test it. No littering your code with IClock dependencies or using a delegate to return the current DateTime.Now (although one could argue that DateTime.Now shouldn’t be a property to begin with). This approach asserts that the Created property that is set in MyRepository.Update is within a certain range.

 /// <summary>
 /// Helper class to compare 2 values are within a certain range.
 /// </summary>
 public class DateComparer : IComparer<DateTime>
 {
 public TimeSpan MarginOfError { get; private set; }

 public DateComparer(TimeSpan marginOfError)
 {
   MarginOfError = marginOfError;
 }

  public int Compare(DateTime x, DateTime y)  // x = expected, y = actual
   {
     var margin = x - y;
     if (margin <= MarginOfError)
       return 0;
     return new Comparer(CultureInfo.CurrentUICulture).Compare(x, y);
   }
 }

You can now write the follow test:

public void MyRepository_UpdateTest()
 {
   var repository = new MyRepository();
   var entity = new MyEntity();
   repository.UpdateMyEntity(entity);
   var comparer = new DateComparer(new TimeSpan(0, 0, 0, 5));
   Assert.IsTrue(comparer.Compare(entity.Created, DateTime.Now) == 0);
 }
4

Unit Testing Expression Tree Equality

Posted in .Net, C#, Unit Testing at August 25th, 2009 by Ben / 4 Comments »

Sometimes you need to test whether two expressions are the same. However when you do a simple AreEqual() test on two expressions that look the same you get a negative result.

This method will fail

[TestMethod]
public void TestDoesNotWork()
{
  Expression<Func<int, int>> expressionA = x => x + 1;
  Expression<Func<int, int>> expressionB = x => x + 1;

  Assert.AreEqual(expressionA, expressionB);
}

This looks like it should work however it doesn’t. This is because when using anonymous expressions/delegates the CLR does some magic behind the scene to add a method on the fly, creating a new instance for every anonymous expression/delegate.

So if you have two expressions that are syntactically the same but not the same reference the easiest way to ensure they are the same is to compile the expression and invoke it comparing the resultant value.

[TestMethod]
public void TestDoesWork()
{
  Expression<Func<int, int>> expressionA = x => x + 1;
  Expression<Func<int, int>> expressionB = x => x + 1;

  Assert.AreEqual(expressionA.Compile().Invoke(3), expressionB.Compile().Invoke(3));
}

An alternate approach would be to de-construct each constituent part of the expression trees comparing each part as you go. This however is far more complex.

For a more real world example that involves using Rhino mocks and Expect calls please read on:

Read the rest of this entry »

0

C# 3.0 – Variance Explained

Posted in .Net, C# at July 30th, 2009 by Ben / No Comments »

The problem:

Why can’t I create a List of type Dog and assign it to a List of type Animal?

IList<Animal> animals = new List<Dog>(); // no good

Theory:

There are 3 terms relating to variance:

Covariance – allows more specific types to be assigned to more general types. (i.e. sub-types (classes, interfaces) can be assigned to any types (classes, interfaces) that they inherit from).

C# Example: Method Return types are Covariant. We can return a sub-type of the method’s declaring return type.


IAnimal GetAnimal(string animalName) {...};

GetAnimal("dog") {return new Dog();} // the dog is more specific and returned as the general type IAnimal
GetAnimal("cat") {return new Cat();} // the cat is more specific and returned as the general type IAnimal

Contravariance – allows general types to accept more specific types – i.e. The reverse of covariance.

C# Example: Method parameters are Contravariant. We can call a method with a parameter that is a sub-type of the parameters declaring type.


IAnimal GetAnimal(IAnimal animal) {...};
GetAnimal(new Dog()); // the method takes a general type IAnimal but is called with the more specific type Dog
GetAnimal(new Cat()); // the method takes a general type IAnimal but is called with the more specific type Dog

Invariance – occurs when neither of these conditions are met.

C# Example: In C# 3.0 Generics are invariant. C# 4.0 allows the variance of generics to be defined (with restrictions).


IList<Animal> animals = new IList<Animal>();
animals.Add(new Dog());
animals.Add(new Cat()); 

IList<Animal> animals = new List<Dog>();
animals.Add(new Dog());
animals.Add(new Cat()); // no dice. You can’t assign a cat to a list of dogs.

0

Two nice string extensions

Posted in .Net, C# at July 9th, 2009 by Gerrod / No Comments »

Here’s a couple (well, one is an overload of the other) of string extension methods I wrote today which I’m quite fond of:


/// <summary>
/// Determines if any of the given matches are a case sensitive match for the
/// nominated string value
/// </summary>
/// <param name="text">The string value to be checked</param>
/// <param name="matches">The list of potential matches</param>
static public bool IsIn(this string text, params string[] matches)
{
    return IsIn(text, true, matches);
}

/// <summary>
/// Determines if any of the given matches are a case sensitive match for the
/// nominated string value
/// </summary>
/// <param name="text">The string value to be checked</param>
/// <param name="caseSensitive"><c>true</c> to perform a case
/// sensitive match</param>
/// <param name="matches">The list of potential matches</param>
static public bool IsIn(this string text, bool caseSensitive, params string[] matches)
{
    StringComparison comparer = caseSensitive
        ? StringComparison.CurrentCulture
        : StringComparison.CurrentCultureIgnoreCase;

    return matches.Any(value => text.Equals(value, comparer));
}


So instead of writing this:


if (name == "James" || name == "Peter" || name == "Sally")
    Console.WriteLine("Your name is too generic!");

You can simply write this:


if (name.IsIn("James", "Peter", "Sally")
    Console.WriteLine("Your name is too generic!");

No offence to the James, Peters, and Sallys of the world.

0

Using a generic base class control in WPF

Posted in C#, WPF at June 26th, 2009 by Gerrod / No Comments »

One thing that I find myself doing all the time is creating some type of base class for my windows/controls in WPF:


namespace Editors {
    public class EntityEditorControlBase<TModel> : UserControl
        where TModel : class, IEntityEditorModel {

        public TModel Model {
            get { return DataContext as TModel; }
            protected set { DataContext = value; }
        }
    }
}

Since this is a generic control you need to specify the concrete type arguments when you subclass it. You can do this in your WPF markup via the x:TypeArguments attribute:


<Editors:EntityEditorControlBase
    x:Class="ConcreteEntityEditorControl"
    x:TypeArguments="Models:ConcreteEntityEditorControlModel"
    xmlns:Editors="clr-namespace:Editors">

    <UserControl.Resources>
        <ResourceDictionary Source="../Resources/EditorResources.xaml" />
    </UserControl.Resources>

    <!-- control content here -->

</Editors:EntityEditorControlBase>

Two important things to note:

  • When you want to attach a resource dictionary to the class, you need to do so using the <UserControl.Resources> tag
  • In your base class control, make sure you include the [ContentProperty("Content")] and [DefaultProperty("Content")] tags on your class to avoid the horrible “The type ‘{0}’ does not support direct content” error.
2

Abstracting the Data Access Layer

Posted in .Net, C#, Development at May 18th, 2009 by Ben / 2 Comments »

This article endeavours to describe how to use the Repository Pattern to abstract and control access (CRUD operations) to a data model locally, through mocks and over-the-wire using the Entity Framework and ADO.Net Data services respectively.

By exposing your Data Access model through a defined interface you can replace your data access implementation to suit your needs whether it be for unit testing or to change the data access frameworks you use.

Background:

Microsoft is pushing the ADO.Net Entity Framework as the ORM of choice going forward.

It’s usually a good idea to get behind Microsoft’s frameworks as you know they will build all sorts of cool utilities and other frameworks on top of them and we all want these goodies. (NOTE: I say usually, because sometimes they cease to support frameworks they’ve pushed before eg. Linq-to-Sql).

The E.F has a number of issues that you will find lots of complaints about on the net, with the most annoying being no support for Persistence Ignorance (i.e. POCOs). However, if you can work around this or are fortunate enough to start a new project where your conceptual model hasn’t been defined yet you might still consider using the E.F.

This article won’t go into the arguments for and against the E.F. and is aimed at people who are happy to head down the E.F. path.

When you use the E.F. you’re next step might be to utilize the RESTful framework they’ve built on top of it called ADO.Net Data Services (formerly Astoria). By simply plugging in your E.F. model you can easily expose portions of your data model over the web via a RESTful nature.

Getting automatic exposure to your data model over http is very exciting due to its simplicity and that universal appeal that any client can interact with your server code.

Let’s get started.

The Repository Pattern:



/// 
/// Generic CRUD Repository operations.
/// 
public interface IRepository : IDisposable
{
    T Single<T>(Expression<Func<T, bool>> whereCondition, params string[] includes);
    Collection<T> Get<T>(Expression<Func<T, bool>> whereCondition, params string[] includes);
    Collection<T> Get<T, TKey>(Expression<Func<T, bool>> whereCondition, Expression<Func<T, TKey>> orderBy, bool ascending, params string[] includes);
    Collection<T> Get<T, TKey>(Expression<Func<T, bool>> whereCondition, Expression<Func<T, TKey>> orderBy, bool ascending, int startRow, int pageLength, out long totalCount, params string[] includes);
    Collection<T> GetAll<T>();
    void Delete<T>(T entity);
    void Add<T>(T entity);
    void SaveChanges();
    bool IsDisposed();
}

First we define the Repository interface. The repository interface exposes a generic set of Create, Read, Update and Delete (CRUD) operations to work against any type of Entity – T.

It’s worth noting that the Get operations take a list of “include” parameters. These “includes” explicitly define which relationship properties to explicitly (eagerly) load when returning the Entity (or collection of Entities) of type T.

For example:


var order = repository.Single<Order>(o => o.OrderID == 10250);

When you call Single on an Order entity the Order entity will be returned; however its Customer property will be null by default.

If you wish to return the Order entity with its Customer relationship eagerly loaded you must specify this explicitly.


var order = repository.Single<Order>(o => o.OrderID == 10250, "Customer");

(NOTE: The IRepository interface has been defined this way for two reasons:

  1. The Entity Framework doesn’t support lazy loading of dependent properties (yet!)
  2. Because we are using the same interface for local access to a data store and also for access across the wire using ADO.Net data service it’s best to explictly know exactly what you are pulling across
    from the underlying datastore for bandwidth and performance reasons.

)

Now that we have a generic Repository interface it’s simply a matter of creating the implementations you require. You can create any implementation to wrap whatever Data Access framework you want, including Linq-to-Sql, Entity Framework, NetTiers, NHibernate, Sonic, your own framework, etc.

For the purposes of this article, I have created two implementations:

  1. An entity framework repository.
  2. An ADO.Net Data Service (.Net Client) repository.

The EntityFrameworkRepository implementation works with a VS2008 generated .EDMX ObjectContext instance and utilizes the Microsoft EFExtensions project to add support for SPROC access.

The DataServiceRepository implementation requires ADO.Net Data Services CTP 1.5 to be installed on your machine to utilize query performance improvements (count) and the INotifyPropertyChanged and INotifyCollectionChanged interface implementations on the client proxy objects to implement change-tracking on the entities.

(NOTE: In the future I hope to create a .Net Data Service (Silverlight Client) repository too.)

Once the desired IRepository implementations have been created you may consider creating an IRepositoryFactory implementation to manage the Repository location and lifecycle operations for you.



    /// 
    /// Factory to return instances of .
    /// 
    public interface IRepositoryFactory
    {
        /// <summary>
        /// Get an instance of <see cref="IRepository"/>
        /// </summary>
        /// <param name="name">the name of the repository to return</param>
        /// <returns>an instance of <see cref="IRepository"/></returns>
        IRepository GetRepository(string name);
    }

Access the EF model in-process:


var repository = repositoryFactory.GetRepository("Northwind_Local");
Orders order = repository.Single<Orders>(o => o.OrderID == 10250);

Or to go over the wire:


var repository = repositoryFactory.GetRepository("Northwind_DataService");
Orders order = repository.Single<Orders>(o => o.OrderID == 10250);

Or to mock out for unit testing:


IRepository mockRepository = MockRepository.GenerateMock<IRepository>();
Expression<Func<Orders,bool>> whereCondition = o => o.OrderID == 3;
mockRepository.Stub(r => r.Single(whereCondition)).Return(new Orders() { OrderID = 3 });
RepositoryFactory.SetRepository("Northwind_Local", mockRepository);

IRepository repository = _repositoryFactory.GetRepository("Northwind_Local");
Orders order = repository.Single(whereCondition);

Where to next:

Download the Repository Pattern VS 2008 SP1 Solution.

Install the ADO.Net Data Services CTP 1.5 installer found under /3rdPartyAssemblies/ADONETDataServices_v15_CTP1.exe in the zip file download.

Then set an environment variable dscodegen_databinding value to 1.
This ensures service reference generation in VS2008 uses CTP version and not the old school version. View the video in this link for more info.

Once you are setup, open up the various unit test classes to see how to utilize the various implementations. The EF model is generated against the Northwind database (included as a file reference).

Reference Links:

Persistence Ignorance
http://blogs.msdn.com/dsimmons/archive/2007/06/02/persistence-ignorance-ok-i-think-i-get-it-now.aspx

Repository Pattern
http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/10/08/the-repository-pattern.aspx

Repository Pattern with EF

Data Access with Repository
http://blogs.microsoft.co.il/blogs/kim/archive/2008/11/12/data-access-with-the-entity-framework.aspx

Testable Data Access with the Repository Pattern
http://blogs.microsoft.co.il/blogs/kim/archive/2008/11/14/testable-data-access-with-the-repository-pattern.aspx

Entity Framework – Some Common Hurdles
http://blogs.microsoft.co.il/blogs/kim/archive/2008/11/17/entity-framework-some-common-hurdles.aspx

ADO.Net Data Services CTP – 1.5

ADO.Net Data Services Blog
http://blogs.msdn.com/astoriateam/default.aspx

Data Binding (ie.implements INotifyPropertyChanged and INotifyCollectionChanged interfaces)
http://blogs.msdn.com/astoriateam/archive/2009/03/21/ado-net-data-services-v1-5-ctp1-data-binding-overview.aspx

Microsoft EFExtensions
http://code.msdn.microsoft.com/EFExtensions

2

Coding better: It’s the little things.

Posted in C# at February 25th, 2009 by Gerrod / 2 Comments »

I really don’t like inefficiency in code. Some people would say I’m quite the coding nazi when it comes to stuff like this; I’m sorry, but I just don’t like having code that exists just because someone thinks “it makes it read more like english”. Sorry, but C# != English.

Don’t get me wrong; I’m all for writing clear, concise code. I strongly encourage using descriptive method names, and fully expressed variable names (e.g. “requestContext” instead of “rc”). But all I’m saying is, don’t over-do it! Here are three small tips you can use to work around small inefficiencies in your code.

Use System.Math
How many times have you come across a segment of code like this?


if (waitTimeMillis < MaxPingTime) {
    waitTimeMillis *= 2;
    if (waitTimeMillis > MaxPingTime) {
        waitTimeMillis = MaxPingTime;
    }
}

Sure, it looks pretty harmless, but we need to read three lines of code to work out that there is an upper limit on waitTime. We can better express that using the Math.Min function:


if (waitTimeMillis < MaxPingTime) {
    waitTimeMillis = Math.Min(waitTimeMillis * 2, MaxPingTime);
}

A boolean is a boolean
I remember one of our lecturers at uni first pointed this one out to me when we were learning java. Comparing a boolean expression to true or false is redundant - just evaluate the expression instead. So, don't do this - ever:


if (MyClass.IsInitialised == true) {
    RunPostInitialisation();
}

No folks, I don't want to see "== true" or "== false" in your code, ever. I guess it could be worse, you could have "!= true"... - either way, lets keep it simple:


if (MyClass.IsInitialised) {
    RunPostInitialisation();
}

Use ternary expressions instead of if/else
Do you really need that if/else clause?


if (house.NumberOfOccupants > 1) {
    house.MaximumNumberOfPets = 3;
} else {
    house.MaximumNumberOfPets = 2;
}

There are circumstances where an if/else clause may be justifiable; but in general, they aren't needed. A ternary expression is much more succinct:


house.MaximumNumberOfPets = house.NumberOfOccupants > 1 ? 3 : 2;

Where the values that you're using for the true/false evaluation of the expression are a bit more complex, you can separate this on to multiple lines to read a bit more clearly:


Type type = Instruments.ContainsKey(instrumentType)
    ? Instruments[instrumentType]
    : UnknownInstrumentType;

Code better!