Statement Completion for Dynamic languages in Sublime Text

Oct 5, 2012

This post describes how to configure Sublime Text in order to get statement completion for JavaScript, Python, (and perhaps PHP, RHTML, Smarty, Mason, Node.js, XBL, Tcl, HTML, HTML5, TemplateToolkit, XUL, Django, Perl, and Ruby).

After following the steps, statement completion will also work for Python projects installed in a virtualenv.

  • Download Sublime Text from here.
  • Install on Windows or OS X (it doesn’t really matter).

Install Package Manager

  • Run Sublime Text
  • Open the Sublime Text Console. This is accessed via the ctrl + ` shortcut.
  • Paste the command found here into the console.
  • Restart Sublime Text

We have just installed Sublime Package Control - A full-featured package manager that helps discovering, installing, updating and removing packages for Sublime Text 2. It features an automatic updater and supports GitHub, BitBucket and a full channel/repository system.

Configure Statement Completion

  • Press ctrl + shift + p (Windows, Linux) or cmd + shift + p (OS X).
  • Type Install Package and select it.

The Install Package command shows a list of all available packages that are available for install. This will include all of the packages from the [default channel](http://wbond.net/sublime_packages/community), plus any from repositories you have added.

  • Select SublimeCodeIntel from the list of packages.

Configure Statement Completion for Python projects in virtualenv

You may skip this if you are not using virtualenv.

  • Create a .codeintel directory at the root of the project
  • Create a config file (without any extension) inside the newly created directory.
{
    "Python": {
        "python": '~/Documents/Projects/VirtualEnvName/bin/python',
        "pythonExtraPaths": ['~/Documents/Projects/VirtualEnvName/lib/python/site-packages',
        ]
    },
}

Note that VirtualEnvName is the name of the virtualenv were the files of the project are located.

The project itself is in ~/Documents/Projects/VirtualEnvName/ProjectName

Statement Completion in action

A screenshot for jQuery (note also the very cool theme)

A screenshot for jQuery

Also,

A screenshot for Document Object Model

A screenshot for Python

References:

AutoFixture, xUnit.net, and Auto Mocking

Jul 31, 2012

Update: In AutoFixture 3 numbers are random.

The features discussed in this post are available when using AutoFixture decleratively with the xUnit.net extension. In addition, it is required to have at least one of the extensions for Auto Mocking using AutoMoq, AutoRhinoMocks, AutoFakeItEasy, AutoNSubstitute, or AutoFoq.

To install AutoFixture with xUnit.net data theories, run the following command in the Package Manager Console:

PM> Install-Package AutoFixture.Xunit

In the test method below we would like to use xUnit.net data theories to provide:

  1. Auto-generated data specimens for d, s, i, a.
  2. Auto-generated data specimens for _, s, i, a, and inline values for d.
  3. Auto-generated data specimens for _, _, i, a, and inline values for d, s.
public void TestMethod(
    double d, string s, IInterface i, AbstractType a)
{
    Assert.True(
        d != 0    &&
        s != null &&
        i != null &&
        a != null
        );
}

That fact that argument i is an interface and argument a is an abstract class prevents us from using [InlineData], [AutoData], or [InlineAutoData] attributes.

AutoFixture allows us to easily define custom DataAttribute derived types:

  • By deriving from AutoDataAttribute and passing to the base constructor a customization that enables auto mocking with Moq, Rhino Mocks, FakeItEasy, or NSubstitute.
  • By deriving from CompositeDataAttribute and passing to the base constructor an array of DataAttribute derived type instances, e.g. an instance of InlineDataAttribute and an instance of AutoDataAttribute derived type.

Auto Mocking using Moq

To install AutoFixture with Auto Mocking using Moq, run the following command in the Package Manager Console:

PM> Install-Package AutoFixture.AutoMoq

We decorate the test method with AutoMoqData and InlineAutoMoqData attributes:

[Theory]
[AutoMoqData]
[InlineAutoMoqData(2)]
[InlineAutoMoqData(3, "foo")]
public void WithMoq(
    double d, string s, IInterface i, AbstractType a)
{
    Write(d, s, i, a);
}

Output

AutoMoqData:
  d = 1
  s = s05080d05-b874-4182-bba5-18678ad9b134
  i = Castle.Proxies.IInterfaceProxy
  a = Castle.Proxies.AbstractTypeProxy
  
InlineAutoMoqData:
  d = 2
  s = sce87888d-8cc8-4f69-927c-c4b1347d3147
  i = Castle.Proxies.IInterfaceProxy
  a = Castle.Proxies.AbstractTypeProxy

InlineAutoMoqData:
  d = 3
  s = foo
  i = Castle.Proxies.IInterfaceProxy
  a = Castle.Proxies.AbstractTypeProxy

Source code

internal class AutoMoqDataAttribute : AutoDataAttribute
{
    internal AutoMoqDataAttribute()
        : base(new Fixture().Customize(new AutoMoqCustomization()))
    {
    }
}

internal class InlineAutoMoqDataAttribute : CompositeDataAttribute
{
    internal InlineAutoMoqDataAttribute(params object[] values)
        : base(new DataAttribute[] { 
            new InlineDataAttribute(values), new AutoMoqDataAttribute() })
    {
    }
}

More information on AutoFixture with Auto Mocking using Moq can be found at AutoFixture as an auto-mocking container blog post.

Auto Mocking using Rhino Mocks

To install AutoFixture with Auto Mocking using Rhino Mocks, run the following command in the Package Manager Console:

PM> Install-Package AutoFixture.AutoRhinoMocks

We decorate the test method with AutoRhinoMockData and InlineAutoRhinoMockData attributes:

[Theory]
[AutoRhinoMockData]
[InlineAutoRhinoMockData(2)]
[InlineAutoRhinoMockData(3, "foo")]
public void WithRhinoMocks(
    double d, string s, IInterface i, AbstractType a)
{
    Write(d, s, i, a);
}

Ouput

AutoRhinoMockData:
  d = 1
  s = s01172643-5162-474f-bcfa-319ef40a8272
  i = Castle.Proxies.IInterfaceProxy201f58a5559841bfb41895881489658c
  a = Castle.Proxies.AbstractTypeProxy5a86172bbda14cc098b4c675c5b7e555

InlineAutoRhinoMockData:
  d = 2
  s = sd3b9c112-5181-4daa-9b2f-333c7498044a
  i = Castle.Proxies.IInterfaceProxy201f58a5559841bfb41895881489658c
  a = Castle.Proxies.AbstractTypeProxy5a86172bbda14cc098b4c675c5b7e555
  
InlineAutoRhinoMockData:
  d = 3
  s = foo
  i = Castle.Proxies.IInterfaceProxy201f58a5559841bfb41895881489658c
  a = Castle.Proxies.AbstractTypeProxy5a86172bbda14cc098b4c675c5b7e555

Source code

internal class AutoRhinoMockDataAttribute : AutoDataAttribute
{
    internal AutoRhinoMockDataAttribute()
        : base(new Fixture().Customize(new AutoRhinoMockCustomization()))
    {
    }
}

internal class InlineAutoRhinoMockDataAttribute : CompositeDataAttribute
{
    internal InlineAutoRhinoMockDataAttribute(params object[] values)
        : base(new DataAttribute[] { 
            new InlineDataAttribute(values), new AutoRhinoMockDataAttribute() })
    {
    }
}

More information on AutoFixture with Auto Mocking using Rhino Mocks can be found at Rhino Mocks-based auto-mocking with AutoFixture blog post.

Auto Mocking using FakeItEasy

To install AutoFixture with Auto Mocking using FakeItEasy, run the following command in the Package Manager Console:

PM> Install-Package AutoFixture.AutoFakeItEasy

We decorate the test method with AutoFakeItEasyData or InlineAutoFakeItEasyData attributes:

[Theory]
[AutoFakeItEasyData]
[InlineAutoFakeItEasyData(2)]
[InlineAutoFakeItEasyData(3, "foo")]
public void WithFakeItEasy(
    double d, string s, IInterface i, AbstractType a)
{
    Write(d, s, i, a);
}

Output

AutoFakeItEasyData:
  d = 1
  s = s2b4c118b-d18b-4782-992a-d4138c65fd2a
  i = Faked IInterface
  a = Faked AbstractType

InlineAutoFakeItEasyData:
  d = 2
  s = se8da7e09-ea4f-4d16-86bd-4229802e5f5d
  i = Faked IInterface
  a = Faked AbstractType

InlineAutoFakeItEasyData:
  d = 3
  s = foo
  i = Faked IInterface
  a = Faked AbstractType

Source code

internal class AutoFakeItEasyDataAttribute : AutoDataAttribute
{
    internal AutoFakeItEasyDataAttribute()
        : base(new Fixture().Customize(new AutoFakeItEasyCustomization()))
    {
    }
}

internal class InlineAutoFakeItEasyDataAttribute : CompositeDataAttribute
{
    internal InlineAutoFakeItEasyDataAttribute(params object[] values)
        : base(new DataAttribute[] { 
            new InlineDataAttribute(values), new AutoFakeItEasyDataAttribute() })
    {
    }
}

More information on AutoFixture with Auto Mocking using FakeItEasy can be found at Auto-Mocking with FakeItEasy and AutoFixture blog post.

Auto Mocking using NSubstitute

To install AutoFixture with Auto Mocking using NSubstitute, run the following command in the Package Manager Console:

PM> Install-Package AutoFixture.AutoNSubstitute

We decorate the test method with AutoNSubstituteData or InlineAutoNSubstituteData attributes:

[Theory]
[AutoNSubstituteData]
[InlineAutoNSubstituteData(2)]
[InlineAutoNSubstituteData(3, "foo")]
public void WithNSubstitute(
    double d, string s, IInterface i, AbstractType a)
{
    Write(d, s, i, a);
}

Output

AutoNSubstituteData:
  d = 1
  s = sf7ce77e0-c2b3-4749-b9ec-78f3aba0254a
  i = Castle.Proxies.IInterfaceProxy
  a = Castle.Proxies.AbstractTypeProxy
  
InlineAutoNSubstituteData:
  d = 2
  s = sf7ba31be-3136-4b50-a51f-3763f1d06004
  i = Castle.Proxies.IInterfaceProxy
  a = Castle.Proxies.AbstractTypeProxy

InlineAutoNSubstituteData:
  d = 3
  s = foo
  i = Castle.Proxies.IInterfaceProxy
  a = Castle.Proxies.AbstractTypeProxy

Source code

internal class AutoNSubstituteDataAttribute : AutoDataAttribute
{
    internal AutoNSubstituteDataAttribute()
        : base(new Fixture().Customize(new AutoNSubstituteCustomization()))
    {
    }
}

internal class InlineAutoNSubstituteDataAttribute : CompositeDataAttribute
{
    internal InlineAutoNSubstituteDataAttribute(params object[] values)
        : base(new DataAttribute[] { 
            new InlineDataAttribute(values), new AutoNSubstituteDataAttribute() })
    {
    }
}

More information on AutoFixture with Auto Mocking using NSubstitute can be found at NSubstitute Auto-mocking with AutoFixture blog post.

Composite xUnit.net Data Attributes

Jul 27, 2012

xUnit.net extensions support data-driven tests called Theories. Such tests are similar to regular xUnit.net tests but instead of being decorated with [Fact] they are decorated with [Theory].

Below is a data-driven test with the data coming a Microsoft Excel (.xls) spreadsheet.

[Theory]
[ExcelData("UnitTestData.xls", "SELECT x, y FROM Data")]
public void Foo(object x, object y)
{
	// 'x' and 'y' are values from the .xls spreadsheet.
}

Also, a data-driven test with the data coming from a type implementing the IEnumerable<object[]>.

[Theory]
[ClassData(typeof(CollectionOfSpecifiedString))]
public void Bar(object x, object y)
{
	// 'x' and 'y' are values from the IEnumerable<object[]> type.
}

internal class CollectionOfSpecifiedString : IEnumerable<object[]>
{
    public IEnumerator<object[]> GetEnumerator()
    {
        yield return new object[]
        {
            "foo", "zoo"
        };
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

In the above samples, [ExcelData] and [ClassData] are attributes representing a data source for a data-driven test.

Using data from multiple attributes

Below is a data-driven test with the data coming from a type implementing the IEnumerable<object[]> combined with the data coming from an .xls spreadsheet.

[Theory]
[ClassExcelData(
    typeof(CollectionOfSpecifiedString),
    "UnitTestData.xls", "SELECT x, y FROM Data")]
public void Zoo(object x, object y)
{
	// 'x' is coming from the IEnumerable<object[]> type.
	// 'y' is coming from the .xls spreadsheet.
}

internal class CollectionOfSpecifiedString : IEnumerable<object[]>
{
    public IEnumerator<object[]> GetEnumerator()
    {
        yield return new object[]
        {
            "foo"
        };
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

Creating a composite attribute

The [ClassExcelData] from the previous example is a composite of two xUnit.net’s data attributes [ClassData] and [ExcelData].

All we have to do is create a type deriving from CompositeDataAttribute, passing in its base constructor an array of the data attributes we would like to compose.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
internal class ClassExcelDataAttribute : CompositeDataAttribute
{
    internal ClassExcelDataAttribute(Type type, string filename, string selectStatement)
        : base(new DataAttribute[] { 
                new ClassDataAttribute(type), 
                new ExcelDataAttribute(filename, selectStatement) })
    {
    }
}

The description for the CompositeDataAttribute algorithm can be found here.

When defining a composite data attribute, it is acceptable for the first attribute to provide some (or all) data for the parameters of the test method. However, subsequent data attributes must be able to provide the data for the exact position where the previous attribute stopped.

Obtaining the CompositeDataAttribute class

CompositeDataAttribute is currently bundled with AutoFixture extension for xUnit.net. You can use it by installing the AutoFixture.Xunit NuGet package.

Using the Web API Dependency Resolver with Castle Windsor's Scoped Lifetime

Jul 16, 2012

Update: Mark Seemann has provided a solution without using the IDependencyResolver interface.

This post is the result of a very good suggestion) in the comments section of the previous post.

The WindsorDependencyScope from the previous post has been modified to use the Scoped lifetime available in Castle Windsor 3.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
using Castle.MicroKernel.Lifestyle;
using Castle.Windsor;

internal sealed class WindsorDependencyScope : IDependencyScope
{
    private readonly IWindsorContainer container;
    private readonly IDisposable scope;

    public WindsorDependencyScope(IWindsorContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }

        this.container = container;
        this.scope = container.BeginScope();
    }

    public object GetService(Type t)
    {
        return this.container.Kernel.HasComponent(t) ? this.container.Resolve(t) : null;
    }

    public IEnumerable<object> GetServices(Type t)
    {
        return this.container.ResolveAll(t).Cast<object>().ToArray();
    }

    public void Dispose()
    {
        this.scope.Dispose();
    }
}

The BeginScope is an extension method for the IWindsorContainer type. It returns by default an instance of a CallContextLifetimeScope type. It uses the Call Context so it can be associated with thread pool threads and manually created threads within a single AppDomain (it does not use the Logical Call Context).

On each request the Web API calls the GetDependencyScope extension method of the HttpRequestMessage type, which, in return, calls it’s own BeginScope method to start a new resolution scope. Using our own implementation of the IDependencyResolver interface we always return a new instance of the WindsorDependencyScope type.

internal sealed class WindsorDependencyResolver : IDependencyResolver
{    
    // 'using' Directives and other type members removed for brevity.
    
    public IDependencyScope BeginScope()
    {
        return new WindsorDependencyScope(this.container);
    }
}

Since we use the Scoped lifetime we need to define it also in the registration code. Then, we will always have at most one instance of each requested type per resolution scope (that is, a request).

internal sealed class WebWindsorInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes
            .FromAssemblyContaining<ValuesController>()
            .BasedOn<IHttpController>()
            .LifestyleScoped());
    }
}

The source code can be found here.

Using the Web API Dependency Resolver with Castle Windsor (Part 2)

Jun 4, 2012

Update: Mark Seemann has provided a solution without using the IDependencyResolver interface.

The code in this post requires the ASP.NET MVC 4 RC. If you use the Beta version use the code from this post.

Among the many changes in ASP.NET MVC 4 RC, there is now added support for releasing object graphs, resolved on each request, using dependency scopes.

Creating a dependency scope per request

Since the IHttpControllerFactory interface has been removed, the recommendation (from the release notes) is to use the IHttpControllerSelector interface to control IHttpController selection and the IHttpControllerActivator interface to control IHttpController activation.

Below is the IHttpControllerSelector interface:

public interface IHttpControllerSelector
{
    HttpControllerDescriptor SelectController(HttpRequestMessage request);
}

// Other methods removed for brevity.

And the IHttpControllerActivator interface:

public interface IHttpControllerActivator
{
    IHttpController Create(
        HttpRequestMessage request, 
        HttpControllerDescriptor controllerDescriptor, 
        Type controllerType);
}

Both interfaces contain method(s) accepting, among others, an HttpRequestMessage. The trick here is to use the HttpRequestMessage’s extension method GetDependencyScope for resolving controllers (instead of using a DI Container directly).

Internally, the GetDependencyScope method uses the DependencyResolver (registered in the GlobalConfiguration instance) calling it’s BeginScope method which creates a new resolution scope. Objects that are resolved in that scope are tracked internally. Once the scope is disposed, those objects are released (using the container’s Release method).

Below is an implementation of the IDependencyScope interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;

internal class ReleasingDependencyScope : IDependencyScope
{
    private readonly IDependencyScope scope;
    private readonly Action<object> release;
    private readonly List<object> instances;

    public WindsorDependencyScope(IDependencyScope scope, Action<object> release)
    {
        if (scope == null)
        {
            throw new ArgumentNullException("scope");
        }

        if (release == null)
        {
            throw new ArgumentNullException("release");
        }

        this.scope = scope;
        this.release = release;
        this.instances = new List<object>();
    }

    public object GetService(Type t)
    {
        object service = this.scope.GetService(t);
        this.AddToScope(service);

        return service;
    }

    public IEnumerable<object> GetServices(Type t)
    {
        var services = this.scope.GetServices(t);
        this.AddToScope(services);

        return services;
    }

    public void Dispose()
    {
        foreach (object instance in this.instances)
        {
            this.release(instance);
        }
            
        this.instances.Clear();
    }

    private void AddToScope(params object[] services)
    {
        if (services.Any())
        {
            this.instances.AddRange(services);
        }
    }
}

Having a custom implementation of the IDependencyScope interface, we can now move on with the implementation of the IDependencyResolver interface. The recommendation (from the source code) is to return a new instance of IDependencyScope every time the BeginScope method is called.

An implementation of the IDependencyResolver interface for Castle Windsor could be similar to the one below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
using Castle.Windsor;

internal class WindsorDependencyResolver : IDependencyResolver
{
    private readonly IWindsorContainer container;

    public WindsorDependencyResolver(IWindsorContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }

        this.container = container;
    }

    public object GetService(Type t)
    {
        return this.container.Kernel.HasComponent(t) ? this.container.Resolve(t) : null;
    }

    public IEnumerable<object> GetServices(Type t)
    {
        return this.container.ResolveAll(t).Cast<object>().ToArray();
    }

    public IDependencyScope BeginScope()
    {
        return new ReleasingDependencyScope(this, this.container.Release);
    }

    public void Dispose()
    {
    }
}

As we can see, the BeginScope method returns a new instance of IDependencyScope which can resolve and release objects that belong to that scope.

Moving next, when upgrading from Beta to RC there might be another thing to consider. Since the IHttpControllerFactory interface has now been removed, implementations of that interface were using the controllerName in order to resolve component instances from the DI Containers. As a result, controllers were registered in the DI Containers using names for each registration.

To keep the named registrations (and not break compatibility with any JavaScript clients) we can create a DefaultHttpControllerSelector derived type and override it’s SelectController method. We can then use the DefaultHttpControllerSelector’s GetControllerName method which returns the requested path name (e.g. “Orders”). At that point we can map that name to an ApiController derived type (ex.: OrderController).

A DefaultHttpControllerSelector derived type could be similar to the one below:

using System;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;

internal class PluralizedNameHttpControllerSelector : DefaultHttpControllerSelector
{
    private readonly HttpConfiguration configuration;
    private readonly Assembly controllerAssembly;

    public PluralizedNameHttpControllerSelector(
        HttpConfiguration configuration, Assembly controllerAssembly)
        : base(configuration)
    {
        if (configuration == null)
        {
            throw new ArgumentNullException("configuration");
        }
            
        if (controllerAssembly == null)
        {
            throw new ArgumentNullException("controllerAssembly");
        }

        this.configuration = configuration;
        this.controllerAssembly = controllerAssembly;
    }

    public override HttpControllerDescriptor SelectController(
        HttpRequestMessage request)
    {
        var controllerName = base.GetControllerName(request);
        var controllerType = this.GetControllerType(controllerName);

        return new HttpControllerDescriptor(
            this.configuration, controllerName, controllerType);
    }

    private Type GetControllerType(string name)
    {
        // Look in 'this.controllerAssembly' and find the types that can be
        // assigned from an instance of IHttpController  and return the one
        // whose name matches with the given name.
    }
}

Make sure to register the above type in Castle Windsor otherwise the framework will pick it's default implementation.

All the above information is the result of browsing the source code on CodePlex. If any articles or blog posts are released (by the ASP.NET team or individuals) I might create a new post with updates, if necessary.

subscribe via RSS