Monday, December 31, 2012

CookieContainer for HttpWebRequest

Happy New Year!

Are you making a series of HttpWebRequests where you need to persist cookies? For example, perhaps you are experiencing an infinite series of authentication hops. Don't worry, this is very easy to resolve by using the System.Net.CookieContainer class.

xUnit Example

[Theory]
[InlineData("http://www.yahoo.com", 0)]
[InlineData("http://www.google.com", 2)]
[InlineData("http://www.bing.com", 8)]
public void CookieJarCount(string requestUriString, int expectedCookieCount)
{
    var request = (HttpWebRequest) HttpWebRequest.Create(requestUriString);
 
    // Create a CookieContainer and assign it to the request.
    var cookieJar = new CookieContainer(); 
    request.CookieContainer = cookieJar;
 
    // Make the request like normal.
    var response = (HttpWebResponse) request.GetResponse();
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
 
    // Let's see how many cookies are in the cookie jar!
    Assert.Equal(expectedCookieCount, cookieJar.Count);
}
Shout it

Enjoy,
Tom

Wednesday, November 28, 2012

XNA and Visual Studio 2012 on Windows 8

Microsoft does not always make it easy to use their latest toys.

The Good
I recently rebuilt my computer and, wanting to stay on the forefront of technology, I of course installed Windows 8 and Visual Studio 2012. Both products come with a series of pros and cons, but the quick boot up times of Windows 8 and the parallel builds of Visual Studio 2012 make them both winners in my book.

The Bad
That being said, the first project that I wanted to work on after rebuilding my machine was a small XNA game that I have been writing for a while now. Unfortunately that XNA has been unofficially retired, and Microsoft is not making it easy for people to continue using their product.

And The Ugly
To use XNA on Windows 8 you must first download and install Games for Windows LIVE Redistributable. Then you must install XNA Studio into Visual Studio 2010 and manually copy the installed assemblies to Visual Studio 2012.

Here are the details:

I hope that helps,
Tom

Saturday, November 17, 2012

jQuery Refresh Page Extension

There are three scenarios when a web page refreshes:

  1. Honors your cache (does not make resource requests).
  2. Verifies your cache (causes resources to generate 304s).
  3. Ignores your cache (causes resources to generate 200s).

For a simple page refresh you want your webpage to generate as few server requests as possible. There any many ways to refresh a page in JavaScript, however they can all have different and sometimes undesirable results. Let's look some code snippets of the aforementioned scenarios in reverse order.

3. Ignore Cache

window.location.reload(true);

This scenario is not usually necessary unless you know that the resources of your page have been updated. Also, using a good minification framework is probably a better way of ensuring that your clients always consume the latest resources with every request.

2. Verify Cache

window.location.reload();

This is obvious similar to the first call, only we are calling an override of the reload method that tells the browser to respect cache. However, this will still cause a series of 304 requests!

1. Honor Cache

window.location.href = window.location.href;

This is obviously a very simple way to refresh the page, and it will honor cache without forcing 304 requests. However, this will not work if your includes a hash tag.

jQuery Plugin

This little jQuery plugin will refresh the page and try to cause as few resource requests as possible.

(function($) {
    $.refreshPage = refreshPage;
    
    function refreshPage(reload) {
        if (reload === true) {
            window.location.reload(true);
            return;
        }
        
        var i = window.location.href.indexOf('#');
        if (i === -1) {
            // There is no hash tag, refresh the page.
            window.location.href = window.location.href;
        } else if (i === window.location.href.length - 1) {
            // The hash tag is at the end, just strip it.
            window.location.href = window.location.href.substring(i);
        } else {
            // There is a legit hash tag, reload the page.
            window.location.reload(false);
        }
    }
})(jQuery);
Shout it

Enjoy,
Tom

Friday, October 26, 2012

xUnit Visual Studio Integration

Good news, everyone! It is actually very easy to get xUnit completely integrated with Visual Studio. You only need to install two plugins...

VS2010 - xUnit Test Runner Extension

This will support running tests with a Visual Studio test project.
This includes all of the VS features, such as code coverage!

https://github.com/quetzalcoatl/xvsr10/downloads

ReSharper - xUnit Contrib Plugin

This will allow ReSharper to detect and run xUnit tests.

http://xunitcontrib.codeplex.com/releases/view/92101
(If you are still running Resharper 6, then you will need the latest: v6.1.1)

Team Build (TFS) Integration

Integrating with xUnit your Team Foundation Server is a very tricky proposition, but it can be done. That, however, is a (rather long) blog post for another day!

Shout it

Enjoy,
Tom

Monday, October 22, 2012

How to Unlock a Configuration Section from IIS Manager

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

If you have ever experienced this problem then you probably have also experienced the fun of digging through your system configuration files to find where to unlock the related authentication sections. This is, to say the least, not fun.

Did you know that you can unlock configuration sections from IIS Manager?

  1. Launch IIS Manager.
  2. Select your Connection's home page.
  3. Open the Configuration Editor under Management.
  4. Navigate to the section that you need to unlock.
  5. Look to the right Action pane and click unlock!

Shout it

Enjoy,
Tom

Tuesday, September 25, 2012

