Skip to content

Jimmy Bogard
Syndicate content
Strong opinions, weakly held
Updated: 2 hours 4 min ago

MediatR hits 1.0

Wed, 12/17/2014 - 16:45

I’ve been using a project I wrote/borrowed/stole from a number of internal projects and existing libraries (thanks Matt) for well over a year now, and are releasing to 1.0. MediatR helps turn complex code into simplified request/response interactions, encapsulating queries, commands and notifications into a single, simple interface, collapsing complex controllers into simple pass-throughs to the real work being done:

public class ConferenceController : Controller
    private readonly IMediator _mediator;

    public ConferenceController(IMediator mediator)
        _mediator = mediator;

    public ActionResult Index(IndexQuery query)
        var model = _mediator.Request(query);

        return View(model);

    public ViewResult Show(ShowQuery query)
        var model = _mediator.Request(query);

        return View(model);

    public ActionResult Edit(EditQuery query)
        var model = _mediator.Request(query);

        return View(model);

    public ActionResult Edit(ConferenceEditModel form)
        var conf = _mediator.Send(form);

        return this.RedirectToActionJson(c => c.Show(new ShowQuery { EventName = conf.Name }), "Default");

MediatR lets you send a request to a single handler:

var request = new ApproveInvoiceRequest {
   InvoiceId = invoiceID
ApproveInvoiceResponse response = mediator.Send(request);

Or do it asynchronously:

var request = new ApproveInvoiceRequest {
   InvoiceId = invoiceID
ApproveInvoiceResponse response = await mediator.SendAsync(request);

Or send a notification to a number of handlers:

var notification = new InvoiceApprovedEvent {
    InvoiceId = invoiceId

I’ve talked about the advantages to this pattern many times, and we use this pattern on nearly every project we encounter these days. The goal of MediatR was to create a small, unambitious implementation of the Mediator pattern, tied only to the Common Service Locator library for instantiating handlers and portable, so it works on just about every platform checkbox I could check, including Xamarin.

The GitHub repo has examples for plugging in all the major containers, and the wiki has documentation. Although the library uses Common Service Locator, it’s completely DI friendly too. Ultimately, the compositional tool is your container, and MediatR merely provides the mediation from message A to handler of A. Enjoy!

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

AutoMapper 3.3 released

Sat, 11/29/2014 - 18:40

View the release notes:

AutoMapper 3.3 Release Notes

And download it from NuGet. Some highlights in the release include:

  • Open generic support
  • Explicit LINQ expansion
  • Custom constructors for LINQ projection
  • Custom type converter support for LINQ projection
  • Parameterized LINQ queries
  • Configurable member visibility
  • Word/character replacement in member matching

In this release, I added documentation for every new feature (linked in the release notes), and pertinent improvements.

This will likely be the last 3.x release, as for the next release I’ll be focusing on refactoring for custom convention support, plus supporting the new .NET core runtime (and therefore support on Mac/Linux in addition to the 6 existing runtimes I support).

Happy mapping!

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

Mobile authentication with Xamarin.Auth and refresh tokens

Thu, 11/13/2014 - 15:46

An internal app I’ve been working with for a while needed to use OAuth2 (specifically, OpenID Connect) to perform authentication against our Google Apps for Your Domain (GAFYD) accounts. Standard OAuth 1.0/2.0 flows are made easy with the Xamarin.Auth component. Since OpenID Connect is built on top of OAuth 2.0, the Xamarin.Auth component could suffice.

A basic flow for using OAuth with Google APIs would look like this:


But for our purposes, we have a mobile application that connects to our APIs, but we simply want to piggyback on top of Google for authentication. So our flow looks more like:


This all works great straight out of the box, very nicely. One problem however – the token returned by the Google servers is only valid for a short period of time – 30 minutes or so. You *could* ignore this problem in the API we built, and not validate that part of the JWT. However, we don’t want to do that. Because we’re now going over the interwebs with our API calls, and potentially over insecure networks like coffee shop wi-fi, we want a solid verification of the JWT token:

  • The token’s hash matches
  • The issuer is valid (Google)
  • The allowed audience is correct – we only accept client IDs from our app
  • The certificate is signed against Google’s public OAuth certificates
  • The token has not expired

This becomes a bit of a problem – the token expires very soon, and it’s annoying to log in every time you use the app. The Xamarin.Auth component supports storing the token on the device, so that you can authenticate easily across app restarts. However, out-of-the-box, Xamarin.Auth doesn’t support the concept of refresh tokens:


Since the refresh token is stored on the device, we just need to ask Google for another refresh token once the current token has expired. To get Xamarin.Auth to request a refresh token, we need to do a couple of things: first, override the GetInitialUrlAsync method to request a refresh token as part of getting an auth token:

public override Task<Uri> GetInitialUrlAsync ()
	string uriString = string.Format (
		Uri.EscapeDataString (this.ClientId),
		Uri.EscapeDataString (this.RedirectUrl.AbsoluteUri),
		this.AccessTokenUrl == null ? "token" : "code",
		Uri.EscapeDataString (this.Scope),
		Uri.EscapeDataString (this.RequestState)

	var url = new Uri (uriString);
	return Task.FromResult (url);

The format of the URL is from Google’s documentation, plus looking at the behavior of the existing Xamarin.Auth component. Next, we create a method to request our refresh token if we need one:

public virtual Task<int> RequestRefreshTokenAsync(string refreshToken)
    var queryValues = new Dictionary<string, string>
        {"refresh_token", refreshToken},
        {"client_id", this.ClientId},
        {"grant_type", "refresh_token"}

	if (!string.IsNullOrEmpty(this.ClientSecret))
		queryValues["client_secret"] = this.ClientSecret;

	return this.RequestAccessTokenAsync(queryValues).ContinueWith(result =>
	    var accountProperties = result.Result;


        return int.Parse(accountProperties["expires_in"]);

I have a pull request open to include this method out-of-the-box, but until then, we’ll just need to code it ourselves. Finally, we just need to call our refresh token as need be before making an API call:

var account = AccountStore.Create().FindAccountsForService("MyService").FirstOrDefault();

if (account != null) {
    var token = account.Properties["refresh_token"];
    var expiresIn = await authenticator.RequestRefreshTokenAsync(token);
    UserPreferences["tokenExpiration"] = DateTime.Now.AddSeconds(expiresIn);

In practice, we’d likely wrap up this behavior around every call to our backend API, checking the expiration date of the token and refreshing as needed. In our app, we just a simple decorator pattern around an API gateway interface, so that refreshing our token was as seamless as possible to the end user.

In your apps, the URL will likely be different in format, but the basic format is the same. With persistent refresh tokens, users of our mobile application log in only once, and the token refreshes as needed. Very easy with Xamarin and the Xamarin.Auth component!

Some minor complaints with the component, however. First, it’s not a Xamarin.Forms component, so all the code around managing accounts and displaying the UI had to be in our platform-specific projects. Second, there’s no support for Windows Phone, even though there are issues and pull requests to fill in the behavior. Otherwise, it’s a great component that makes it simple to add robust authentication through your own OAuth provider or piggybacking on a 3rd party provider.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

Dealing with the linker in Xamarin apps

Tue, 11/11/2014 - 18:51

The last few months I’ve been working quite a bit with Xamarin and in particular Xamarin.Forms. I’ve got a series of posts upcoming on my exploits with that and migrating to ReactiveUI, but first things first, I actually need to deploy my app.

I’ve got my app working in debug/release mode in the simulator, and debug mode on a device. However, when I ran the app in release mode on a device, it just crashed without warning. Not a very good experience. I’ve deployed this app several times on the device, but something was causing this crash.

Typically a crash on a deployment is one of two things:

  • Something off in DEBUG conditional code/config
  • Something off in DEBUG/RELEASE project config

I checked the DEBUG conditional code config, which does things like point to the test/production API endpoints. That looked OK, so what else was different?

Screen Shot 2014-11-11 at 9.20.41 AM

That was my debug version of the app, where no assemblies were linked. In the Release mode, only SDK assemblies were linked. For many cases, this works, as the compiler can figure out exactly what methods/fields etc. are being referenced.

Normally, this is OK, until you get a series of telling exceptions, usually a MissingMethodException. In my case, I switched my Debug settings to the same as Release, and got:

System.MissingMethodException: Default constructor not found for type System.ComponentModel.ReferenceConverter
  at System.Activator.CreateInstance (System.Type type, Boolean nonPublic) [0x00094] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System/Activator.cs:326
  at System.Activator.CreateInstance (System.Type type) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System/Activator.cs:222
  at System.ComponentModel.TypeDescriptor.GetConverter (System.Type type) [0x0009f] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/
  at ReactiveUI.ComponentModelTypeConverter.<typeConverterCache>m__0 (System.Tuple`2 types, System.Object _) [0x0002d] in /Users/paul/code/reactiveui/ReactiveUI/ReactiveUI/Platform/ComponentModelTypeConverter.cs:24
  at Splat.MemoizingMRUCache`2[System.Tuple`2[System.Type,System.Type],System.ComponentModel.TypeConverter].Get (System.Tuple`2 key, System.Object context) [0x00000] in <filename unknown>:0
  at Splat.MemoizingMRUCache`2[System.Tuple`2[System.Type,System.Type],System.ComponentModel.TypeConverter].Get (System.Tuple`2 key) [0x00000] in <filename unknown>:0
  at ReactiveUI.ComponentModelTypeConverter.GetAffinityForObjects (System.Type fromType, System.Type toType) [0x00000] in /Users/paul/code/reactiveui/ReactiveUI/ReactiveUI/Platform/ComponentModelTypeConverter.cs:30
  at ReactiveUI.PropertyBinderImplementation+<typeConverterCache>c__AnonStorey5.<>m__0 (System.Tuple`2 acc, IBindingTypeConverter x) [0x00000] in /Users/paul/code/reactiveui/ReactiveUI/ReactiveUI/PropertyBinding.cs:1006
  at System.Linq.Enumerable.Aggregate[IBindingTypeConverter,Tuple`2] (IEnumerable`1 source, System.Tuple`2 seed, System.Func`3 func) [0x00000] in <filename unknown>:0

First lesson: keep linker settings the same between build configurations. When you encounter this sort of issue, the problem is usually the same – reflection/dynamic loading of assemblies means the linker can’t see that you’re going to access some type or member until runtime. The fix is relatively simple – force a reference to the types/members in question.

In my iOS project, I have a file called “LinkerPleaseInclude.cs”, and in it, I include all types/members referenced:

public class LinkerPleaseInclude
    public void Include()
        var x = new System.ComponentModel.ReferenceConverter (typeof(void));

Completely silly, but this reference allowed my app to run with the linker in play. More info on the linker can be found on the Xamarin documentation.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

Azure Mobile Services with AutoMapper

Wed, 10/29/2014 - 15:23

At the recent Xamarin Evolve conference, Paul Batum gave a great talk on Azure Mobile Service in cross-platform business apps, part of which included a piece on how AutoMapper fits in with their overall system:

There were sooooo many of those C# shirts at the conference, I felt a little left out without one.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

Comparing processing times of NServiceBus saga patterns

Tue, 10/28/2014 - 19:16

A few weeks ago I gave a talk at NSBCon NYC on scaling NServiceBus, and one of the pieces I highlighted were various saga/processing patterns and how they can affect performance. It was difficult to give real numbers as part of the discussion, mostly because how long it takes to do something is highly variable in the work being done and environmental constraints.

I compared three styles of performing a set of distributed work:

And highlighted the performance differences between them all. Andreas from the Particular team mentioned that some work had been done to improve saga performance, so I wanted to revisit my assumptions to see if the performance numbers still hold.

I wanted to look at a lot of messages – say, 10K, and measure two things:

  • How long it took for an individual item to complete
  • How long it took for the entire set of work to complete

Based on this, I built a prototype that consisted of a process of 4 distinct steps, and each variation of process control to track/control/observe progress. You can find the entire set of code on my GitHub.

Here’s what I found:

Process Total Time Average Median Observer 6:28 0.1 sec <0.1 sec Controller 6:25 3:25 3:37 Routing Slip 2:57 2.6 sec <0.1 sec

Both the observer and controller styles took roughly the same total amount of time. This is mostly because they have to process the same total amount of messages. The observer took slightly longer in my tests, because the observer is more likely to get exceptions for trying to start the same saga twice. But once an item began in the observer, it finished very quickly.

On the controller side, because all messages get funneled to the same queue, adding more messages meant that each individual item of work would have to wait for all previous items to complete.

Finally, the routing slip took less than half the time, with higher total average but comparable median to the observer. On the routing slip side, what I found was that the process sped up over time as the individual steps “caught up” with the rate of incoming messages to start the process.

This was all on a single laptop, so no network hops needed to be made. In practice, we found that each additional network hop from a new message or a DB call for the saga entity added latency to the overall process. By eliminating network hops and optimizing the total flow, we’ve seen in production total processing times decrease by an order of magnitude based on the deployment topology.

This may not matter for small numbers of messages, but for many of my systems, we’ll have 100s of thousands to millions of messages dropped on our lap, all at once, every day. When you have this situation, more efficient processing patterns can alleviate pressure in completing the work to be processed.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs