Nathan Cooper Software Engineer Expert in C# and .NET
28 JUL 2019

Your software should build, test and push artifacts on YOUR machine

How to avoid getting tricked by tutorials and get your Continuous Integration code right the first time

Your software should build, test and push artifacts on YOUR machine feature image
Read more...
25 JUN 2019

The query strings in my asp.net core project used to be terrible. Adding this library changed everything

If you use asp.net core, and are interested in writing shorter, clearer arrays in your query strings, or you're interested in configuring alternative names for your parameters: Read this.

The query strings in my asp.net core project used to be terrible. Adding this library changed everything feature image
Read more...
4 APR 2019

How I learnt to create reproducible C++ build environments with Docker

I quick overview of a really interesting series of Microsoft blog posts, and the application I built following them

How I learnt to create reproducible C++ build environments with Docker feature image
Read more...
4 JAN 2019

The Power of Positive Thinking

'Don't bring me problems, bring me solutions'... On the surface this sounds great, empowering even, but, as we'll see, this isn't a great idea.

The Power of Positive Thinking feature image Photo Credit: Amanda Jones
Read more...
22 DEC 2018

How much like the Titanic is your microservice architecture?

How your shiney new microservice architecture might actually be destroying your availability

How much like the Titanic is your microservice architecture? feature image
Read more...
21 DEC 2018

Should you code in your spare time?

Is the only way to become a 'great programmer' to spend a lot of your spare time coding? Is that even the best way?

Read more...
23 OCT 2017

How to use Octopus substitute variables In JavaScript files

Octopus package steps have a feature that allows you to replace Octopus Variables in any file.

Great, but I use that in JavaScript it needs to work locally before any octopus magic happens. So I use this:

var baseUrl = octoTemplate("#{portalUri}", "http://localhost:4200/");

....

function octoTemplate(value, fallback) {
    if (value.substr(0, 2) === "#{") {
        return fallback;
    }

    return value;
}

Read more...
26 SEP 2017

Validating Min and Max in your Angular form

So the min and max constraints on number field in your template based form aren’t working? Users can type in out of range values and the form is still valid. What’s happening?

Let’s say you’ve got a form, named myform, with this input:

<input type="number" [(ngModel)]="model.count" name="count" #count="ngModel" required min="0">

With Angular’s FormsModule, you get the validation on the required attribute basically for free. With no further code, if the user doesn’t fill in this input then count.hasError('required') is true and myform.valid is false. It’s the same with other attributes like pattern, maxLength etc.

However, you don’t get this with min or max.

This actually depends on your version of Angular. Angular 4 briefly had it, but it was removed in version 4.2.3). Apparently was a breaking change for some, but not for me, so let’s get it back.

The angular/forms package still has all the validation code we need, all we have to do is create our own directive. Here it is:

import { Directive, Input, forwardRef } from "@angular/core";
import {
	Validator, AbstractControl, NG_VALIDATORS, Validators, ValidatorFn
	} from "@angular/forms";

@Directive({
    selector: "[min][formControlName],[min][formControl],[min][ngModel]",
    providers: [
        { provide: NG_VALIDATORS,
			useExisting: forwardRef(() => MinDirective),
			multi: true }
    ]
})
export class MinDirective implements Validator {
    private _validator: ValidatorFn;
    @Input() public set min(value: string) {
        this._validator = Validators.min(parseInt(value, 10));
    }

    public validate(control: AbstractControl): { [key: string]: any } {
        return this._validator(control);
    }
}

Create another one for max, add it into the declarations in your module, and you’re all set.

Read more...
21 SEP 2017

If you're making iframe content for another website, here's how to do it better

Iframes are not usually the posterboy of a quality web experience. But they are useful, and part of my dayjob used to be making a site that could be iframed into other organisation’s websites.

A lot of getting iframes right is to do with good design, communication, documentation etc. But let’s talk about two things you can do in your code right now to improve any iframed application you might be distributing.

Support resizing through the iframe

Go and use David J. Bradshaw’s iframe-resizer code. This is a fantastic bit of code, and the readme is easy to follow.

Be sure to turn the scroll bar off. A scrolling box within another page doesn’t look or feel good. Taking the scroll bar away also encourages the host page builder to give your site the space it needs to breath.