Func Injection in Unity

Let your container be your factory. :)

If you are using LinqToSql and dependency injection, then you have probably created a factory with which you create DataContexts. But what if you could just let your IOC Container do that work for you? You can!

If you are using Unity then you can inject a Func<T> of any registered type. Unity will automatically bind the injected Func to the container's resolve method, thus preserving the resource Lifetime Manager.

Example Code

public class FuncInjectionTests
{
    [Fact]
    public void TransientLifetimeFuncIsThreadsafe()
    {
        var container = new UnityContainer();
 
        container
            .RegisterType<IUserService, UserService>(
                new ContainerControlledLifetimeManager())
            .RegisterType<IDataContext, DataContext>(
                new TransientLifetimeManager());
 
        var parallelOptions = new ParallelOptions {MaxDegreeOfParallelism = 100};
 
        Parallel.For(0, 1000, parallelOptions, i =>
        {
            var userService = container.Resolve<IUserService>();
 
            Parallel.For(0, 1000, parallelOptions, j =>
            {
                userService.Update();
            });
        });
 
        Assert.Equal(1, UserService.Count);
        Assert.Equal(1000000, DataContext.Count);
    }
}
 
public interface IUserService
{
    void Update();
}
 
public interface IDataContext : IDisposable
{
    void UpdateUser();
}
 
public class UserService : IUserService
{
    public static int Count;
 
    private readonly Func<IDataContext> _dataContextFactory;
 
    public UserService(Func<IDataContext> dataContextFactory)
    {
        _dataContextFactory = dataContextFactory;
        Interlocked.Increment(ref Count);
    }
 
    public void Update()
    {
        using (var dataContext = _dataContextFactory())
            dataContext.UpdateUser();
    }
}
 
public class DataContext : IDataContext
{
    public static int Count;
 
    public DataContext()
    {
        Interlocked.Increment(ref Count);
    }
 
    public void UpdateUser()
    {
        Trace.WriteLine(Thread.CurrentThread.ManagedThreadId + " - " + Count);
    }
 
    public void Dispose()
    {
    }
}
Shout it

Enjoy,
Tom

Thursday, August 30, 2012

WebDrivers in Parallel

Here is a post that is long over due, and is finally getting published by request!

Concurrent WebDrivers

A WebDriver is not thread safe, but it is not required to be a singleton either. If you instantiate multiple drivers, they can all be run at the same time. If you cast a series of drivers into a collection of the IWebDriver interface, and then throw that into a Parallel ForEach, you have yourself one fun toy to play with!

So what are some uses of this?

Admittedly it is not a particularly common or practical use case to have multiple automated browser sessions running at the same time, but it can still come in handy. One fun application is to test website concurrency. You can do a minor load test of a webpage, or your can have two sessions trying to race each other for a limited resource.

...also, running WebDrivers in parallel can make for a killer demo!

Sample Code (xUnit Test)

public class ParallelDemo : IDisposable
{
    public IList<IWebDriver> Drivers { get; private set; }
 
    public ParallelDemo()
    {
        Drivers = new List<IWebDriver>
        {
            new InternetExplorerDriver(),
            new FirefoxDriver(),
            new ChromeDriver()
        };
    }
 
    public void Dispose()
    {
        foreach (var driver in Drivers)
        {
            driver.Close();
            driver.Dispose();
        }
    }
 
    [Fact]
    public void ParallelSearch()
    {
        Parallel.ForEach(Drivers, SearchForTom);
    }
 
    private static void SearchForTom(IWebDriver driver)
    {
        driver.Url = "https://www.google.com/#q=tom+dupont";
        var firstResult = driver.FindElement(By.CssSelector("h3 > a.l"));
        Assert.Contains("Tom DuPont .NET", firstResult.Text);
    }
}
Shout it

Enjoy,
Tom

Saturday, August 18, 2012

Linq to Sql Batch Future Queries

Batch queries are crucial feature of any good ORM...including LinqToSql!

Future queries are an unobtrusive and easy to use way of batching database queries into a lazy loaded data structures. Future queries were originally a feature of NHibernate, and have since been ported to other ORMs. However I am currently working on a project where I do not have access to those tools.

Thus I created LinqToSql.Futures, a simple extension that adds batched futures queries to LinqToSql.

Using Future Queries

  1. Get the LinqToSqlFutures NuGet package.
  2. Extend your DataContext to implement IFutureDataContext. (This is optional, see below!)
  3. Use future queries!

To batch queries together, simply call the ToFuture extension method on your IQueryables, this will return a Lazy collection of entities. The first time that one of the Lazy collections is accessed, all of the pending queries will be batched and executed together.

[Fact]
public void ToFuture()
{
    // SimpleDataContext Implements IFutureDataContext 
    using (var dataContext = new SimpleDataContext())
    {
        Lazy<IList<Person>> people = dataContext.Persons
            .Where(p => p.FirstName == "Tom" || p.FirstName == "Cat")
            .ToFuture();
 
        Lazy<IList<Pet>> pets = dataContext.Pets
            .Where(p => p.Name == "Taboo")
            .ToFuture();
 
        // Single database call!
        Assert.Equal(2, people.Value.Count);
        Assert.Equal(1, pets.Value.Count);
    }
}

To see the future queries working, you can use SqlProfiler to capture the batch query:

Extending Your DataContext

To use the code above, you need only extend your generated DataContext to implement the IFutureDataContext interface (which consists of a mere one property). Additionally, the sample code below overrides the Dispose method to optimize query disposal.

partial class SimpleDataContext : IFutureDataContext
{
    protected override void Dispose(bool disposing)
    {
        if (_futureCollection != null)
        {
            _futureCollection.Dispose();
            _futureCollection = null;
        }
 
        base.Dispose(disposing);
    }
 
    private IFutureCollection _futureCollection;
    public IFutureCollection FutureCollection
    {
        get
        {
            if (_futureCollection == null)
                _futureCollection = this.CreateFutureCollection();
 
            return _futureCollection;
        }
    }
}

Do you not have access to extend your DataContext? No problem...

Alternative Consumption

Your DataContext does not need to implement IFutureDataContext to use future queries. You can also create a FutureCollection and pass that into the ToFuture method. This will provide the future queries with a batch context.

[Fact]
public void FutureCollection()
{
    using (var dataContext = new SimpleDataContext())
    using (var futureCollcetion = dataContext.CreateFutureCollection())
    {
        Lazy<IList<Person>> people = dataContext.Persons
            .Where(p => p.FirstName == "Tom" || p.FirstName == "Cat")
            .ToFuture(futureCollcetion);
 
        Lazy<IList<Pet>> pets = dataContext.Pets
            .Where(p => p.Name == "Taboo")
            .ToFuture(futureCollcetion);
 
        // Single database call!
        Assert.Equal(2, people.Value.Count);
        Assert.Equal(1, pets.Value.Count);
    }
}

Links

If you enjoy the future queries or need to extend them, then please feel free to download the source from GitHub.

LinqToSql.Futures on GitHub
LinqToSql.Futures on NuGet

Shout it

Enjoy,
Tom

Sunday, July 29, 2012

Lazy Unity Injection

Adapting a legacy project to use proper Dependency Injection can be difficult.

Often times your services can not be singletons, and then those dependencies cause chains of other services to require transient lifetimes. Sometimes these service dependency trees can grow deep, and their initialization can become quite expensive. If you are working with a website, those big trees can add up and cost a lot of time and memory with every request.

One way to trim a deep or expensive dependency tree is to inject Lazy types of your services.

Lazy injection will prevent an optional resource from being instantiated until it is actually needed. While this is not a scenario that you want to architect your application into voluntarily, it can be a crucial performance optimization. Have you ever taken a memory dump of your website and found thousands of services floating in memory? I have, and let me assure you, it's not pretty!

LazyExtension for Unity

public class LazyExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        Context.Policies.Set<IBuildPlanPolicy>(
            new LazyBuildPlanPolicy(), 
            typeof(Lazy<>));
    }
 
    public class LazyBuildPlanPolicy : IBuildPlanPolicy
    {
        public void BuildUp(IBuilderContext context)
        {
            if (context.Existing != null)
                return;
 
            var container = context.NewBuildUp<IUnityContainer>();
            var typeToBuild = context.BuildKey.Type.GetGenericArguments()[0];
            var nameToBuild = context.BuildKey.Name;
            var lazyType = typeof(Lazy<>).MakeGenericType(typeToBuild);
 
            var func = GetType()
                .GetMethod("CreateResolver")
                .MakeGenericMethod(typeToBuild)
                .Invoke(this, new object[] { container, nameToBuild });
 
            context.Existing = Activator.CreateInstance(lazyType, func);
 
            DynamicMethodConstructorStrategy.SetPerBuildSingleton(context);
        }
 
        public Func<T> CreateResolver<T>(
            IUnityContainer currentContainer, 
            string nameToBuild)
        {
            return () => currentContainer.Resolve<T>(nameToBuild);
        }
    }
}

Unit Tests

public interface ITestClass
{
    int HighFive();
}
 
public class TestClass : ITestClass
{
    public static int InstanceCount = 0;
 
    public TestClass()
    {
        Interlocked.Increment(ref InstanceCount);
    }
 
    public int HighFive()
    {
        return 5;
    }
}
 
[TestFixture]
public class TestFixture
{
    [Test]
    public void Test()
    {
        using (var container = new UnityContainer())
        {
            container.RegisterType<ITestClass, TestClass>();
            container.AddNewExtension<LazyExtension>();
 
            var testClass1 = container.Resolve<Lazy<ITestClass>>();
 
            Assert.AreEqual(false, testClass1.IsValueCreated);
            Assert.AreEqual(0, TestClass.InstanceCount);
 
            Assert.AreEqual(5, testClass1.Value.HighFive());
            Assert.AreEqual(true, testClass1.IsValueCreated);
            Assert.AreEqual(1, TestClass.InstanceCount);
 
            var testClass2 = container.Resolve<Lazy<ITestClass>>();
 
            Assert.AreEqual(false, testClass2.IsValueCreated);
            Assert.AreEqual(1, TestClass.InstanceCount);
 
            Assert.AreEqual(5, testClass2.Value.HighFive());
            Assert.AreEqual(true, testClass2.IsValueCreated);
            Assert.AreEqual(2, TestClass.InstanceCount);
        }
    }
}
kick it on DotNetKicks.com

