Thursday 18 December 2014

Getting NServiceBus, SignalR and Autofac to work together

I’m currently working on an existing web app that we’re updating to add in NServiceBus and SignalR. A broad brush overview is shown below…

image

Here a request is sent from the browser which goes to a SignalR hub inside the website. That request is then sent onto the bus and some back end magic happens, which ultimately ends up in a response being sent to the bus. This is picked up by the website and a response is pushed down to the client courtesy of SignalR.

If we look into what’s happening inside the website we see the following…

image

The hub implements an interface that’s injected into the message handler, so that the handler can call back to the hub when the response message comes in, which ultimately then makes the hub call back to the browser to finish the loop.

Getting all this setup was a bit of a bother and I went down a few blind alleys before getting it all to work properly, hence documenting it so that I can hopefully short-circuit someone else’s work.

In pseudocode this is what happens…

  • The browser makes a request to the hub.
  • The hub code creates a unique Request Id, and stuffs this into a dictionary, mapping this Request Id to the SignalR Context.ConnectionId.
  • The hub then sends a message onto the bus, this contains the Request Id.
  • After the back-end has processed this message a response is placed on the bus, again containing the Request Id.
  • The message handler receives the message and uses the callback interface and Request Id to build a dynamic object that we can call the browser back with.
  • The message handler then makes the callback.

For this example I’m doing the callback within the message handler, but you could encapsulate this fully within the Hub too if you prefer. OK, enough explanation, on to some code…

    public interface ICallback
{
dynamic GetCallback(Guid requestId);
}



This interface is used to communicate between the message handler and the Hub. In addition I added a “registration” service that is used to map a Request Id to a client connection Id…

    public interface IRegistration
{
void Register(Guid id, string data);

string GetRegistration(Guid id);
}



The implementation of this service was a simple dictionary, this however should be beefed up as it needs a “tidy up” mechanism that will ensure that data is removed from this dictionary when the client disappears. The hub then is as shown below…

    public class WibbleHub : Hub, ICallback
{
public WibbleHub(IBus bus, IRegistration registration)
{
_bus = bus;
_reg = registration;
}

public void RequestWibble(string text)
{
Guid requestId = Guid.NewGuid();

_reg.Register(requestId, Context.ConnectionId);

_bus.Send(new WibbleMessage { RequestId = requestId, Text = text});
}

public dynamic GetCallback(Guid requestId)
{
dynamic callback = null;
string clientId = _reg.GetRegistration(requestId);

if (null != clientId)
callback = Clients.Client(clientId);

return callback;
}

private IBus _bus;
private IRegistration _reg;
}



The hub imports the bus and registration services, and the RequestWibble method is the one we’re calling from the web client. This registers the mapping between the Request Id and the client Connection Id, and then sends a message onto the bus.


The GetCallback method uses the registration service to find the client connection Id, then returns a dynamic object hooked to that client if the Id matches one that has been registered.


The message handler is fairly simple too…

    public class WibbleHandler : IHandleMessages<WibbleMessage>
{
public WibbleHandler(ICallback callback)
{
_callback = callback;
}

public void Handle(WibbleMessage message)
{
var cb = _callback.GetCallback(message.RequestId);

if (null != cb)
{
try
{
cb.wibbleSucceeded(message.Text);
}
catch (Exception ex)
{
int i = 0;
}
}
}

private ICallback _callback;
}



The handler imports the ICallback interface (exposed by the Hub), and when it handles the incoming message it calls the GetCallback() method to retrieve the dynamic object that allows us to call down to the web client.


The last piece of the puzzle is wiring this up, and that was the main thing that took time to get right, mainly down to my misunderstanding of how NServiceBus does its stuff. I created a DependenciesConfig file as follows…

    public static class DependencyConfig
{
public static void BuildDependencies()
{
var container = BuildContainer();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

public static IContainer BuildContainer()
{
if (null == _container)
{
var builder = new ContainerBuilder();

builder.RegisterControllers(Assembly.GetExecutingAssembly())
.PropertiesAutowired();

builder.RegisterType<WibbleHub>()
.AsSelf()
.As<ICallback>()
.ExternallyOwned()
.SingleInstance();

builder.RegisterType<Registration>().As<IRegistration>().SingleInstance();

_container = builder.Build();

var config = new BusConfiguration();
config.UsePersistence<InMemoryPersistence>();
config.UseTransport<RabbitMQTransport>();
config.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(_container));

var bus = Bus.Create(config);
bus.Start();

}

return _container;
}

private static IContainer _container;
}



This has a static BuildContainer method that creates the AutoFac container, and there are a couple of things of note. First off is the registration of the hub, this is registered as a singleton, as is the registration service too.


Then (and this is the bit that I got wrong) is the configuration of the bus. First off, the container is built before the bus is constructed, so the bus itself is not constructed as part of the container itself, it lives “outside”. The bus is setup to hook to the Autofac container using the UseContainer() member, this links the bus to the registered components, and means that when a message comes in on the bus that it can resolve all dependencies such as the ICallback interface exposed by the hub.


Now to the voodoo magic. In the above there is nowhere that the bus itself is registered with the Autofac container, so conventional wisdom would dictate that any components requiring IBus wouldn’t be able to resolve it, so for example this controller shouldn’t work…

    public class DefaultController : Controller
{
public DefaultController(IBus bus)
{
_bus = bus;
}

public ActionResult Index()
{
return View();
}

private IBus _bus;
}



But it does work. How is a mystery. After a bit of searching I came across this post on Stack Overflow that indicates that NSB does this for you. That’s great, but also somewhat confusing for anyone who doesn’t know this beforehand, which presumably is everyone who uses NSB and Autofac, or any IOC container probably as people are used to registering dependencies themselves, rather than some magic happening. Personally I’m not a fan of this magic, it’ll most likely trip you up. However, with this in place it all works as expected – I can then pop some Javascript into my client and everything works as expected.


There’s one more class to add and that’s the startup for Owin, so that we can get SignalR up and running properly…

    public class Startup
{
public void Configuration(IAppBuilder app)
{
var container = DependencyConfig.BuildContainer();

GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);
app.UseAutofacMiddleware(container);
app.MapSignalR(new HubConfiguration { EnableDetailedErrors = true });
}
}



The demo (attached) has a simple form where you can enter text, click a button and lo and behold a message is displayed on screen. That’s pretty useless, but at least is shows how NServiceBus, Autofac and SIgnalR can play nicely together. I’m using RabbitMQ as my messaging infrastructure, feel free to bring your own along if you would prefer.


Hope this helps someone!

Monday 17 November 2014

Fun (or rather not) with EventSource

I’ve been an advocate of good logging in applications (especially server side ones) for many years, and today I’m working on something for myself and wanted to use the latest and greatest event logging framework so chose System.Diagnostics.Tracing (which has been around since .NET 4 days). I’ve used it before but today I came across an issue that had me stumped for some time.

I’d created a custom event source, and derived this from an interface so that I could inject an implementation in at runtime…

  public interface ILogger
{
void T1(string message);
void T2(string message);
}

public class Logger : EventSource, ILogger
{
public void T1(string message) { this.WriteEvent(1, message); }
public void T2(string message) { this.WriteEvent(2, message); }
}

But when I used PerfView to view my events there were none. After a lot of head scratching I tried a sample from Vance’s blog (which seems to be the main place to get any information about this feature) and of course that worked first time. I did some more fiddling in code and then stumbled across the reason as I was debugging the code. It’s worthy of a blog post, as this may well catch someone else out.


I’d created the interface and implemented it in the EventSource derived class so that I could mock out the logger code for testing – however this was the part that caught me out. When the code runs, the EventSource class builds a manifest that contains details of the "events" that are written out – and this uses the following bit of reflection to get all the methods that we want to expose as "events" in the ETW trace…

  MethodInfo[] methods = eventSourceType.GetMethods(BindingFlags.NonPublic | 
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);

I’ve highlighted the offending enum value above. This is saying "find me all methods whether public or not, defined on this Instance ONLY". So, because I’d created an interface and then implemented that interface, my methods were not found by the code that generates the manifest, and hence I wasn’t getting anything useful in the ETL file.


The net effect of this is that I cannot directly use an interface to define an interface for the events I want to emit. There are a few ways around this I can think up…



  • Hard-code the logger class as in the examples on Vance’s posts. Nope, not going to fly, I this stuff to be mockable/testable!
  • Create an EventSource derived class and add shim methods to call the actual logging methods
  • Write my own version of EventSource, seems like a lot of work for little gain!
  • Create a shim class that forwards all calls to the EventSource derived class

