1 2 3 4 5 6 7 8 9 10 11 12

Dependency Injection Containers - Cheat Sheet

01 Feb, 2015

There are a lot of articles out there that describe both Dependency Injection and Inversion of Control. The purpose of this one is to serve as a quick reference for the things I keep forgetting because configuring a DI container is something I do so infrequently. This is a very simple guide showing the easiest scenarios and the simplest syntax. It walks through the same 3 steps:

1. Create Container
2. Configure Container
3. Retrieve from Container

In the following DI libraries:

  • Ninject
  • Unity
  • SimpleInjector
  • StructureMap

Of course it will feature examples tenuously related to animals.

Principals

A Dependency Injection library makes dependency injection easier by doing the work of wiring up an "object graph" (collection of related objects) for your application to use. This is generally done at the entry point to an application:

  • For console apps this is in the main method of Program.cs.
  • For MVC and Web API apps this is in Startup.cs.
  • For class libraries it is difficult to include dependency injection in the library itself as these have no defined entry point. One approach is to rely on the calling application to wire up the dependencies.
  • For WebForms apps it is possible to setup the DI container in the Global.asax Application_Start method however it's a bit more complicated.

Console App Example

In this example we're going to begin building a console app which simulates an ecosystem of toads.

picture of a toad

...

EF7 Table Mapping Exception

15 Jan, 2015

Note: This blog post relates to a library undergoing development and as such the information is likely to become outdated.

Even with Database First through the EDMX gone in Entity Framework 7 it's still possible to work with existing databases.

While trying this out with one of my databases I ran into the following Exception:

<Message>An error has occurred.</Message>

<ExceptionMessage>Invalid object name 'SomeClass'.</ExceptionMessage>

<ExceptionType>System.Data.SqlClient.SqlException</ExceptionType>

<StackTrace>
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)[...]
</StackTrace>

The Entity Framework "Invalid object name [class name]" exception means that the matching table for one of your classes hasn't been found.

In this case I'm trying to map the SomeClass to the underlying SQL table Map.Test:

[Table("Test", Schema="Map")]
public class SomeClass
{
    public int Id { get; set; }
}

The current version of EF7 (7.0.0-rc1-11953) does not have support for mapping using attributes in this way. Instead one must use Fluent configuration in the DbContext as follows:

public class MyContext : DbContext
{
    public DbSet<SomeClass> SomeClasses { get; set; }

    protected override void OnConfiguring(DbContextOptions options)
    {
        options.UseSqlServer(ConnectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<SomeClass>().ForRelational().Table(tableName: "Test", schemaName: "Map");
    }
}

The mapping is configured fluently in the OnModelCreating method. For slightly more useful information about setting EF7 up see this link.

I hope this helps!

...

C# Async for Slugs

07 Dec, 2014

Fun fact for you dear reader, I've not been programming for long, my degree was in Chemistry and though I taught myself a little programming during my degree I was mainly focused on Chemistry. This means I've been programming professionally for less time than C# 5 has been released.

This is why I've found tutorials so far for the Async/Await features in C# 5 (Net 4.5) to be a little lacking, they generally assume the reader has been writing async programs prior to the release of the features.

As a solution to this I've endeavoured to write a guide to async for miserable slugs like myself who have not had exposure to async prior to these keywords.

Demo Scenario

We're going to stick with a very simple console app available on GitHub to make sure all the concepts can be understood by a slug.

Our Program.cs main method is shown below:

public static void Main(string[] args)
{   
    SlugService slugService = new SlugService();
    slugService.GetSlugs(generation: 1);
}

The GitHub version contains a lot more lines which allow the method calls to be timed with the built in stopwatch.

The Slug Service is tasked with retrieving the records of some slugs we've stored somewhere. Let's see what it does:

...

ASP NET MVC - Model Create With List of Model

25 Nov, 2014

This post runs through how to create a form for creating a model with a list of child models using MVC 5 and Razor.

I've been rather quiet on the blogging front lately, I've been working on getting my MVC 5 quiz application up and running on Azure, it's here if anyone wants to give it a go.

One thing I wanted to do while working on the site was allow for a model to be created along with a list of "sub" models; for example when creating a question it would be nice for a user to also create the answers on the same page.

Setup

To demo this we need a model which could "own" some collection of other items. I happened on the perfect example today in the Json.NET source:

Rabbit with a pancake on its head.

...

ASP.NET Identity 2.0 Tutorial - Password Reset and Roles

13 Oct, 2014

Given how much you all enjoyed the previous tutorial, i.e. not at all, I thought I'd write a follow up post. As promised this blog post extends the basic system we created in the main tutorial to add roles and a password reset function.

I won't show how to setup the emails for password reset because I'm too lazy to fill in the form for a free SendGrid account, however plugging emails in should be the easy bit.

Password Reset

The default template provides the controller actions and views for a full password reset function. The user can enter an email address at /Account/ForgotPassword. When posted the action below is called:

public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = await UserManager.FindByNameAsync(model.Email);
        if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id.ToString())))
        {
            // Don't reveal that the user does not exist or is not confirmed
            return View("ForgotPasswordConfirmation");
        }
        string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id.ToString());
        var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);      
        // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
        return RedirectToAction("ForgotPasswordConfirmation", "Account");
    }
    return View(model);
}

I have commented out the email sending part for the reasons mentioned above.

All we need to do is supply our UserManager with a token provider. From the code for the default UserManager:

/// <summary>
/// Used for generating reset password and confirmation tokens
/// </summary>
public IUserTokenProvider<TUser, TKey> UserTokenProvider { get; set; }

As usual Microsoft have made everything easy by giving us a nice interface to implement. This also means you can adapt your password reset to function however you like. For instance you could add an expiry date to the reset token or have a token which is a combination of a Guid and number or two Guids.

For my token provider I'm simply going to generate a new Guid to act as the reset token. This maps onto the nullable reset token field on my user table, I've hidden some stuff here because I don't want you stealing the super secure password hashes ("password" and "password1"):

...
1 2 3 4 5 6 7 8 9 10 11 12