Tuesday, December 1, 2015

Singleton Azure WebJob

I have an Azure website project I have been working on.  This project required a scheduled task to run so I decided to give Azure WebJobs a try.  Creation of the job and getting it to deploy was pretty straight forward.  One of the things that is nice is for each instance your website uses the WebJob is duplicated.  For some WebJobs this can be be a really nice feature. 

The WebJob I am using does some data import and manipulation.  Having multiple instances of this WebJob running is not what I wanted.  After some searching I found that you can make your WebJob run on a single instance no matter how many instances your website is using.

To do this you will need to do the following.

  1. Add a “settings.job” file to the root of your WebJob project
  2. Modify the properties of the file and set the:
    • Build Action = Content
    • Copy to Output Directory = Copy always
  3. The contents of the “settings.job” file should contain the following json:
    { "is_singleton": true }

This should be all that is needed to get your WebJob running as a single instance when installed on many instances.

Saturday, May 16, 2015

Setting up Web API 2 with Windsor using OWIN hosted in IIS


tldr; Get the code from my Github repository here: https://github.com/devdaves/ExampleWebApi

Start a new ASP.NET Web Application

image

Select the Empty template.  Don't check any of the core references (Web Forms, MVC or Web API).

image

Once the project is ready to go, open the package manager console and run the following commands to install the necessary nuget packages.

  • install-package Microsoft.AspNet.WebApi.Owin
  • install-package Microsoft.Owin.Host.SystemWeb
  • install-package Castle.Windsor

Open the web.config and add the following code:

<appSettings>
  <add key="owin:AutomaticAppStartup" value="true" />
</appSettings>

In the Solution Explorer create a Startup class at the root of the site with the following code:

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        HttpConfiguration config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();
        appBuilder.UseWebApi(config);
    }
}

In the Solution Explorer create a Models folder and inside the Models folder create a Contact class with the following code:

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

In the Solution Explorer create a Controllers folder and inside the Controllers folder create a Web API controller called ContactsController with the following code:

public class ContactsController : ApiController
{
    [HttpGet]
    [Route("contacts")]
    public IHttpActionResult Get()
    {
        return Ok(new Contact(){FirstName = "Donald", LastName = "Duck"});
    }
}

At this point you have enough to run the application and should be able to go to http://localhost:####/contacts in your browser and see the contact returned.

Now its time to add Windsor.  In the Solution Explorer add a new folder called Windsor.  Create a new class called WindsorDependencyScope with the following code:

internal class WindsorDependencyScope : IDependencyScope
{
    private readonly IWindsorContainer _container;
    private readonly IDisposable _scope;

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

        _container = container;
        _scope = container.BeginScope();
    }

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

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

    public void Dispose()
    {
        _scope.Dispose();
    }
}

Add a new class to the Windsor folder called WindsorHttpDependencyResolver with the following code:

internal sealed class WindsorHttpDependencyResolver : IDependencyResolver
{
    private readonly IWindsorContainer _container;

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

        _container = container;
    }

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

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

    public IDependencyScope BeginScope()
    {
        return new WindsorDependencyScope(_container);
    }

    public void Dispose()
    {
    }
}

In the Windsor folder create a new folder called Installers.  Create a new class in the Installers folder called ControllerInstaller with the following code:

public class ControllerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
        .Pick().If(t => t.Name.EndsWith("Controller"))
        .Configure(configurer => configurer.Named(configurer.Implementation.Name))
        .LifestylePerWebRequest());
    }
}

Create another new class in the Windsor/Installers folder called DefaultInstaller with the following code:

public class DefaultInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
            .Pick()
            .WithServiceDefaultInterfaces()
            .Configure(c => c.LifestyleTransient()));
    }
}

Now we need to make the final changes to the Startup class we created in the root of the site.  Make it look like this:

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var container = new WindsorContainer().Install(
            new ControllerInstaller(),
            new DefaultInstaller());
        var httpDependencyResolver = new WindsorHttpDependencyResolver(container);

        HttpConfiguration config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();
        config.DependencyResolver = httpDependencyResolver;
        appBuilder.UseWebApi(config);
    }
}

Now that Windsor is setup lets add a contact repository and add that as a dependency to the controller so we can see Windsor in action.

