Blog

Throttling actions in .Net Core 2.1 using AttributeFilter

I have previously written about Throttling in the pre-core times, and this is sort of the update to that post – with a bit of fixes and tweaks.

Lets get to it;

A few changes:

In my last post I did things a bit differently, for instance; I used to throw a custom exception type and handle that as a response, I have learned that this is an anti-pattern and is strongly discouraged (at least by David Fowler).
Anyway now we return a class, which is basically just my old ApiException type, just without the inherited bits of Exception. – this is both cheaper and cleaner.
Also since we are using .NET Core, we are using IMemoryCache instead of HttpRuntime.Cache – which is also nice.

services.AddMemoryCache();

On to the attribute:

There isn’t a lot to it to be honest.

  1. Check for existence of cache entry
  2. If none, create one and set allowExecute = true
  3. If allowExecute != true, return throttle response and short-circuit the pipeline.

Do note that this throttle uses IP as it’s target, but could easily be username or similar.

Usage:

[IPThrottling("GetItems", 300)]
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
    return new string[] { "value1", "value2" };
}

The above throttles for 300 seconds for the GetItems key, so you can group together functionality as well, if you really need to.

Ill talk about the custom response in a different blogpost

Developer and Power User Tools

Developer tools

  • Visual Studio Code
    Great editor, that (at least for me) has beaten sublime and the others. – built with electron as well!
  • Visual Studio
    I am a .NET Dev, so this is pretty essential for my daily use.
  • Notepad++
    I’ve switched mostly to use VSCode as my main editor, but for small things I like the speed of notepad++.
  • DockStation
    “Visual Docker” Dock station helps me quickly assemble large container applications with not much more than some drag and drop. Awesome!
  • HashCheck
    A simple right-click menu tool for getting the hash of any file.
  • Advanced Installer – Paid
    For any project I do where I need an installer, I use advanced installer… it’s simply an amazingly easy to use tool for all installation needs. (even does installer from *.sln file.)
  • GitKraken
    The best git gui out there.

Visual Studio Extensions

Ive made this a category by itself as there are many really good extensions.

Power User Tools

  • Fiddler
    Webrequest sniffer.
  • Wireshark
    Package sniffer.
  • Postman
    Best Rest Client.
  • ConEmu
    Guake style powershell prompt – whats not to like?
  • Everything search
    Great indexing and searching engine with a hotkey.
  • 1Password – Paid
    Everyone should be using a password manager these days, I use 1Password.
  • LightShot
    Awesome screenshot taking app.
  • Snagit – Paid
    Another amazing screenshot tool.
  • Evernote
    Notetaking for pro’s. nothing to more to say.
  • OneNote
    Another great notetaking app.

Chrome Addons

  • YSlow
    A website “slowness” tester for chrome.
  • Toby
    A much better (shareable) start page for chrome.
  • Awesome Screenshot
    Full page screenshots.
  • ColorZilla
    A Colorpicker.

Websites

  • Codepen.io
    Some fiddle, some bin, some plunk.. I pen.
  • Foundation for email
    Need html emails, but have html and separate css? – no problem.
  • APIMatic
    Transform any api spec into any other api spec.
  • Can I Use
    Lookup any html/css feature and see if its supported by browser xyz.
  • GuidGenerator
    A great looking, simple to use, Guid (v4) Generator.
  • Cron expression editor
    I keep forgetting how to Cron.. never again!
  • Http Status Codes api
    Awesome api to test statuscode handling – just request http://httpstat.us/418 or any other (Supported) status code.
  • Simple Online Rest Api
    When you just need to prototype – Request one of the endpoints and itll return what you sent (basically).

async await “explained” by examples

What does async and await really do?

Using the await keyword is basically just waiting for whatever function that comes after that keyword to create a thread, do work and return to the calling thread once it is done.
Everything that comes after is a “continuation”
The following 2 functions do pretty much the same thing

The above should also indicate something else, namely continuation.
In the first method everything after the “Task” calls would probably run before the tasks would finish.
In the latter, everything after the await call IS the continuation.
So doing something like the following;


Would result in the function taking around 6 seconds to do its “work”, since everything is a continuation of the former.
– this is probably not what you would want.
Instead you can do something like this;

Which would take around 2 seconds.

Exceptions:

Using async and await there is something to note in regards to exceptions:
I found this in an MSDN article and I think it explains it pretty well.

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. Exceptions thrown from async void methods can’t be caught naturally.

 https://msdn.microsoft.com/en-us/magazine/jj991977.aspx


The following code should explain:

So never ever use async void – it will take days to figure out what is actually going on.
If you have any questions please comment below and I will try to update the article with an answer 🙂

Injecting ClaimsPrincipal into Service / Business logic – layers (.NET Core)