Make embedding your site easy

Make it extremely difficult to screw up and make the default behaviour good. This is what it takes to embed the content I work on:

<section id="nathan_thing">
        <noscript>Please enable JavaScript to view nathan's stuff</noscript>
</section>
<script>
    function nathan_config() {
        this.subroute = "YOUR_SUBROUTE";
    };
</script>
<script src="https://wheremyembedscriptis.com/assets/embed.min.js"></script>

There’s very little here to get wrong. The person copying this code doesn’t even have to know what an iframe is, they don’t even have to know where my site is hosted, and I can change it at any time.

That’s because my embed script looks like this:

/**
 * Embeds the iframe into <section id="nathan_thing"></section>
 */
(function () {
    var config = new window.nathan_config();
    var baseUrl = "https://whenmysiteis.com/";

    var html = '<iframe id="nathans-id"' +
        ' src="' + baseUrl + config.subroute + '/someroute"' +
        ' width=100% allowtransparency="true" frameborder="0"' +
        ' tabindex="0" title="Nathans-thing"' +
        '></iframe>' +
        '<meta http-equiv="X-UA-Compatible" content="IE=edge">' +
        '<!--[if lte IE 8]>' +
        '<![endif]-->';

    document.getElementById("nathan_thing").innerHTML = html;

})();

Simple and easy. I removed a bunch of extra good stuff from this code for example purposes, so just in case you want the full thing here it as a .txt file.

Read more...
24 FEB 2017

Serving 3rd Party Images as Secure Content

I’ve built a site that’s served over https, calling ASP.NET WebApi also over https, but contains images that are on plain old http. I trust these image locations, and just want to proxy them. This is kind of a wierd thing to want to do, but if this ever happens to you, here’s how to do it:

Step 1: create a controller for the browser img tags to call

[HttpGet]
[AllowAnonymous]
[CacheOutput(ServerTimeSpan = 3600, ClientTimeSpan = 3600)]
[Route(template: "BarSection/FooImage/{fooId}", Name = "FooImage")]
public async Task<HttpResponseMessage> FooImage(int fooId)
{
  var foo = await GetFooAsync(fooId);
  if (string.IsNullOrWhiteSpace(foo?.ImageUrl))
  {
    throw new HttpResponseException(HttpStatusCode.NotFound);
  }

  using (var client = new HttpClient())
  {
    var res = await client.GetAsync(paymentMethod.ImageUrl);
		
    var response = Request.CreateResponse(HttpStatusCode.OK);
		
	response.Content = new StreamContent(await res.Content.ReadAsStreamAsync());
	response.Content.Headers.ContentType = res.Content.Headers.ContentType;

	return response;
  }
}

Step 2: replace the urls in your models before providing them to the browser

private string ProxyFooImageUrl(string externalUrl, int fooId)
{
  if (string.IsNullOrWhiteSpace(url))
  {
	return url;
  }

  var imageRoute = this.Url.Route("FooImage",
	new
	{
	  fooId = fooId,
	});

  // Force https, because even though the site is https the load balancer may be talking to this app via http
  var uri = new UriBuilder(new Uri(Request.RequestUri, imageRoute))
  {
  	Port = -1,
	Scheme = Uri.UriSchemeHttps
  }.Uri;

  return uri.AbsoluteUri;
}

Step 3: Profit

Note that it isn’t a very good idea to serve arbitrary links from your server, so don’t alter FooImage to directly accept links from the caller.

I happen to be using WebAPI, but I’ve added some MVC style caching using Strathweb.CacheOutput

Read more...
11 JUL 2016

Build your own event logging

Let's make our logging structured

Read more...
8 JUL 2016

Progressive Enhancement Example

I want to improve my website's experience for users with JavaScript, whilst keeping solid non-JavaScript functionality. Remember when you couldn't count on Javascript being there? No, me neither. But not every device is a laptop or modern mobile phone, so let's check this out

Read more...
8 JUL 2016

How to easily pass your domain errors into your model state

Let’s say I’m writing a web app to add People to a GuestList. The GuestList is a sensible place to keep the logic to decide whether a person is added and the reason why. For example:


public class BobHatingGuestList : IGuestList
{

...

public IEnumerable<ValidationResult>(Person person)
{

    var errors = new List<ValidationResult>();

    if (person.Name.Equals("bob", StringComparison.InvariantCultureIgnoreCase));
    {
        errors.Add(new ValidationResult("I really hate all bobs", new[] { "person" }));
        return errors;
    }

    if (_guestCount >= _maxGuestCount)
    {
        errors.Add(new ValidationResult("The list is full", new[] { "person" }));
        return errors;
    }

	return errors; 
}

}

We can just add this to the ModelState:


[HttpPost]
public ActionResult AddPerson(id personId, id guestListId){

	...
	
	ModelState.AddErrors(_guestList.CanAddPerson(person));
	
	if (this.ModelState.IsValid)
	{
	    _guestList.Add(person);
	    return RedirectToAction("Index");
	}
	
	...

	return View(model);
}

Using this extension method


public static class ModelStateDictionaryExtensions
{
    public static void AddErrors(this ModelStateDictionary modelStateDictionary,
        IEnumerable<ValidationResult> validationResults)
    {
        if (validationResults == null)
            return;

        foreach (var validationResult in validationResults)
        {
            if (validationResult.MemberNames.Any())
            {
                foreach (var member in validationResult.MemberNames)
                {
                    modelStateDictionary.AddModelError(member, validationResult.ErrorMessage);
                }
            }
            else
                modelStateDictionary.AddModelError(String.Empty, validationResult.ErrorMessage);
        }
    }
}

Read more...
8 JUL 2016

How to use properly encapsulated collections In Entity Framework

This is the pattern I use when writing classes with Collections in Entity Framework 6 (EF). Specifically, when these EF entities need to be proper domain objects with proper encapsulation, rather than just lightweight data objects.

The reason proper encasulation is tricky, is that the collections you expose have to be powerful. They need to expose the ability to add and remove items, because EF needs to be able to do that That’s great for EF, but it might just break the encapsulation of your class. Here is the pattern I use to expose the correct collection interface to consumers of my class, while accommodating Entity Framework.

I used a backing collection with just the level of access EF needs:


protected internal virtual ICollection<MyEntity> MyEntitysCollection { get; set; }

I expose that collection as something less powerful. As an IEnumerable or a IReadonlyCollection, for example. Or maybe I don’t expose it at all. I follow my class design instincts without caring about EF.


public IEnumerable<MyEntity> MyEntities
{
	get
	{
		return MyEntityCollection;
	}
}

Here’s the magic bit. When creating the entity type configuration I’ll need access the actual collection. But instead of ruining our encapsulation by making it public, I can do this instead:


public static Expression<Func<MyClassThisIsIn, ICollection<MyEntity>>> MyEntityMapping =
	f => f.MyEntityCollection;

Which enables me configure EF like this:

	
// Example
HasMany(MyClassThisIsIn.MyEntityMapping)
            .WithRequired()
            .HasForeignKey(e => e.MyClassThisIsIn_Id);

Done. Now I have a class with a collection that has the correct encapsulation, but also works as an Entity Framework entity.

Read more...
8 JUL 2016

Deleting Entity Framework Orphans and Domain Events in Entity Framework 6

One of the ‘missing features’ of Entity Framework 6 is properly dealing with the removal of entities from collections. A naive listOfEntities.Remove() won’t actually delete the entity. Instead it will remove the relation between the entity and the collection. This might burn you in a very obvious way if you have constrained the foreign key of the child element to not be null.

This also means that cascade deletes you may have set up won’t work. Although there are more reasons they might not work anyway. Jimmy Bogard provides a workaround for this on his site, lostechies.com: Missing EF Feature Workarounds: Cascade delete orphans.

This post fixing Entity Framework’s deletion problem using Domain Events, which you can also read about on lostechies.com.

I think this a good idea example of domain events, which are a useful tool for building applications. This isn’t actually my code, a ex-colleague of mine wrote pretty much all of this, but I thought it would be a useful thing to share here.

Domain Events

First things first, let’s create interfaces for the raising and handling of events:


public interface IDomainEventHandler<in T> where T : IDomainEvent
{
    void Handle(T domainEvent);
}

public interface IDomainEvent
{
}

And a class to orchestrate our domain event handling. This class keeps track of the IDomainEventHandlers and routes the IDomainEvents to them based on type.