Of these I picked the last, as I do want my event source code to be mockable, and it seemed to be the least bad of the options, so I ended up with the following class...

  public class ActualLogger : EventSource
{
public void T1(string message) { this.WriteEvent(1, message); }
public void T2(string message) { this.WriteEvent(2, message); }
public static ActualLogger Instance { get { return _instance; } }
static ActualLogger _instance = new ActualLogger();
}

public class Logger : ILogger
{
public void T1(string message) { ActualLogger.Instance.T1(message); }
public void T2(string message) { ActualLogger.Instance.T2(message); }
}

Well, something like that anyway!


As an aside, if you want to look at the manifest that is generated from your EventSource derived class, there's a static method on EventSource that can be useful...

    var manifest = EventSource.GenerateManifest(typeof(ActualLogger), typeof(ActualLogger).Assembly.Location);

Hope this helps someone!

Thursday 23 October 2014

ComboBox binding in Workflow activities

Today I was creating a simple activity with a couple of combo boxes, and came across a problem where the binding wasn’t working correctly (well, at all). I had an InArgument<string> property on my activity, and wanted to set this from a combo box on the design surface. I guess I haven’t done this before as it doesn’t work out of the box, and you need to write an IValueConverter to get it working. I’ve trodden this path before but this was a bit of a tricky beast.

After some wailing and gnashing I came up with the following base class converter…

public abstract class ComboBoxToModelItemConverter<T> : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
T retVal = default(T);

ModelItem mi = value as ModelItem;

if (null != mi)
{
var arg = mi.GetCurrentValue() as InArgument<T>;

if (null != arg)
{
var expression = arg.Expression;
var literal = expression as Literal<T>;

if (null != literal)
retVal = literal.Value;
}
}

return retVal;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return new InArgument<T>((T)value);
}
}





I then created a concrete class to bind to InArgument<string>…

public class ComboBoxStringToModelItemConverter : ComboBoxToModelItemConverter<string>
{
}



With that created I could then get the binding to work by adding the converter to the binding. I have a class that contains TemplateId and Name, I wish to show the Name on screen but store the TemplateId (and this is mapped to an InArgument<string> on the activity). The XAML is as follows…

<local:ComboBoxStringToModelItemConverter x:Key="comboConverter"/>


<ComboBox ItemsSource="{Binding Templates}" 
SelectedValue="{Binding ModelItem.TemplateId, Converter={StaticResource comboConverter}}"
SelectedValuePath
="TemplateId" DisplayMemberPath="Name" />



With that done it all works as expected. I’m surprised that a converter such as this doesn’t exist in the Workflow libraries – and also in the many, many years I’ve been playing with Workflow that I’ve not needed one. Anyhow, I hope this is of use to someone!

Tuesday 30 September 2014

Fun with ExpressionTextBox

After a short hiatus doing other things (a lot of back-end services work) I’m back in the fray with Workflow.

Yesterday, a colleague asked me to help out with an activity he was building that works like a combination of an If and a ForEach. The basic premise is that we have a List<Something>, and want to iterate through that list until we find a match with a Predicate<Something>, in which case we then schedule a child activity.

So, I came up with the following…

image

Here we have a collection of Noodle’s (as an argument called Stuff), and we’re going to iterate through all elements in the collection until we find the first that matches the predicate (x => x.Name == “Sausages”). When found, we then execute the Body activity, with item as the variable holding the selected Noodle instance.

The activity code is fairly simple…

    public class Find<T> : NativeActivity, IActivityTemplateFactory
{
public InArgument<IEnumerable<T>> Values { get; set; }

public ActivityAction<T> Body { get; set; }

public InArgument<Predicate<T>> Match { get; set; }

protected override void Execute(NativeActivityContext context)
{
var match = this.Match.Get(context);

// Iterate through the collection and if we find a match, we're sorted...
foreach(var o in Values.Get(context))
{
if (match(o))
{
context.ScheduleAction<T>(this.Body, o);
break;
}
}
}

protected override void CacheMetadata(NativeActivityMetadata metadata)
{
...
}

public Activity Create(DependencyObject target)
{
...
}
}



The activity contains a collection of type T, a body that is passed the selected value from the collection, and a predicate that matches against the items in the collection. I’ve also overridden CacheMetadata to setup all of the arguments correctly, and in addition implemented IActivityTemplateFactory as there’s some setup that needs to be done when the activity is created in order to get it to work correctly. Full details are in the code download.