So… You want to add authorization or atleast being able to figure out the username in the business logic layer.
What i’ve previously done is inject the username from the ui layer into the service-layer through input params on all methods (bad).
To inject the claimsprincipal in .NET Core we utilize the builtin IOC capabilities and simply
services.AddTransient(s => s.GetService().HttpContext.User); in Startup.cs
with the above we can simply just state (in the constructor) that our service / class / what ever needs a ClaimsPrincipal

Note: This requires the user is authenticated AND that you are using Claims (obviously).

Building on this, we could do something like the following;
Create a new service interface something like ICurrentUserProvider, with a method like public YourUserModel GetCurrentUser().

Implement the provider, injecting ClaimsPrincipal, your DbContext and maybe a caching service.

The convert the ClaimsPrincipal to your YourUserModel save it to the cache and return it.

Easy, simple HttpRuntime.Cache

A simple to use caching function that both gets and/or sets the key depending on results.

This is a post for my future self. – Hi future self! (wave).
The following is an easy to use caching function.

The function gets or updates based on results.
The wrapper helps create different cacheExpirations based on needs.
Usage:

Outlook/Gmail removes line breaks

I had a run in, with the particular feature of outlook, developing an application that sent plain-text emails.
I had code very similar to the following

which would result in the following plain-text
Hello,\r\n
Please update the following:\r\n
\r\n
Item1\r\n
Item2\r\n
Item3\r\n

But outlook would show me the following
Hello,\r\n
Please update the following:\r\n
Item1Item2Item3

Most solutions to this include creating the email as HTML instead.
This is fortunately NOT needed.
Outlook uses certain rules to determine something called “Continuation”.
* Every message starts with continuation off.
* Lines less than 40 characters long do not trigger continuation, but if continuation is on, they will have their line breaks removed.
* Lines 40 characters or longer turn continuation on. It remains on until an event occurs to turn it off.
* Lines that end with a period, question mark, exclamation point or colon turn continuation off. (Outlook assumes it’s the end of a sentence?)
* Lines that turn continuation off will start with a line break, but will turn continuation back on if they are longer than 40 characters.
* Lines that start or end with a tab turn continuation off.
* Lines that start with 2 or more spaces turn continuation off.
* Lines that end with 3 or more spaces turn continuation off.

Credits:

mtruesdell and his SO answer here

Versioning WebApi and documenting version with Swagger

Versioning in WebApi

Note: This post draws alot of points from https://www.troyhunt.com/your-api-versioning-is-wrong-which-is/ – but is more about implementation and documentation through swagger.
So please go read Troy’s post and then come back :).
There are a couple of ways of versioning a restful api
among them are:
1. Url versioning e.g. GET http://example.com/api/v1/cars
2. Request-Header e.g. GET http://example.com/api/cars — Header: api-version: 1
There are pros and cons in both regards, Troy gets around them quite nicely.
Time to code!

Url Versioning

Easy – simply use either the RoutePrefix- or RouteAttribute

Read more about the Routing-Attribute here

Request-Header

Drawing from Troy’s post
We create a new attribute which uses a custom routing constraint

** Usage **

Effectively matching routes based on the “api-version” header.

Swagger

When using swashbuckle (swagger implementation for .Net).
It knows about the default Route- and RoutePrefixAttribute, so Url Versioning is taken care of, out of the box.
But Header versioning is not.
Fortunately, it’s quite easy to implement an OperationFilter that adds the header as a parameter to the endpoints in question.
This implementation uses a list of versions and the endpoints relativepaths to know when to add the parameter and when not to.


How would you implement the OperationFilter?

The ServiceActionResult Pattern. Part Two

Continuing from my previous post The ServiceActionResult Pattern
This could also be implemented in a Generic Repository Pattern. If you have read, any post about a using a generic repository, it usually looks something like this:

The interesting part is the Update/Delete/Insert methods.
Yes… you could return a boolean saying whether or not the transaction was successful.
But we could also use the ServiceActionResult “Pattern”, to make it look something like this;

Which gives us that nice granular return state AND the actual entity in question (which is nice for RESTful services)

The ServiceActionResult pattern

This is not a GOF pattern or anything, but it’s very nice and brings alot to the table.
Basically what I do is this;
Whenever I have some sort of Service/Repository or something similar. Basically any façade where I delegate to CRUD or do CRUD, I return a ServiceActionResult.
The ServiceActionResult class looks like the following:

It’s just a basic generic class that holds a class (T) and an Enum.
The Enum could look something like this, but could be anything you’d like.

It’s kinda like REST.
Return the entity and an HTTP Status code, but instead of a statuscode, we return a ServiceActionStatus
Below you’ll see basic usage:

Using the above. The caller of the CarService just needs to Switch on the ServiceActionStatus and can easily handle, lots of different types of responses.