Enjoy,
Tom

Saturday, June 16, 2012

.NET BlockingQueue

Task.Factory.StartNew is great, but often abused.

Do you need to make a call that could take a long time to complete, but you don't care about the results? If so, then you need to make an async call. Should you make these calls by constantly creating and starting new Tasks? No, as this could use up a lot of resouces, exhaust your thread pool, or possibly even tear down your app domain.

I was recently introduced to System.Collections.Concurrent.BlockingCollection, and I absolutely love that class. However, 99% of my use cases with BlockingCollections are actually more specific to queuing. My solution: create a generic BlockingQueue!

Simple File Example

public class SimpleFile
{
    public string Path { get; set; }
    public string Contents { get; set; }
}
 
public class SimpleFileQueue : BlockingQueue<SimpleFile>
{
    public SimpleFileQueue(int threadCount) : base(threadCount) { }
 
    protected override void ProcessModel(SimpleFile model)
    {
        System.IO.File.WriteAllText(model.Path, model.Contents);
    }
 
    protected override void HandleException(Exception ex)
    {
        // TODO: Log me!
    }
}
 
public static class SimpleFileExample
{
    public static readonly SimpleFileQueue Queue = new SimpleFileQueue(3);
 
    public static void EnqueueSimpleFile(string path, string content)
    {
        Queue.Enqueue(new SimpleFile
        {
            Path = path,
            Contents = content
        });
    }
}

BlockingQueue<T> Implementation

public abstract class BlockingQueue<T> : IDisposable
{
    #region Private Members
 
    private const int Timeout = 60000;
 
    private bool _disposed;
    private readonly CancellationTokenSource _tokenSource;
    private readonly BlockingCollection<T> _collection;
    private readonly Task[] _tasks;
 
    #endregion
 
    #region Public Properties
 
    public int Count
    {
        get { return _collection.Count; }
    }
 
    public bool IsCanceled
    {
        get { return _tokenSource.IsCancellationRequested; }
    }
 
    public bool IsCompleted
    {
        get { return _tasks.All(t => t.IsCompleted); }
    }
 
    #endregion
 
    #region Constructor & Destructor
 
    protected BlockingQueue(int threadCount)
    {
        _tokenSource = new CancellationTokenSource();
            
        var queue = new ConcurrentQueue<T>();
        _collection = new BlockingCollection<T>(queue);
 
        _tasks = new Task[threadCount];
        for(var i=0; i<threadCount; i++)
            _tasks[i] = Task.Factory.StartNew(ProcessQueue);
    }
 
    ~BlockingQueue()
    {
        Dispose(true);
    }
 
    #endregion
 
    #region Abstracts
 
    protected abstract void HandleException(Exception ex);
 
    protected abstract void ProcessModel(T model);
 
    #endregion
 
    #region Methods
 
    public void Enqueue(T model)
    {
        if (IsCompleted)
            throw new Exception("BlockingQueue has been Completed");
 
        if (IsCanceled)
            throw new Exception("BlockingQueue has been Canceled");
 
        _collection.Add(model);
    }
 
    public void Cancel()
    {
        if (!IsCanceled)
            _tokenSource.Cancel(false);
    }
 
    public void CancelAndWait()
    {
        Cancel();
        Task.WaitAll(_tasks);
    }
 
    private void ProcessQueue()
    {
        while (!IsCanceled)
        {
            try
            {
                T model;
                var result = _collection.TryTake(out model, Timeout, _tokenSource.Token);
 
                if (result && model != null)
                    ProcessModel(model);
            }
            catch (OperationCanceledException)
            {
                break;
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
    }
 
    #endregion
 
    #region IDisposable
 
    public void Dispose()
    {
        Dispose(false);
    }
 
    private void Dispose(bool finalizing)
    {
        if (_disposed)
            return;
 
        Cancel();
 
        if (!finalizing)
            GC.SuppressFinalize(this);
 
        _disposed = true;
    }
 
    #endregion
}
Shout it

Enjoy,
Tom

Sunday, May 20, 2012

MvcBundleConfig NuGet Package

MvcBundleConfig is now available on NuGet!

MvcBundleConfig is a very simple project that adds configuration and debugging features to MVC 4's bundling framework. Once you create a new MVC4 web application and install the MvcBundleConfig NuGet Package, then you need only update our layout to use the new bundle extension methods, and you are ready to go!

Please note that the System.Web.Optimization NuGet package is still in beta, and thus that dependency is not included in the current version of the NuGet package. However, if you have created a new MVC4 project then that assembly should already be included.

Sample Installation Steps

  1. Create a new ASP.NET MVC 4 Project
  2. Select Manage NuGet Packages
  3. Search for and install MvcBundleConfig
  4. Update the Layout
kick it on DotNetKicks.com

Enjoy,
Tom

Friday, May 4, 2012

Configuring WebClient Timeout and ConnectionLimit

Simplicity is nice, but not when it comes at the expense off accomplishing your goal.

Recently I have been using System.Net.WebClient to access some REST APIs. It is great how simple the WebClient class is to use, but unfortunately it does not natively support configuring it's timeout or connection limit. In fact, before I knew that the default connection limit was preventing me from making more than two concurrent requests at a time, it was actually causing me some serious issues while doing performance testing.

Good news, both of these issues are very easy to fix by simply extending the WebClient class.

Sample Class

public class ConfigurableWebClient : WebClient
{
    public int? Timeout { get; set; }
    public int? ConnectionLimit { get; set; }
        
    protected override WebRequest GetWebRequest(Uri address)
    {
        var baseRequest = base.GetWebRequest(address);
        var webRequest = baseRequest as HttpWebRequest;
        if (webRequest == null)
            return baseRequest;
 
        if (Timeout.HasValue)
            webRequest.Timeout = Timeout.Value;
 
        if (ConnectionLimit.HasValue)
            webRequest.ServicePoint.ConnectionLimit = ConnectionLimit.Value;
 
        return webRequest;
    }
}
kick it on DotNetKicks.com

Enjoy,
Tom

Saturday, April 14, 2012

xUnit Theory, the Data Driven Unit Test

Update: I have also written a post about NUnit's Data Driven TestCaseAttribute.

Do you like copying and pasting code? Neither do I.

A good set of unit tests often end up reusing the same code with varied inputs. Rather than copy and paste that test code over and over, we can use the pattern of data driven unit tests to help streamline our test fixtures. This is the practice of having a single test definition be invoked and count as multiple tests at run time. This also enables us to do other dynamic things, such as configuring our unit tests from external sources. :)

I frequently use MSTest, but it's data driven tests inconveniently require you to define a DataSource. (Updated) Come to find out NUnit does offer data driven unit tests with their TestCaseSource attribute. Meanwhile xUnit offers several lightweight and simple options for defining data driven tests, which it refers to as theories.

Let's take a look at some of xUnit's Theory data sources:

InlineData Example

public class StringTests1
{
    [Theory,
    InlineData("goodnight moon", "moon", true),
    InlineData("hello world", "hi", false)]
    public void Contains(string input, string sub, bool expected)
    {
        var actual = input.Contains(sub);
        Assert.Equal(expected, actual);
    }
}

PropertyData Example

public class StringTests2
{
    [Theory, PropertyData("SplitCountData")]
    public void SplitCount(string input, int expectedCount)
    {
        var actualCount = input.Split(' ').Count();
        Assert.Equal(expectedCount, actualCount);
    }
 
    public static IEnumerable<object[]> SplitCountData
    {
        get
        {
            // Or this could read from a file. :)
            return new[]
            {
                new object[] { "xUnit", 1 },
                new object[] { "is fun", 2 },
                new object[] { "to test with", 3 }
            };
        }
    }
}

ClassData Example

public class StringTests3
{
    [Theory, ClassData(typeof(IndexOfData))]
    public void IndexOf(string input, char letter, int expected)
    {
        var actual = input.IndexOf(letter);
        Assert.Equal(expected, actual);
    }
}
 
public class IndexOfData : IEnumerable<object[]>
{
    private readonly List<object[]> _data = new List<object[]>
    {
        new object[] { "hello world", 'w', 6 },
        new object[] { "goodnight moon", 'w', -1 }
    };
 
    public IEnumerator<object[]> GetEnumerator()
    { return _data.GetEnumerator(); }
 
    IEnumerator IEnumerable.GetEnumerator()
    { return GetEnumerator(); }
}
kick it on DotNetKicks.com

Happy testing!
Tom

Sunday, April 8, 2012

Migrating from NUnit to xUnit

I recently started using xUnit, and I have been really enjoying it!

If you are currently using NUnit to write your unit tests, then it is not at all difficult to migrate to using xUnit. The philosophical difference between the two is simply this: with xUnit you need to think of your tests as objects, rather than of methods. Or if you prefer acronyms: put some more OOP into your TDD. *bu-dum, tish!*

Anyway, here is a visual representation of equivalent commands between NUnit and xUnit:

xUnit

NUnit

[NUnit.Framework.TestFixture]
public class TestFixture
{
  [NUnit.Framework.TestFixtureSetUp]
  public void TestFixtureSetUp()
  {
    // 1) Set up test fixture  -------->
  }
  [NUnit.Framework.TestFixtureTearDown]
  public void TestFixtureTearDown()
  {
    // 8) Tear down test fixture  ----->
  }
 
 
 
  [NUnit.Framework.SetUp]
  public void SetUp()
  {
    // 2) Set up TestA  --------------->
    // 5) Set up TestB  --------------->
  }
  [NUnit.Framework.Test]
  public void TestA()
  {
    // 3) Run TestA  ------------------>
  }
  [NUnit.Framework.Test]
  public void TestB()
  {
    // 6) Run TestB.  ----------------->
  }
  [NUnit.Framework.TearDown]
  public void TearDown()
  {
    // 4) Tear down TestA  ------------>
    // 7) Tear down TestB  ------------>
  }
}
 
public class TestData : IDisposable
{
 