In the Execute method I iterate through the elements in the collection and execute the Match function against each. For the first that matches I then schedule the body activity, passing through the selected element. This then terminates the loop (that’s what we wanted, a more standard implementation might iterate though all matching elements in the collection.


The Designer


The important thing about the code is the designer (and that’s why I wrote the post in the first place). It’s fairly rudimentary, but there is something that might trip you up which is why I wrote this post.


The designer XAML contains a couple of ExpressionTextBox’s as shown in the image below…


image


The first is bound to the Values property on the activity, the second to the Match property. The important thing to note is that in order to get these to work properly you *must* use the ExpressionType property of the ExpressionTextBox…

    <sapv:ExpressionTextBox
Expression="{Binding ModelItem.Values, Mode=TwoWay,
Converter={StaticResource argToExpressionConverter}}"

OwnerActivity="{Binding ModelItem, Mode=OneWay}"
ExpressionType="{Binding ListType}"/>



Now, the type of items in the bound List is based on the type of element you choose to fill the list – in my case I have Noodles. So, the ExpressionType for the list would be IEnumerable<Noodle>, and the datatype for the predicate would be Predicate<Noodle>.


If you don’t use the ExpressionType property of the ExpressionTextBox then the text box will essentially be one-way, it will bind to values you set on the property grid, but won’t allow you to push values the other way (even if those values match 1:1 with what you type in the property grid). So, ExpressionType is mandatory, and has to be the right type.


In order to get the right type, I have created two properties on the Designer, and these call down to the underlying activity to get the actual type necessary. As an example here’s the code for the ListType…

    public Type ListType
{
get
{
if (null == _listType)
{
var findActivity = this.ModelItem.GetCurrentValue();

var valuesProp = findActivity.GetType().GetProperty("Values");

var args = valuesProp.PropertyType.GenericTypeArguments;

_listType = args[0];
}

return _listType;
}
}

private Type _listType;



This code gets the fund activity which is exposed through the ModelItem (which is a proxy object over the activity you are editing). I then lookup the Values property and return the first generic argument – in my example this will be IEnumerable<Noodle>. I have a similar property for the match predicate.


The Code


If you want to have look at the full code please click to download it…

Tuesday 8 July 2014

Polling with Timeout in .NET 4.5

A couple of times recently I have needed to be able to wait (asynchronously) for something to happen, but also permit a timeout to occur. I wrote a version of this many moons ago that used wait handles and was pretty difficult to understand, now with async support in .NET I decided to rewrite it.

The basic premise is that I want to be able to call the following…

while (not done and not timedout)
{
if (signalFunc())
return (dataFunc());
else
wait a bit;
}


The signalFunc() is called to check that something has happened. The dataFunc() returns the actual data you are waiting for.

One of the places I need this is when trying to make a fully asynchronous pipeline in Azure look like a synchronous function to the caller. A request comes in, gets queued, gets processed, gets queued again, and gets processed again before being complete – and I want a way to hide all of this complexity from a caller so that we can provide an API that looks synchronous to the caller, but is actually asynchronous internally.


In this case I add a sentinel value to the database that the signalFunc() looks for, and then push the request into my Azure pipeline. The signalFunc() is polled repeatedly and, once the request has passed al the way through my request pipeline it updates the sentinel in the database. The signalFunc() will then report true and I can then execute the dataFunc() to find whatever it is the caller needs and return it to them.


So, after having rewritten this using async I have arrived at the following API…

public static Task<T> PollWithTimeoutAsync<T>(Func<bool> signalFunc, Func<T> dataFunc, int millisecondsBetweenPolls, int millisecondsToTimeout)



There’s also another one that includes a cancellation token. The signalFunc() is called repeatedly (with a delay of millisecondsBetweenPolls) and if true the dataFunc() is called to provide the data. The whole operation waits at most millisecondsToTimeout before throwing a TimeoutException.


The full code is as follows…

public static async Task<T> PollWithTimeoutAsync<T>(Func<bool> signalFunc, Func<T> dataFunc, int millisecondsBetweenPolls, int millisecondsToTimeout)
{
if (null == signalFunc) throw new ArgumentNullException("signalFunc");
if (null == dataFunc) throw new ArgumentNullException("dataFunc");
if (millisecondsBetweenPolls >= millisecondsToTimeout) throw new ArgumentException("The millisecondsBetweenPolls should be less than millisecondsToTimeout");

using (var cts = new CancellationTokenSource(millisecondsToTimeout))
{
bool done = signalFunc();

while (!done)
{
try
{
await Task.Delay(millisecondsBetweenPolls, cts.Token);
}
catch (TaskCanceledException)
{
throw new TimeoutException();
}

done = signalFunc();
}

return dataFunc();
}
}