In the Solution Explorer add a folder called Repository.  In the Repository folder add a new interface called IContactsRepository with the following code:

public interface IContactsRepository
{
    Contact GetContact();
}

Add a class called ContactsRepository to the Repository folder with the following code:

public class ContactsRepository : IContactsRepository
{
    public Contact GetContact()
    {
        return new Contact(){FirstName = "Donald", LastName = "Duck"};
    }
}

Now lets go add the dependency to the ContactsController, make the ContactsController code look like this:

public class ContactsController : ApiController
{
    private IContactsRepository repository;

    public ContactsController(IContactsRepository repository)
    {
        this.repository = repository;
    }

    [HttpGet]
    [Route("contacts")]
    public IHttpActionResult Get()
    {
        return Ok(this.repository.GetContact());
    }
}

That should be it.  Running the site now everything should work.

Monday, May 5, 2014

Pimp your Bash console on Windows

Since I have been doing so much Git work I wanted to post some things I do to pimp my Bash console out.

First thing is we need to get to our home directory.  Do this by typing this in your bash console:

cd

This should change your prompt to point to ~.  The next thing is we need to see if there is already a .bashrc file.  The easiest way I have found to do this is to type the following in the bash console:

explorer .

This should open a windows explorer window in your home directory.  Check to see if a .bashrc file exists.  If this file does not exist type the following in the bash console window:

touch .bashrc

Go back to windows explorer and you should now see the .bsahrc file.  Open the file in your favorite text editor.  Here is an example of what I have been putting in my .basrc file:

alias brc="source ~/.bashrc"
alias cls=clear
alias ..='cd ..'
alias cd..='cd ..'
alias dir='ls --color -X'
alias e='explorer .'

h()
{
    cd ~/skydrive/dev;
}

cl() {
    d=$1
    if [[ -z "$d" ]]; then
        d=$HOME
    fi
    if [[ -d "$d" ]]; then
        cd "$d"
        dir
    else
        echo "bash: cl: '$d': Directory not found"
    fi
}



brc an easy way to reload the bashrc file while in the bash console.  This way you don’t have to restart the console each time you make a change.
cls I am used to typing this in DOS
.. a shortcut to go back a directory
cd.. bash wants a space between the cd and the .. this alias lets me forget the space and it doesn’t complain about it.
dir I am used to typing this in DOS
e shortcut to open explorer in the current directory
h shortcut to my start directory where all my code is
cl change directory and list its contents

Saturday, March 29, 2014

Git Config Commands

I have been doing a bunch of work with Git lately.  I wanted to do a post about some commands I don’t want to forget.

Who are you?
git config --global user.name '<name goes here>'
git config --global user.email '<email address here>’

Turn off https verification
We are using Stash and its using a self signed certificate.  This command allows us to access the Stash repositories over HTTPS.

git config --global http.sslVerify false

Make notepadd++ your editor (no more vim)
I am not a VIM kinda guy so this was a huge help when using things like rebase.

git config --global core.editor '"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession –noPlugin'

Set Visual Studio 2013 as your diff tool
git config --global difftool.prompt true
git config --global difftool.vs2013.cmd '"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\vsdiffmerge.exe" "$LOCAL" "$REMOTE" //t'
git config --global difftool.vs2013.keepbackup false
git config --global difftool.vs2013.trustexistcode true
git config --global diff.tool vs2013

Set Visual Studio 2013 as your merge tool
git config --global mergetool.prompt true
git config --global mergetool.vs2013.cmd '"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\vsdiffmerge.exe" "$REMOTE" "$LOCAL" "$BASE" "$MERGED" //m'
git config --global mergetool.vs2013.keepbackup false
git config --global mergetool.vs2013.trustexistcode true
git config --global merge.tool vs2013

Log Alias
This alias I find really useful. I got this from one of my co-workers.  Here is a link to where it came form (source).

git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

Saturday, February 22, 2014

Unit Testing Async Methods with Moq

The other day I was pairing with a colleague.  We where working on unit testing some classes that where using the new async and await features.  We ran into some issue trying to get mocking working for our classes dependencies. Here is some example code on how we got things to work.

So given the following code:

public interface IClass2
{
    Task<string> GetSomeString_MethodAsync();
}

public class Class2 : IClass2
{
    public async Task<string> GetSomeString_MethodAsync()
    {
        await Task.Run(() => Thread.Sleep(2000));
        return "hello world.";
    }
}

public class Class1
{
    private IClass2 class2;

    public Class1(IClass2 class2)
    {
        this.class2 = class2;
    }

    public async Task<string> SomeMethod()
    {
        return await this.class2.GetSomeString_MethodAsync();
    }
}

And we can test it like this:

private Mock<IClass2> class2Mock;
private Class1 class1;

[TestInitialize]
public void Setup()
{
    this.class2Mock = new Mock<IClass2>();
    this.class1 = new Class1(this.class2Mock.Object);
}
            
[TestMethod]
public async Task SomeMethodTest()
{
    var expectedString = "Hello World";
    var tcs = new TaskCompletionSource<string>();
    tcs.SetResult(expectedString);
    this.class2Mock.Setup(x => x.GetSomeString_MethodAsync()).Returns(tcs.Task);

    var result = await this.class1.SomeMethod();

    Assert.AreEqual(result, expectedString);
}

Note the usage of the TaskCompletionSource in the unit test along with the declaration of the test using “async Task”.

Monday, April 29, 2013

Getting Started with Castle Windsor Interceptors in ASP.NET MVC

Don’t you hate when writing code you have to think about generic exception handling, logging of method calls, caching of methods, authorization, etc...  Well suppose there was a tool/technique you could use that you could write the above items once and make sure they get implemented on existing code along with any new code added in the future.  Castle Windsor and its Interceptors support just that.

In the example below we will create a interceptor and do the necessary wiring up to make it work.  We will be using an ASP.NET MVC4 application based on the initial Windsor setup done in my last blog post.
http://blog.devdave.com/2013/04/castle-windsor-in-aspnet-mvc-4.html

Create a manager class to do some work.  We will call methods of this class in our controller class. later in this blog post  In the Infrastructure folder create a new folder called Managers.  Inside the Managers folder create a new folder called Interfaces.  Create an interface called IExampleManager in the interface folder.

public interface IExampleManager
{
    void ExampleMethod();
}

Creating the concrete implementation of the manager, create a class called ExampleManager in the Managers folder.

public class ExampleManager : IExampleManager
{
    public void ExampleMethod()
    {
        Debug.WriteLine("Doing Work...");
    }
}

Now we need to register our new manager in Windsor.  In the Infrastructure\Installers folder add a new class called ManagerInstaller.

public class ManagerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
            .Where(type => type.Name.EndsWith("Manager"))
            .WithServiceDefaultInterfaces()
            .Configure(c => c.LifestyleTransient()));
    }
}

Now that Windsor knows how to handle the manager we can modify our controllers constructor like so

private IExampleManager exampleManager;

public HomeController(IExampleManager exampleManager)
{
    this.exampleManager = exampleManager;
}

Since Windsor knows how to turn an IExampleManager into ExampleManager it will handle this for us when Windsor instantiates the controller.

Modify the controller action method to call a method on the example manager.

public ActionResult Index()
{
    this.exampleManager.ExampleMethod();
    return new ContentResult(){Content = "test"};
}

Running the site and calling the Index action, note the output window.
image

Now lets say we wanted to intercept the call to any public method of the ExampleManager class.  We can do this by adding in an interceptor. To do this we will need to create the interceptor.  Create a new folder inside the infrastructure folder called Interceptors.  Create a new class in this folder called ExampleInterceptor.

public class ExampleInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Debug.WriteLine(string.Format("Before method: {0}", invocation.Method.Name));
        invocation.Proceed();
        Debug.WriteLine(string.Format("After method: {0}", invocation.Method.Name));
    }
}

Now we need to tell Windsor about the interceptor.  In the Infrastructure\Installers folder lets add a new class called InterceptorInstaller.

public class InterceptorInstaller : IWindsorInstaller
{
    public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
    {
        container.Register(Component.For<ExampleInterceptor>()
                               .LifestyleTransient());
    }
}

Now lets go back to our manager installer and add in the interceptor to all managers.

public class ManagerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
            .Where(type => type.Name.EndsWith("Manager"))
            .WithServiceDefaultInterfaces()
            .Configure(c => c.LifestyleTransient().Interceptors<ExampleInterceptor>()));
    }
}