public static class DomainEvents
{
    private static readonly Logger Log = LogManager.GetCurrentClassLogger();

    [ThreadStatic] //so that each thread has its own callbacks
    private static Lazy<List<Delegate>> domainEventHandlers;

    static DomainEvents()
    {
        domainEventHandlers = new Lazy<List<Delegate>>();
    }

    // Registers a callback for the given domain event
    public static void Register<T>(Action<T> callback) where T : IDomainEvent
    {
        domainEventHandlers.Value.Add(callback);
    }

    // Clears callbacks passed to Register on the current thread
    public static void ClearCallbacks()
    {
        domainEventHandlers = new Lazy<List<Delegate>>();
    }

    // Raises the given domain event
    public static void Raise<T>(T domainEvent) where T : IDomainEvent
    {
        // Find any registered handlers in the IoC container via ServiceLocator
        if (ServiceLocator.IsLocationProviderSet)
        {
            Log.Trace("Domain event '{0}' raised", typeof (T).Name);

            foreach (var handler in ServiceLocator.Current.GetAllInstances<IDomainEventHandler<T>>())
            {
                Log.Trace("Handler '{0}' starting", handler.GetType().Name);

                handler.Handle(domainEvent);

                Log.Trace("Handler '{0}' finished", handler.GetType().Name);
            }

            Log.Trace("Domain event '{0}' handled", typeof (T).Name);
        }

        if (domainEventHandlers == null)
        {
            return;
        }

        Log.Trace("Domain event '{0}' raised", typeof (T).Name);

        foreach (var action in domainEventHandlers.Value.OfType<Action<T>>())
        {
            action(domainEvent);
        }

        Log.Trace("Domain event '{0}' handled", typeof (T).Name);
    }
}


Entity Framework Specifics

Now to create the specific code for the entity framework stuff. Entity being our base class for the thing we’d like to delete, although this could be object.


public class EntityDeleted : IDomainEvent
{
    public Type EntityType { get; private set; }
    public Entity DeletedEntity { get; private set; }

    public EntityDeleted(Entity deletedEntity)
    {
        EntityType = deletedEntity.GetType();
        DeletedEntity = deletedEntity;
    }
}

And here is the handler. Our datacontext is IBusinessDataContext, which inherits from DbDataContext.

The Handle(EntityDeleted domainEvent) is where we actually do the deletion. The IObjectContextAdapter is an Entity Framework-ism we use to get the underlying ObjectContext from the DataContext, exposing the DeleteObject method we need.


public class EntityDeleteHandler : IDomainEventHandler<EntityDeleted>
{
    private readonly IBusinessDataContext _context;
    private readonly IObjectContextAdapter _contextAdapter;

    public EntityDeleteHandler(IBusinessDataContext context)
    {
        _context = context;
        _contextAdapter = (IObjectContextAdapter)_context;
    }


    public void Handle(EntityDeleted domainEvent)
    {
        ObjectStateEntry state;
        if (_contextAdapter.ObjectContext.ObjectStateManager.TryGetObjectStateEntry(domainEvent.DeletedEntity, out state))
        {
            if (state.State != EntityState.Detached)
                _contextAdapter.ObjectContext.DeleteObject(domainEvent.DeletedEntity);
        }
    }
}

Here’s an example usage:


if (Products.Contains(product))
{
	// Remove from the collection
	//(which deletes the relationship rather than the entity)
    ProductsCollection.Remove(product);

	// Call the domain event,
	// allowing EntityDeleteHandler (if registered) to actually delete the object
    DomainEvents.Raise(new EntityDeleted(product));
}

NB:

These events are dispatched before commit, so if handler does something outside of the entity framework transition scope (like send an email), it will still happen if there’s a rollback. This isn’t a problem for my example usage, but either a more sophisticated event handling mechanism, or some kind of distributed transaction scope would be needed.

Read more...
4 MAY 2016

Use git locally even if you're stuck on a project using TFS

I gave a 15 minute talk about git-tfs and how it enables you to do that

Read more...
29 SEP 2015

Engineering Chaos

This is a indispensable piece of advice: “The best way to avoid failure is to fail constantly”

Engineering Chaos feature image Photo Credit: Netflix
Read more...