It’s fairly terse (isn’t all good code like that?) and uses a feature of CancellationTokenSource which helps out a lot here, as the override I have used ensures that the token is cancelled after the period defined by the millisecondsToTimeout parameter. So, I setup a cancellation token source to go off in a few seconds, then loop calling the signalFunc() and if that reports false, use Task.Delay() to wait for a while before polling again. The beauty of Task.Delay is that it’s also cancellable by using a cancellation token, so if I’m in the middle of waiting and the overall timeout expires, the delay task will throw a TaskCancelledException, which I convert into a TimeoutException before throwing it up the chain.


Here I’m basically waiting in a loop, periodically calling the signalFunc(), but able to fail when the cancellation token timer fires. Simple and elegant!


If you want the version that also has a cancellation token then that’s here for you too…

public static async Task<T> PollWithTimeoutAsync<T>(Func<bool> signalFunc, Func<T> dataFunc, int millisecondsBetweenPolls, int millisecondsToTimeout, CancellationToken cancellationToken)
{
if (null == signalFunc) throw new ArgumentNullException("signalFunc");
if (null == dataFunc) throw new ArgumentNullException("dataFunc");
if (millisecondsBetweenPolls >= millisecondsToTimeout) throw new ArgumentException("The millisecondsBetweenPolls should be less than millisecondsToTimeout");

using (var cts = new CancellationTokenSource(millisecondsToTimeout))
{
using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken))
{
bool done = signalFunc();

while (!done)
{
try
{
await Task.Delay(millisecondsBetweenPolls, linkedCts.Token);
}
catch (TaskCanceledException)
{
// Was this a timeout?
if (cts.IsCancellationRequested)
throw new TimeoutException();
else
// No, it was most probably the outer cancellation token
throw;
}
done = signalFunc();
}

return dataFunc();
}
}
}



Hopefully someone will find this useful. If you want the code, complete with unit tests then please click here.

Wednesday 4 June 2014

Using Data Annotations with Portable Class Libraries

I am currently writing an application that’s targeting multiple platforms – iOS, Android, Windows Phone as clients, and naturally .NET on the server which will be hosted in Azure. I’m making good use of portable class libraries, so that I can share as much code between my clients as possible (and I’m using Xamarin to make all this possible).

For my client projects I have two shared libraries – one with interfaces, another with implementations. As an example I have a DTO class on the client as follows…

public class AccountInformationRequest
{
public string Token { get; set; }

public string MSISDN { get; set; }

public string Carrier { get; set; }
}



This class is also used on the server in a controller method…

public async Task<AccountInformation> PostAccountInformation(AccountInformationRequest request)
{
return await _accountInformationService.GetAccountInformation(request);
}



On the server however I want to use data annotations to minimise the amount of code I need to write in order to validate the incoming request but this poses a problem – the AccountInformationRequest type is defined in a Portable Class Library, and if I update it to add on the data annotation attributes then my PCL will be re-targeted and won’t then run on all of my desired client platforms.


As usual in programming, another level of indirection solves every problem. Since .NET 1.0 we’ve had ICustomTypeDescriptor, and indeed one of the first articles I wrote online was about this interface (the article is long gone, it was written in 2001 ish). Since .NET 2 things have got measurably better for anyone wanting to do some spelunking with types, as it released the TypeDescriptor and TypeDescriptorProvider support. Fast forward a few more years and we now have a very simple way to augment one class with metadata from another – the massively named ‘AssociatedMetadataTypeTypeDescriptionProvider’.


What this class allows you to do is say “Hey, this class X provides metadata for that class Y”. Or more to the point for this article, “This server class which has all the attributes I need replaces the metadata for the PCL class”. All you need to do is create a second class which has all the metadata attributes you need (in my case just validation), then register it. My server side class is as follows…

public class AccountInformationRequestServer
{
[Required]
public string Token { get; set; }

[Required]
public string MSISDN { get; set; }

[Required]
public string Carrier { get; set; }
}



Then I can just register it inside Global.asax…

TypeDescriptor.AddProvider
(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(AccountInformationRequest),
typeof(AccountInformationRequestServer)),
typeof(AccountInformationRequest));