  public TestData()
  {
    // 1) Set up test fixture
  }
 
  public void Dispose()
  {
    // 8) Tear down test fixture
  }
}
public class TestClass
  : IDisposable, Xunit.IUseFixture
{
  public TestClass()
  {
    // 2) Set up TestA
    // 5) Set up TestB
  }
  [Xunit.Fact]
  public void TestA()
  {
    // 3) Run TestA
  }
  [Xunit.Fact]
  public void TestB()
  {
    // 6) Run TestB
  }
 
  public void Dispose()
  {
    // 4) Tear down TestA
    // 7) Tear down TestB
  }
  public TestData TestData { get; set; }
  public void SetFixture(TestData data)
  {
    // 2.5) Set fixture data for TestA
    // 5.5) Set fixture data for TestB
    TestData = data;
  }
}
kick it on DotNetKicks.com

Happy testing!
~Tom

Saturday, March 31, 2012

Configuring Bundles in MVC 4

We write a lot of JavaScript.

Thus the bundling, compression, and minification of JavaScript is important to the speed and performance of modern websites. This is why I love and have been a big advocate of tools like Combres, and also why I was so excited to hear that such features were (finally) coming built in to ASP.NET MVC 4.

Introducing MvcBundleConfig

MvcBundleConfig is a very simple minimalist project I wrote to add configuration and debugging features to MVC 4's bundling framework, and achieves all 6 six of the goals listed below. It requires only MVC4 to run, and you need only add one config file to your project, one line of code to your application start, and you are off and running.

NuGet Package: https://nuget.org/packages/MvcBundleConfig/

Source on GitHub: https://github.com/tdupont750/MvcBundleConfig

Before we get to the demonstration at the bottom, let's review the needs and wants of a good minification framework.

What I NEED in a minification tool:

  1. Compress resources into single files.
    • Multiple request take time and resources, neither of which are things that any of us have to spare. By compressing resources into single requests and can limit the overhead and load time on both our clients and our servers.
  2. Minify JavaScript and CSS content.
    • Minification removes as many unnecessary white spaces and characters as possible from your resource files, reducing file size by up to 80% on average. When then compounded with gzip, we can reduce the file size another 50%. This means that our web applications can be brought down to clients 90% faster.
  3. Make use of both client and server side caching.
    • Making 90% less requests is nice, and making those requests 90% smaller is even better, but only ever having to request or serve them once is the key to true performance. Unfortunately client and server caching can be a bit complex due to quirks of different technologies and browsers. A good minification framework should abstract these concerns away from us.
  4. Ability to turn off during debugging.
    • As fantastic as everything that we have listed about is for a production website, it is a nightmare for a development website. Debugging JavaScript is no less complicated or time consuming than debugging C#, and we need to be able to use a debuggers and other client side tools that are inhibited by minification. A good minification framework must expose a debugging mode that skips compression pipeline.

What I WANT in a minification tool:

  1. Simple and dynamic configuration.
    • I hate hardcoded configuration. It bloats my code, and it requires bin drops to deploy. Meanwhile I really like the ability to add simple configuration files to my site as often as I can. Config files are explicit, abstract, and can be updated at any time. Win.
  2. Take a few dependencies as possible.
    • I mentioned above that I like Combres and it has a reasonably sized code base, unfortunately the fact that it's NuGet package pulls down half a dozen additional dependencies makes it feel quite heavy. The fewer dependencies a framework takes the better.

MvcBundleConfig Examples

Bundles.config

<?xml version="1.0"?>
<bundleConfig ignoreIfDebug="true" ignoreIfLocal="true">
  <cssBundles>
    <add bundlePath="~/css/shared">
      <directories>
        <add directoryPath="~/content/" searchPattern="*.css" />
      </directories>
    </add>
  </cssBundles>
  <jsBundles>
    <add bundlePath="~/js/shared" minify="false">
      <files>
        <add filePath="~/scripts/jscript1.js" />
        <add filePath="~/scripts/jscript2.js" />
      </files>
    </add>
  </jsBundles>
</bundleConfig>

Global.asax.cs

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    BundleTable.Bundles.RegisterTemplateBundles();
 
    // Only code required for MvcBundleConfig wire up
    BundleTable.Bundles.RegisterConfigurationBundles();
}

_Layout.cshtml

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <title>@ViewBag.Title</title>
 
        @* Call bundle helpers from MvcBundleConfig *@
        @Html.CssBundle("~/css/shared")
        @Html.JsBundle("~/js/shared")
    </head>
    <body>
        @RenderBody()
    </body>
</html>

In the Browser

NuGet Package: https://nuget.org/packages/MvcBundleConfig/

Source on GitHub: https://github.com/tdupont750/MvcBundleConfig

kick it on DotNetKicks.com

Enjoy,
Tom

Sunday, March 11, 2012

Converting SNES Soundtracks to MP3

Do you like video game soundtracks from the Super Nintendo Entertainment System? Do all of your media devices use the MP3 format? Well then you are in luck!

You can download any SNES sound track and convert all of it's tracks to MP3 for free.

Step 1: Setup the Tools

Step 2: Go get some music

