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

Creating your own ContentTemplates in WPF

Posted in .Net, WPF at December 23rd, 2009 by Gerrod / 1 Comment »

This isn’t something that I do often, but rolling your own look-and-feel by starting a ContentTemplate from scratch can be a right pain in the botty. Today I found this excellent sample project from Microsoft, which contains custom ContentTemplates for most UI controls in the framework. It provides an excellent starting point for creating your own customized controls.

Check it out!

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?

0

Containing floats in HTML

Posted in Asp.Net at November 27th, 2009 by Gerrod / No Comments »

Have you ever created a block-level element (e.g. a div), whose only contents are floating elements – only to find that your block-level element doesn’t stretch down to contain it’s children? Well, I have, and it’s a problem that always annoys me because I can never bring to mind the easiest way of fixing it.

The simplest solution is to use “overflow:hidden” in the style of your parent element, however this doesn’t work for all browsers scenarios. So, for a much more comprehensive description of the problem, as well as a number of approaches you can use to solve it, check out this post.

2

AutoMapper

Posted in .Net at November 15th, 2009 by Drew / 2 Comments »

Ever had those mundane tasks of mapping your entities to Data Transfer Objects for use in your service layer? While browsing the web the other day I found this great tool called AutoMapper which does a superb job in filling this void.

Writing mapping code is painful, creates more work and means you have more tests to write. This is where AutoMapper fits in.

Given the following entities:

public class Bank {
public string Name{ get; set; }
}

public class Customer {
public string Name { get; set; }
public Bank BankDetails{ get; set; }
}

public class CustomerDTO {
public string Name { get; set; }
public string BankName{ get; set; }
}

Now all we need to do is use the mapper in code like so:

AutoMapper.CreateMap<Customer, CustomerDTO>(); //setup the mappings
Customer newCustomer = new Customer() {Name = "test" };
CustomerDTO transformedCustomer = AutoMapper.Map<Customer, CustomerDTO>(newCustomer);

Brilliant! We now have a working CustomerDTO object and it even mapped our BankName for us without even setting up any custom mapping. Here is what AutoMapper can do for you:

  • Matching property names
  • Methods starting with the word “Get” automatically get mapped. e.g. GetAccountBalance() maps to AccountBalance
  • Nested property names (Bank.Name maps to BankName, pretty sure this only works with PascalCase)

AutoMapper can also map collections for you too. One of the things to remember here is you don’t need to create a mapping for collections, just the element types.

For the testers amongst us I hear you say that you now can’t test your mappings like you could before with custom mapping code. Well there is an answer to this.

Mapper.AssertConfigurationIsValid();

This method will assert that all properties from the source will be mapped to something on the destination object. Mapping objects is now no longer painful!

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

What Is a Race Condition?

Posted in .Net, Asp.Net, Javascript at October 6th, 2009 by Drew / No Comments »

Just thought I would put a post out on something I learnt today that can occur when using ajax- a race condition. A race condition is is where the output or result of something is dependent on the timing of other events/code. A good example of this is below:

function ValidateInput() {
//some slow running code here...
}

function SaveForm() {
//save the form
}

<form>
<input type="text" onchange="ValidateInput()" />
<input type="button" onclick="SaveForm();" value="Submit" />
</form>

The problem here can occur when the user hits the Submit button before the validation method can finish. One way to overcome this is use a semaphore to indicate whether the form still needs validating on the SaveForm method.

1

Get a TreeViewItem’s Parent item

Posted in .Net at September 15th, 2009 by Drew / 1 Comment »

Further to Gerrod’s post on selecting an item in a treeview, I found myself scratching my head on how to find a treeviewitem’s parent item. Here I was expecting a TreeViewItem.Parent property. Unfortunately after scouring the dark depths of the internet, I found that using the VisualTreeHelper class was the answer:


private static TreeViewItem GetParentTreeViewItem(DependencyObject item)

{
if (item != null)
{
  DependencyObject parent = VisualTreeHelper.GetParent(item);
  TreeViewItem parentTreeViewItem = parent as TreeViewItem;
  return parentTreeViewItem ?? GetParentTreeViewItem(parent);
}

return null;
}

I’m sure this can be easily converted into an extension method for those of you expecting the Parent property like I was.

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 »