The registration looks a little cryptic, so I’ve altered it below to show the orginalClass (that being the class defined in the PCL) and the metadataClass (that being the one defined server side)…

TypeDescriptor.AddProvider
(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(originalClass), typeof(metadataClass)),
typeof(originalClass));



That’s all there is to it. Now I can make an API call from the client, and have API validation on the server, whilst still using the same datatypes in both PCL and full fat .NET.


You’ll find the AssociatedMetadataTypeTypeDescriptionProvider class defined within System.ComponentModel.DataAnnotations (in the assembly with the same name).


Wednesday 9 April 2014

Altering the schema name of ASP.NET Identity tables

I like keeping my database schema as clean and readable as possible, and one of the things I do is use a schema name to group related functionality.

I’ve been doing a fair bit of work with ASP.NET Identity recently, and one of the things was to add the generated tables for identity into their own schema. Moreover, I also wanted to change the name of the tables. This is a snap using Code First – all you need to do (in your IdentityDbContext derived class) is the following…

    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<DbUser>().ToTable("Users", "AUTH");
    modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles", "AUTH");
    modelBuilder.Entity<IdentityUserLogin>().ToTable("ExternalLogins", "AUTH");
    modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims", "AUTH");
    modelBuilder.Entity<IdentityRole>().ToTable("Roles", "AUTH");

Make sure you call the base class OnModelCreating method before including these changes. With that you’ll get a nice set of tables inside SQL server…

image

I realise that this will mean that I need to be careful when installing a new version of ASP.NET Identity (to ensure that the override still works), but I’d rather pay that price and have a ‘clean’ schema.

Monday 7 April 2014

Optimizing ASP.Net Identity Database Access

I have to say I’m a bit obsessive about issuing SQL requests as they take time, and so the fewer requests I can make the better.

Recently I’ve installed the latest version of ASP.NET Identity (2.0.0.0) and whilst running SQL Profiler I noticed something odd being executed for every instance of my DbContext class. What I was expecting was one SQL statement (that being the one I was explicitly issuing), however what I actually saw in the profiler was three…


(1) SELECT Count(*) FROM sys.databases WHERE [name]=N'VPC'


(2) exec sp_executesql N'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME=@Table',N'@Table nvarchar(11)',@Table=N'AspNetUsers'


(3) SELECT
[Extent1].[PublisherId] AS [PublisherId],
[Extent1].[ApiKey] AS [ApiKey],
[Extent1].[Name] AS [Name],
[Extent1].[Description] AS [Description]
FROM [VPC].[Publisher] AS [Extent1]
ORDER BY [Extent1].[Name] ASC

The one I was expecting was #3, the other two were unexpected and also unwanted. So I had to find out where they were coming from.


When I start hunting I always think “it’s my fault, I’ve caused this somehow” – and to be honest it almost always is caused by my code. But I was pretty sure that this wasn’t my code – or at least, it wasn’t cause by my code directly. What followed was an hour or so of fruitless searching in my project – I began with an EF profiler, no change, then I added some extra debug, no change, wired up some logging for Owin to see if it was one of the bits of middleware added into the pipeline, still no change, none was telling me what I needed to know.


I then started hunting on the web, and happened to find just what I needed on www.symbolsource.org, specifically the code for the IdentityDbContext class (which was where I’d hazarded a guess the problem was). I was (as most people will do) deriving from IdentityDbContext<TUser> which I’d assumed was benign but it wasn’t. It contains the following code in the default constructor…

  public IdentityDbContext(string nameOrConnectionString)
: this(nameOrConnectionString, true)
{
}

And looking at the next constuctor...

  public IdentityDbContext(string nameOrConnectionString, bool throwIfV1Schema)
: base(nameOrConnectionString)
{
if (throwIfV1Schema && IsIdentityV1Schema(this))
{
throw new InvalidOperationException(IdentityResources.IdentityV1SchemaError);
}
}

Not much going on there - or is there?. If you look at the code for the IsIdentityV1Schema function it reveals all - it's checking if the database exists, and it's also doing the column name lookup.


So, to remove the two additional SQL statements from your code, you need to pass false as the second parameter to the IdentityDbContext constructor…

  public class DbApplicationRepository 
: IdentityDbContext, IDbApplicationRepository
{
public DbApplicationRepository(string connectionString)
: base(connectionString, false)
{
}

...
}

Hopefully this will help someone!