Running the site and calling the Index action, note the output window now.
image

As you can see the interceptor intercepted the call to the method on our ExampleManager.   Adding new public methods to our manager call will automatically get intercepted also.  This means that adding code in the future required no thought about the interceptor.  This opens up all kinds of ideas for interceptors like:

  • Exception Handling
  • Logging
  • Performance Counters
  • Authorization
  • Caching
  • Timing
  • etc...

Note there is a different way to implement interceptors.  You can use an attribute on a class that is already under the control of Windsor.  More information about this can be found here: http://docs.castleproject.org/Windsor.Interceptors.ashx.

Monday, April 15, 2013

Castle Windsor in Asp.Net MVC 4

The project I am using at work currently uses Castle Windsor as its IOC container.  My colleague did the initial setup so I decided to do this blog post based on a new MVC project to explain the setup and get more familiar with the steps needed to make MVC and Castle Windsor work together.

First thing, create a new MVC 4 website (which template you use is up to you).  After that I updated all the existing NuGet packages and added this one Castle Windsor.

Create a Infrastructure folder at the root of the MVC application.  Inside the Infrastructure folder create a WindsorControllerFactory class.  This will inherit MVC’s DefaultControllerFactory and override the GetControllerInstance and ReleaseController methods. We will use this class in a later step to tell MVC to use this controller factory instead of its default one.

public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel kernel;

        public WindsorControllerFactory(IKernel kernel)
        {
            this.kernel = kernel;
        }

        public override void ReleaseController(IController controller)
        {
            kernel.ReleaseComponent(controller);
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
            }
            return (IController)kernel.Resolve(controllerType);
        }
    }

Next create a folder in the Infrastructure called Installers.  This is where all of the installers used by Windsor will go.  Our first installer will be a class named ControllersInstaller.  This inherits the IWindowsInstaller interface which requires the implementation of the Install method.  The code below basically says all classes in the assembly that are based on the IController interface should be created using LifestyleTransient which basically means instantiate an instance every time.

public class ControllersInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Classes.FromThisAssembly()
                                .BasedOn<IController>()
                                .LifestyleTransient());
        }
    }

The last step needed to get things running is the modifications needed in the global.asax.cs file.  There are several things going on the code below.  Note the static field used to store the container, the value of the field is set in the static method BootstrapContainer.  This method does two things.

  1. Set the value of the container by instantiating an instance of the WindsorContainer and telling it to Install all the installers in the assembly (basically any class that inherits form the IWindsorInstaller interface).
  2. Tell MVC to use our WindsorControllerFactory instead of the default MVC controller factory implementation.

The BootstrapContainer method is called on application start after the other MVC registration code.  The last change is to dispose the container on application end.

public class MvcApplication : System.Web.HttpApplication
{
    private static IWindsorContainer container;

    private static void BootstrapContainer()
    {
        container = new WindsorContainer().Install(FromAssembly.This());

        var controllerFactory = new WindsorControllerFactory(container.Kernel);
        ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        MvcApplication.BootstrapContainer();
    }

    protected void Application_End()
    {
        container.Dispose();
    }
}

At this point adding a controller and view should work correctly.  All these changes to make MVC work the way it would have before doing all this.  So what is the big deal, what if in my Home controller I wanted to do something like this:

private IContactManager contactManager;

public HomeController(IContactManager contactManager)
{
    this.contactManager = contactManager;
}

Using the code we have now this would not work since the container at this point would not know how to resolve IContactManager into its concrete implementation.  To get this to work we would need to add a new installer to our installer folder.  For example:

public class ManagerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
            .Where(type => type.Name.EndsWith("Manager"))
            .WithServiceDefaultInterfaces()
            .Configure(c => c.LifestyleTransient()));
    }
}

This installer’s install method would get called by the instantiation of the container in the global.asax.cs application start event.  This installer says to register all the classes in the assembly that end in Manager and follow the default interface pattern (info) and instantiate them on a per use basis.

So now lets say the CustomerManager had a dependency on the CustomerRepository.  This would require a new installer.  I prefer to use a separate installer for each convention I am going to use.  This way if a specific convention needs to have a different lifestyle (per call, singleton, etc…) it easier to setup.  No need to show this installer since it would be just like the one above with a separate lambda in the where clause.