SNESMusic.org is a very nearly complete archive of all SNES soundtracks. Go there, find something you like, and download the RSN file. These RSN files are actually archives contains all of the individual tracks in SPC format.

Open the RSN file using WinRAR and extract the SPCs. If you have properly installed the foo_gep component, you should now be able to open and play these files in Foobar.

(Having a hard time deciding what to get? Check out VGMuseum's top SNES Soundtracks.)

Step 3: Convert to MP3

Create a playlist in Foobar of all the tracks that you wish to convert. Select them, right click, and select convert.

Set the output format to "MP3 Lame". Update your destination settings, I recommend specifying an output folder, and setting a multi-track file pattern of "%album%\%album% - %title%". There is no need to update the processing or other settings unless you wish to.

Click convert and the program will ask you to specify the file path of the LAME MP3 Encoder that you downloaded in step 1. Just put in the path and select lame.exe

Step 4: Rock out!

Foobar should now be converting your SPC files to MP3s. :)

Enjoy,
Tom

Monday, February 20, 2012

Browser Specific TestFixtures Sharing Tests

I will get to WebDrivers running in parallel next week, for now something even more fun: How to share Tests across browser specific TestFixtures with WebDriver.

When writing a unit test to test a webpage, you will want to duplicate that test against multiple browsers. How do we do accomplish this feat? Inheritance!

Step 1: SetUpFixture

First we need to create a SetUpFixture that will manage our WebDrivers. This will be largest and most complex class of our demonstration.

[SetUpFixture]
public class SetUpFixture
{
    private static IWebDriver _internetExplorerDriver;
    private static IWebDriver _chromeDriver;
 
    public static IWebDriver InternetExplorerDriver
    {
        get
        {
            if (_internetExplorerDriver == null)
            {
                DisposeDrivers();
                _internetExplorerDriver = new InternetExplorerDriver();
            }
            return _internetExplorerDriver;
        }
    }
 
    public static IWebDriver ChromeDriver
    {
        get
        {
            if (_chromeDriver == null)
            {
                DisposeDrivers();
                var dir = ConfigurationManager.AppSettings["chrome"];
                _chromeDriver = new ChromeDriver(dir);
            }
            return _chromeDriver;
        }
    }
 
    private static void DisposeDrivers()
    {
        if (_internetExplorerDriver != null)
        {
            _internetExplorerDriver.Close();
            _internetExplorerDriver.Dispose();
            _internetExplorerDriver = null;
        }
        if (_chromeDriver != null)
        {
            _chromeDriver.Close();
            _chromeDriver.Dispose();
            _chromeDriver= null;
        }
    }
 
    [TearDown]
    public void TearDown()
    {
        DisposeDrivers();
    }
}

Step 2: Base Class

Second we create an abstract base class that will go select our WebDriver from the SetUpFixture via an abstract property.

[TestFixture]
public abstract class TestFixtureBase
{
    public abstract IWebDriver WebDriver { get; }
 
    [SetUp]
    public void SetUp()
    {
        WebDriver.Url = "about:blank";
    }
}

Step 3: Tests

Write your tests in abstract classes that inherit from the base class.

public abstract class TestFixtureA : TestFixtureBase
{
    [Test]
    public void Test1()
    {
        WebDriver.Url = "http://www.phandroid.com/";
        Assert.IsTrue(WebDriver.Title.StartsWith("Android Phone"));
    }
 
    [Test]
    public void Test2()
    {
        WebDriver.Url = "http://www.reddit.com/";
        Assert.IsTrue(WebDriver.Title.StartsWith("reddit"));
    }
}

Step 4: Driver Specific TestFixtures

Create a test fixture for each permutation of browser and test class.

public class ChromeTestFixtureA : TestFixtureA
{
    public override IWebDriver WebDriver
    {
        get { return SetUpFixture.ChromeDriver; }
    }
}
 
public class InternetExplorerTestFixtureA : TestFixtureA
{
    public override IWebDriver WebDriver
    {
        get { return SetUpFixture.InternetExplorerDriver; }
    }
}

Step 5: Run!

Okay, next week I'll actually talk about running WebDrivers in parallel. :)

kick it on DotNetKicks.com

Enjoy,
Tom

Saturday, February 11, 2012

Sharing a WebDriver across TestFixtures

I absolutely love WebDriver.

WebDriver (also known as Selenium 2.0) is a web testing tool that is both useful and easy, which is a very rare find. If you are doing web development with ASP.NET, you need to take 30 minutes of your time and go try out WebDriver. That is all the time it will take to get you hooked.

WebDriver and NUnit

To launch a browser you need only new up a Driver object for that browser. I used to create a new Driver in my TestFixtureSetup, and then close and dispose of that in the testFixtureTearDown. However now that Firefox does not persist my windows login credentials it can be very frustrating to have to log back in for every test fixture.

A solution to this problem is simply to share a single WebDriver across multiple TestFixtures. Fortunately NUnit's SetUpFixture makes this very easy to do.

Step 1: Create a SetUpFixture

This class's SetUp method will be called once before any TestFixtures run, and then it's TearDown will be called once after all the TestFixtures have completed.