Friday 7 March 2014

Your hosting provider does not yet support ASP.NET 4.5…

Oh yes it does, I’ve been using .NET 4.5 for *ages* on Azure. Well, it feels like it anyway, but today I got this error after adding an extra couple of dependencies in from NuGet.

It was a simple fix – the stuff I’ve added (Cross Origin Requests) has updated my project but not set it to .NET 4.5.1 which is necessary for it to work. A quick trip to settings land…

image

And now it’s working again. Phew!

Sunday 2 March 2014

Configuring ASP.NET Identity

[Note: It looks like email is now a first class entity in the database tables as of version 2.0.0.0 of the EF Identity provider]
Recently I’ve been tinkering around with ASP.NET Identity and, like many, have stumbled around in the dark due to lack of documentation – or lack of me being able to find the documentation. Rather than add to the problem I’ll add to the solution, by adding some much-needed documentation as I go.
I have a new project that I want to add ASP.NET Identity to, and after having let the default code whirr around for a while I need to extend it a little. What I want to do is as follows…
  • Add some extra columns to the ‘user’ table
  • Allow email addresses as usernames
I’m sure I may find more things I need to do as I go, but this will do for the moment. I like clear separation of concerns, so am splitting out the data context and associated classes into another assembly for now – that way I can get to grips with it better and also swap it out for something else if necessary. The shell of the solution contains the following classes…
    public abstract class ApplicationUser : IdentityUser
    {
        public string Email { get; set; }
    }



That’s my extended “user” class for now, I’ve added an email property as I need to record that in the database. In my scenario I have two types of user in the system – parents and children. A parent has a username and an email (which may both be the email address), whereas a child may not have an email address.
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext() : base("DefaultConnection")
        {
        }
    }



This DbContext class derives from the provided IdentityDbContext<TUser> class (that resides in the Microsoft.AspNet.Identity.EntityFramework assembly). You’ll notice that the constructor passes the database connection string “DefaultConnection” to the base class – this is the name used by ASP.NET Identity so I thought I’d use it too. Now to create a user and test what I’ve done so far. I created a simple Console app, created a database in SQL Express, and then fired up the following code…
    using (var ctx = new ApplicationDbContext())
    {
        var store = new UserStore<ApplicationUser>(ctx);
        var manager = new UserManager<ApplicationUser>(store);

        // Now create a user...
        ApplicationUser user = new ApplicationUser
        {
            UserName = "Test",
            Email = "me@here.com"
        };

        var result = manager.Create(user, "password");
    }



The UserManager class is provided by Microsoft.AspNet.Identity, and is a corollary to the Membership class of old – with a few new bits added for good measure, most notably a load of Task<> methods so you can do all of this stuff asynchronously.

The UserStore class provides an EF based implementation of the IUserStore<TUser> interface. So, if you want to store your users somewhere else, just cruft up an IUserStore<> derived class and you’re away - it’s a very small interface…
    public interface IUserStore<TUser> : IDisposable where TUser : Microsoft.AspNet.Identity.IUser
    {
        Task CreateAsync(TUser user);
        Task DeleteAsync(TUser user);
        Task<TUser> FindByIdAsync(string userId);
        Task<TUser> FindByNameAsync(string userName);
        Task UpdateAsync(TUser user);
    }



Not much to override there should you wish to store and retrieve users from somewhere other than the standard store. However, the user store will probably need to do a lot more than just the above, so there are a bunch of additional interfaces that a user store should consider implementing. These are as follows…
    IUserClaimStore<TUser>
    IUserLoginStore<TUser>
    IUserPasswordStore<TUser>
    IUserRoleStore<TUser>
    IUserSecurityStampStore<TUser>

All of these derive from IUserStore<TUser> and the EF provided UserStore class implements the lot. Then there’s a bunch of properties on UserManager that check if the specified user store implements these interfaces and acts accordingly. As an example, you might not want a ‘security stamp’ on your user record – you could create your own class and implement just the bits you need.

Now, UserManager has a bunch of other properties you can set which alter how it does it’s job too. And there’s a bit of strangeness to UserManager which caught me out for a while. I’ve been programming in .NET since 2000 so I’m not a stranger to the odd exception – but when I tried this code I didn’t get any…
    ApplicationUser user = new ApplicationUser
    {
        UserName = "me@here.com",
        Email = "me@here.com"
    };

    var result = manager.Create(user, "password");