[SetUpFixture]
public class SetUpFixture
{
    public const string ProfileKey = "firefoxprofile";
 
    public static IWebDriver WebDriver { get; private set; }
 
    [SetUp]
    public void SetUp()
    {
        var profileDir = ConfigurationManager.AppSettings[ProfileKey];
        if (String.IsNullOrWhiteSpace(profileDir))
        {
            WebDriver = new FirefoxDriver();
        }
        else
        {
            var profile = new FirefoxProfile(profileDir);
            WebDriver = new FirefoxDriver(profile);
        }
    }
 
    [TearDown]
    public void TearDown()
    {
        if (WebDriver == null)
            return;
 
        WebDriver.Close();
        WebDriver.Dispose();
    }
}

Step 2: Create an abstract base class

This abstract class will use the TestFixtureSetUp to copy the static WebDriver that was initialized by the SetUpFixture. I also like to have a SetUp that will clear the browser, just to make sure you are navigation to a new page from a blank one.

public abstract class TestFixtureBase
{
    public IWebDriver WebDriver { get; private set; }
 
    [TestFixtureSetUp]
    public void TestFixtureSetUp()
    {
        WebDriver = SetUpFixture.WebDriver;
    }
 
    [SetUp]
    public void SetUp()
    {
        WebDriver.Url = "about:blank";
    }
}

Step 3: Make your TestFixtures inherit the base class

These TestFixtures will now share the static WebDriver.

[TestFixture]
public class TestFixtureA : TestFixtureBase
{
    [Test]
    public void Test1()
    {
        WebDriver.Url = "http://www.phandroid.com/";
        Assert.IsTrue(WebDriver.Title.StartsWith("Android Phone"));
    }
}
 
[TestFixture]
public class TestFixtureB : TestFixtureBase
{
    [Test]
    public void Test1()
    {
        WebDriver.Url = "http://www.reddit.com/";
        Assert.IsTrue(WebDriver.Title.StartsWith("reddit"));
    }
}

Step 4: Run those tests!

If you love .NET 4.0 then stay tuned, because in my next post I'll explore running WebDrivers in PARALLEL! See you next week. :)

kick it on DotNetKicks.com

Enjoy,
Tom

Saturday, January 7, 2012

.NET Collection Runtimes

Each week my department holds a morning tech review. Subjects vary from testing tools, advanced caching mechanisms, to good ol' basic .NET facts. This week the tech review was an "Asymptomatic Analysis of .NET Collections". While most of the material was pretty straight forward, I always find getting back to the basics to be a good thing.

I thought that it was fun to see all of the collection run times aggregated into one table. As several of my coworkers pointed out, it can be a bit of a pain to find all these "simple" facts on the SEO crammed internet...so then why does no one simply blog about it?

In summary: here is some stolen content. Thanks Byron!

List-Like Collections

  List LinkedList SortedList
Add O(1) or O(N) O(1) O(Log N) or O(N)
Remove O(N) O(N) O(N)
Clear O(N) O(1) O(Log N)
Get O(1) O(N) O(Log N)
Find O(N) O(N) O(Log N)
Sort O(N log N) or O(N^2) - Already sorted
Underlying
Data
Structure
Array Dynamically allocated nodes Array

Hash-Like Collections

  Dictionary SortedDictionary HashSet SortedSet
Add O(1)
or O(N)
O(Log N) O(1)
or O(N)
O(log N)
Remove O(1) O(log N) O(1) O(N)
Clear O(N) O(Log N) O(N) O(N)
Get / Find O(1) O(Log N) O(1) O(Log N)
Sort - Already sorted - -
Underlying
Data
Structure
Array + Linked List Dynamically allocated nodes
(Binary Search Tree)
Array + Linked List Dynamically allocated nodes
(Binary Search Tree)

If you would like to see any updates/additions please feel free to leave a comment.

Enjoy,
Tom

Tuesday, January 3, 2012

Why Atwood's Law is a Good Thing

Any application that can be written in JavaScript, will eventually be written in JavaScript.

Jeff Atwood proposed this simple rule way back in 2007. Now, as his predictions come true, we may find ourselves asking "why would anyone want to do such a crazy thing?" Well here are three simple reasons:

1: Because we can!
Software development is an art that requires practice. Why do college students write compilers? Why did John Carmack port Rage to iOS? Why did I port Chrono Trigger to a graphing calculator? Software engineers are artisans, these challenges represent our art form at it's best.

2: JavaScript represents true platform independence.
Windows, Mac, Linux, x86, x64, iOS, Android, the list goes on; frankly, there are just too many platforms out there to develop for. The beauty of JavaScript is that it is a universally recognized spec that is supported everywhere. This level of accessibility is advantageous for developers and consumers alike.

3: It shows the power of modern technology.
The fact that we can run a Java Virtual Machine in the browser shows just how far modern browsers and house hold hardware have come. It was only a few years ago that Virtual Machines were a concept reserved for only the most powerful of server farms. The tower of Dubia was not built out of necessity, it instead stands as a monument to human achievement; that is how I view emulator hardware in a browser, a virtual monument of human engineering.

...also, why wouldn't you want to play NES games in your browser?

Tom

Real Time Web Analytics