OK, so that’s created a user – right? Not in my database it hasn’t. This caught me out for a while – there was no user in the database, but also no exception, so what’s up?

Well, after some head scratching I decided to look at the result from this call and saw this…
    "User name me@here.com is invalid, can only contain letters or digits."



Aha, so that’s my problem. But no exception – hmmm, this library is going to take some getting used to. I cannot remember the last time I explicitly went looking for a “success” code before. What is returned is an IdentityResult instance which includes a Succeeded property and also a bunch of errors in a string collection. Feels like I’m back in the good old days of COM, I’m sure there’s a reason for this design – but that reason was in a meeting probably 3 years ago and hasn’t dribbled down to us. I don’t have an issue with returning multiple errors, that’s fine, but I prefer the way that the Task<> classes do their errors by returning an AggregateException at the end, rather than needing me to plumb the depths of a return code. Oh well.

Permitting emails as usernames


OK, so now to the reason you’re probably here – how do I permit a username to hold an email?

The UserManager class has a UserValidator property which implements IIdentityValidator<TUser>, and the default one doesn’t permit any non-alpha characters in a username. So, you can replace the default, or just alter a property on it as follows…
    var manager = new UserManager<ApplicationUser>(store);
    var val = manager.UserValidator as UserValidator<ApplicationUser>;

    if (null != val)
        val.AllowOnlyAlphanumericUserNames = false;



That’s it – you can now insert usernames that are email addresses. And you could optionally replace the validator with one of your own as you might want to use a regular expression to validate a username, or ensure that the username is not the same as the password and so on. One other thing that the validator does is ensure that no user exists in the database with the same username, which of course your derived class would need to do too.

Adding extra columns to the AspNetUsers table


Due to the magic that is EF 4 (and now 6), by creating my ApplicationUser class above and then adding the Email property (and running against a new database), EF will create the database structure for me so I get a new table with an Email column. Sweet.

By default you get a schema that contains tables prefixed with AspNet, such as AspNetUsers, AspNetRoles and so on. If you want to alter these you can override OnModelCreating in your DbContext class to do something like the following…
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<IdentityUser>().ToTable("Users", "auth");
    }



As an example, the above will store users in a table called Users within the auth schema. Note – if you go down this route I would suggest you don’t call the base class OnModelCreating, and instead copy the code from the base class and alter as necessary (as there’s a few intricacies in there that could bite you).

Wrap Up


With all that in place, I can now store additional information against a user, and I can also use an email address as the username.

Friday 17 January 2014

Painfully Slow Debugging in Visual Studio 2013 and Internet Explorer

I’ve been researching an issue today with debugging on VS2013 and IE. It’s a really weird one as the symptoms don’t make a great deal of sense, however I have found a cause and a temporary cure.

I have a simple website that I am debugging. If I startup the application and put a breakpoint within some code that gets called before any web requests are made all is fine.

I then click something on a page which drops me into the debugger. I was debugging some code as shown below…

Code Snippet
public ActionResult Login(string id)
{
    var ctx = Request.GetOwinContext();

    var props = new AuthenticationProperties
    {
        RedirectUri = Url.Action("Callback")
    };

    ctx.Authentication.Challenge(props, id);

    return new HttpUnauthorizedResult();
}

My breakpoint was on the first line, I was then stepping through the code and here’s the problem.

Stepping through took *ages*. The first click of F10 took about 9 seconds. Subsequent keypresses were 5 seconds or so. I had to figure this out.

As usual I turned to the internet and found a bunch of useless stuff, and then I found this which led me to this and so I download xPerf, ran some tests and came up with a graph that showed me it was Internet Explorer that was waiting which was strange – as I was inside Visual Studio, admittedly debugging something in IE. I then tried debugging with Chrome & Firefox, both were OK.

Whilst I debug I mostly use the keyboard, however during one of my sessions I used the mouse and clicked on the step commands on the toolbar, and strangely enough these worked as usual, it was single stepping with the keyboard that was causing the problem.

Unlike Bruce (the two links above) I couldn’t get any further with analysing the data (the graphs he drilled down to don’t seem to be available in the version I just downloaded), so I went back to the Net and asked again and this article popped up. LastPass – yep, I’m using it and yep, disabling it did the trick.

Now don’t get me wrong – I love LastPass and I wouldn’t be without it, but for the moment it’s off limits to Internet Explorer on my machine.

Hope this helps someone else!