Ali Kheyrollahi: Performance Counters for your HttpClient

Level [T2]

Pure HTTP APIs (aka REST APIs) are very popular at the moment. If you are building/maintaining one, you have probably learnt (perhaps the hard way) that having a monitoring on your API is one of your top cross-cutting concerns. This monitoring involves different aspects of the API, one of which is the performance.

There has been many approaches to solving cross-cutting concerns on APIs. Proxying has been a popular one and there has been proliferation of proxy type services such as Mashery or Apigee which basically sit in front of your API and provide an abstraction which can solve your security and access control, monetizing or performance monitoring.

This is a popular approach but comes with its headaches. One of these problems is that if you already have a security mechanism in place, it can clash with the one provided by the service. Also the geographic distribution of these services, although are getting better, is not as good as the one provided by many cloud vendors. This can mean that your traffic could be bouncing across the Atlantic ocean a couple of times before getting to your end users - and this is bad, really really bad. On the other hand, these will not tell you what is happening inside your application which you have to solve differently using classic monitoring approaches. So in a sense, I would say you might as well just byte! the bullet and just implement it yourself.

PerfIt was a library I built a couple of years ago to provide performance counters for ASP.NET Web API. Creating and managing performance counters for windows is not a rocket science but is clumsy and once you do it over and over and for every service, this is just a bit too much overhead. So this was designed to make it really simple for you... well, actually for myself :) I have been using PerfIt over the last two years - in production - and it serves the purpose.

Now, it is all well and good to know what is the performance characteristics of your API. But this gets really more complicated when you have taken a dependency on other APIs and degradation of your API is the result of performance issues in your dependent APIs.




This is really a blame game: considering the fact that each MicroServie is managed by a single team and in an ideal DevOps world, the developers must support their services and you would love to blame another team rather than yourself especially if this is truly the direct result of performance degradation in a dependent service.

One solution is have access to performance metrics of the dependent APIs but really this might not be possible and kinda goes against the DevOps model of operations. On the other hand, what if this is due to an issue in an intermediary - such as a Proxy?

The real solution is to benchmark and monitor the calls you are making out of your API. And I have implemented a new DelegatingHandler to do that measurement for you!


PerfIt! for HttpClient

So HttpClient is the de-facto class for accessing HTTP APIs. If you are using something else then either you have a really really good reason to do so or you are just doing it wrong.

PerfIt for client provides 4 standard counters out of the box:

  • Total # of operations
  • Average time taken (in seconds)
  • Time taken for the last operation (in ms)
  • # of operations per second

These are the 4 counters that you would normally need. If you need another, just get in touch with me but remember these counters must be business-independent.

First step is to install PerfIt using NuGet:
PM> Install-Package PerfIt
And then you just need to install the counters for your application. This can be done by running this simple code (categoryName is the performance counter grouping):
PerfItRuntime.InstallStandardCounters("<categoryName>");
Or by using an installer class as explained on the GitHub page and then running InstallUtil.exe.

Now, just add PerfitClientDelegatingHandler to your HttpClient and make some requests against a couple of websites:
using System;
using System.Net.Http;
using PerfIt;
using RandomGen;

namespace PerfitClientTest
{
class Program
{
static void Main(string[] args)
{
var httpClient = new HttpClient(new PerfitClientDelegatingHandler("ClientTest")
{
InnerHandler = new HttpClientHandler()
});

var randomSites = Gen.Random.Items(new[]
{
"http://google.com",
"http://yahoo.com",
"http://github.com"
});
for (int i = 0; i < 100; i++)
{
var httpResponseMessage = httpClient.GetAsync(randomSites()).Result;
Console.Write("\r" + i);
}

}
}
}
And now you should be seeing this (we have chosen "ClientTest" for the category name):

So as you can see, instance names are the host names of the APIs and this should provide you with enough information for you to monitor your dependencies. Any deeper information than this and then you really need tracing rather than monitoring - which is a completely different thing...



So as you can see, it is extremely easy to set this up and run it. I might expose the part of the code that defines the instance name which will probably be coming in the next versions.

Please use the GitHub page to ask questions or provide feedbacks.



Dominick Baier: IdentityServer Beta 1-2

Yesterday we pushed another interim release of IdentityServer to nuget.  You can see all commits here if you are interested.

Besides many smaller changes and bug fixes – the main new feature is that you can now configure which claims go into identity and access tokens. This allows sending e.g. a ‘role’ claim to a resource.

Before that change, this always required extending the claims provider. Check the wiki for updated docs.

Internally, everything is based now on Katana and the JWT handler v4 – which allowed to finally fix the data types of claims like ‘iat’ or ‘auth_time’ to numbers (before that the JWT handler only allowed strings). This improvers interop with other OIDC systems. Katana v3 is also a pre-req for supporting WS-Federation and OIDC based upstream IdPs, which is a feature that we will soon start working on.

We also moved all active development to the dev branch and periodically publish dev nugets to myget. See here.

As always, and feedback is appreciated. Thanks for the support so far!


Filed under: .NET Security, ASP.NET, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Darrel Miller: Vermont Code Camp

This past weekend I had the opportunity to attend and speak at Vermont Code Camp.  Apart from being hosted at the beautiful University of Vermont, it was an event packed with excellent speakers.

I presented my talk on “Crafting Evolvable API Responses”, which itself managed to evolve considerably since doing it at New York Code camp the weekend before.  The slides are available here on slideshare:

It was also great to see such a great showing of women speakers.

vtcodecamp

If you get the chance next year to attend, this is one event that I would definitely recommend.


Glenn Block: Our new book and my personal journey toward REST and Hypermedia

It’s hard to believe, but it has been 6 months since our new book, “Designing Evolvable Web APIs with ASP.NET” shipped! So far the feedback that we’ve received has been really positive and we’re excited to see the momentum.

book

In the first part of the book we focus on educating about the fundamentals of the web architecture and HTTP, and APIs. Next we focus on the designing of a hypermedia API, and a TDD/BDD driven implementation of a CollectionJson API using ASP.NET Web API. We also give you several coding patterns that you can use to get started building hypermedia APIs.

In the second part of the book, we focus on ASP.NET Web API itself and the underlying architecture. We do this in the context of the first part, with the explicit goal of helping you further toward building out an evolvable API. We delve deeply into the nuts and bolts of Web API including hosting, routing and model binding. We cover comprehensively how to secure your API, and the security internals. And we cover other topics like TDD and using Inversion of Control.

You can buy it online now here. We also have a Github repo with all the code, which includes a working hypermedia API.

The people that made this book a reality.

This book has been a collaborative effort with four other amazing folks that I’ve had the privilege to work with. It combines the knowledge of the Web API team itself as well as key advisors who were with us every step of the way as we built it. It was a collaborative effort across 4 time zones and countries:

  • Howard Dierking, my co-conspirator on the Web API team. An amazing individual who is helping educate the world on REST and hypermedia through his Pluralsight work.
  • Darrel Miller, a long time proponent of REST and hypermedia in the .NET world before many of us at Microsoft had a clue of what that means. Darrel has been building real hypermedia systems for a long time. Darrel was one of our first handfuls of advisors on Web API.
  • Pedro Felix, an expert on Web API security and the ASP.NET Web API architecture. His comprehensive contribution in the book on the security aspects of Web API is unparalleled in the .NET world.
  • Pablo Cibraro, former CTO of Tellago and a consultant who has implemented many API solutions. Pablo is an expert in Agile and TDD, and he wrote some deep chapters testability and IOC.

We also had a fantastic set of reviewers and advisors.

Why write this book?

This book is part of a very personal journey, a  journey that started several years ago when I joined the WCF team at Microsoft. At that time I had the pop culture understanding of REST, that is a lightweight API exposed over HTTP that doesn’t use SOAP. I joined the team to help build a better experience in the platform for these types of APIs. Little did I know the journey that awaited me, as I would delve deeper and deeper into the REST community.

It was a journey of learning.  I was fortunate to have wonderful teachers who had already been treading the path, chief of which (ordered last name first) were: Jan Algermissen, Mike Amundsen Alan Dean, Mike Kelly, Sebastien Lambla, Darrel Miller, Henrik Nielsen, Ian Robinson, Aaron Skonnard, and Jim Webber. I am deeply indebted for their help. The is book was built really on the shoulders of these giants!

During that period, I learned about HTTP and REST, that REST is much more than building an RPC JSON API, and about how to make APIs more robust. This included learning about fundamental aspects of the web architecture like caching, ETAGS and content negotiation. The learning also included the hidden jewel of REST APIs, hypermedia, and new media types like HAL, CollectionJson and Siren that were designed specifically for hypermedia-based systems.

It was clear looking at our existing Microsoft frameworks that they did need meet the requirements for building APIs that really leveraged HTTP and took advantage of the web architecture. Looking within the .NET OSS community, solutions like Open Rasta, however were explicitly designed with this in mind. There were also a ton of other options outside the .NET world in Java, Ruby, Python and PHP, and more recently in node.js.

After soaking this all in, my team at Microsoft, and a team of fantastic advisors from the community, worked together to create a new framework that was designed from the get-go to fully embrace HTTP, to enable, but not force building a RESTful system.

As part of this we had an explicit goal from day one to ensure this framework would also enable building a fully hypermedia based system. Another explicit goal was to make the framework easier to test, and to allow it to work well with agile development. This framework ultimately became what you now know as ASP.NET Web API.

Although ASP.NET Web API had the foundations in place to enable such systems, you have work to do. I am not going to say that it naturally leads you to build a hypermedia system. This was not an accident. We deliberately did not want to force people down a specific path, we wanted to make sure though if you wanted to build such a system, it wouldn’t fight you.

We saw a lot of folks jump on this, even internally, folks like the Office Lync Team that built probably one of the largest pure hypermedia APIs in existence using Web API.  Many of these early adopters had the advantage of working directly with our team. They worked with me, and Henrik Nielsen (My Web API architect, and one of the creators of HTTP) to help guide them down the path. We did a lot of educating on HTTP, API fundamentals and what hypermedia is and how to build systems that support it.

On the outside we also saw a lot of energy. Folks like our advisory board jumped in and started doing the same in the wild. They built real systems, and they guided customers.

All of this work (including shipping Web API) definitely succeeded in help raising the bar around modern API development and hypermedia in the industry in general. More and more folks including some of the largest companies started coming out of the woodwork and saying, we want to build these types of systems.

However, many folks, in particular in the .NET community, have not crossed this chasm yet and do not understand how or why to build such systems. In particular building a hypermedia-based system is a sticking point. Many are scared by the term and don’t understand what it is. Others dismiss it as purely academic. Even those that do grasp the concepts often do not know where to start to implement them. This last point makes total sense, taking into consideration the points I mentioned earlier that ASP.NET Web API does not lead you toward building such APIs, it enables it.

With this book we wanted to change that. We wanted to bring these API techniques to the masses. We wanted to show you why and how to actually build these APIs with ASP.NET Web API. We wanted to show you how to make the underlying architecture of the framework to work with you in achieving that goal.

I believe we’ve done that. We look forward to your experiences with the book as you embark on API development with ASP.NET.


Darrel Miller: Implementing Conditional Request Handling for your API


In the previous post in this series on Conditional Requests I introduced the topic of validators, their purpose and how they can be constructed.  A large chunk of the work that needs to be done to support conditional requests is done by the origin server.  This blog post is about that role.

ForkInRoad

The first job of the origin server is to return a validator header along with responses for resources that want to support conditional requests.  The second function it performs is when it receives a conditional request it needs to decide if it is going to fulfill the request or fail.  A server can recognize a conditional request because there is a request header that starts with If-. Which if- header is used depends on the type of validator being using and the type of HTTP method being used.  The following if- headers are lists in the message headers repository:


  • If-Match
  • If-Modified-Since
  • If-None-Match
  • If-Range (rfc7233 – Range Requests)
  • If-Schedule-Tag-Match (rfc6638 - CALDAV)
  • If-Unmodified-Since

The If-Range and If-Schedule-Tag-Match are slightly different cases that we can save for discussion on a different day.

For reads…

For safe requests like GET the goal is to only return a response body if it has changed from what has previously been retrieved.  Therefore we use the If-none-match header with an Etag or the if-modified-since header with a Last-modified validator.  If these pre-conditions fail, then the 304 – Not modified header is returned.

Book

The if-none-match is named the way it is because a client can actually send multiple Etag values.  This can be used when a cache is holding multiple different variant representations and it only wants to receive an update if all of its variants are out-of-date. 

When comparing validators for the purpose of deciding to read or not, a “weak” comparison is used.  This means that both strong and weak validators are compared and are considered equal if the validator values are the same.

For writes…

For unsafe requests like PUT, POST, PATCH, DELETE, the conditional headers if-match and if-unmodified-since are used to abort the request if the  validators do not match. In this case the status code 412 – Precondition Failed should be returned.

Write

When comparing validators before writing,  a “strong” comparison is used.  This means that only strong validators can be used and must be equal before the request can be performed.

Bring a backup

Although a client only really needs one type of validator value to perform conditional requests, it is recommended that an origin server return both a Etag and a Last-modified header if possible.   I can only assume this is to provide support for web caches that only support HTTP/1.0.  ETags have been standardized since 1997.  It continues to amaze me how seriously the IETF folks take backward compatibility.

Clairvoyant?

The specification makes it clear that for each of the conditional request headers, the origin server must not perform the actual request behaviour if the pre-condition fails.  However, it goes on to say that

redirects and failures take precedence over the evaluation of preconditions in conditional requests

This infers that you needs to do just enough of the request processing to know that it will produce a success status code, before testing the the pre-condition and performing the request.  This has some significant implications on how you might be able to implement conditional request handling.  The specification says,

a recipient cache or origin server MUST evaluate received request preconditions after it has successfully performed its normal request checks and just before it would perform the action associated with the request method.

The part I find interesting about this last quote is the distinction between “request checks” and the “action associated with the request method”  It would be valuable to further explore this distinction and understand what checks need to be performed before pre-conditions can be evaluated.

Precedence

If you consider each of the individual elements of the entire conditional request handling process in isolation, each piece is fairly straightforward.  However, the HTTP specification puts no limitations on the ability to send multiple different conditional headers at the same time.  In order to produce sane results there specification lays out a set of rules as to the order in which these conditional headers should be evaluated.  I have simplified the rules a little by ignoring the possibility of If-Range headers, and the end result is the diagram below.

image

If you follow the flow chart through and reach the GO symbol, that means that the actual request can be performed.

Don’t fail if you don’t have to

One interesting area that I was not previously aware of until I created this diagram was the step that takes place after an Etag fails to match or the If-Unmodified-Since fails.  If some other request has already made the same change that the current conditional request is trying to make, then a server should not return a 412 failure, but simply return a 2XX status.

One last piece of the puzzle

In the first article on this subject we talked about the validator values that are required to make conditional requests.  This article covers the role of the server in conditional request handling.  The next article will discuss how the client can make conditional requests.

Image credit: Fork https://flic.kr/p/kUFSi7
Image credit: Book https://flic.kr/p/8JBSSW
Image credit: Writing https://flic.kr/p/5WtwEy


Filip Woj: Over 100 ASP.NET Web API samples

As you might now by now, last month my ASP.NET Web API 2 Recipes book was released by Apress. The book contains over 100 recipes covering various Web API scenarios that aim to help you save some headaches when working … Continue reading

The post Over 100 ASP.NET Web API samples appeared first on StrathWeb.


Darrel Miller: Code Camp NYC

This weekend I had the opportunity to speak for the first time at the New York city Code Camp.  It was an excellent event with a huge turnout and an equivalently huge number of sessions.

NewYork

With fourteen different sessions happening simultaneously, attendees were spoiled for choice and I am quite sure there were plenty of people having to make difficult choices.

Web Performance

I was happy to get the chance to see Nik Molnar’s talk on Full Web Stack Performance.  I got to learn about a number of handy HTTP related utilities that I had not seen before as well as get some great insight into how the web browsers are attempting to enable jank free user experiences.

There were a loads of other sessions that I would have loved to have seen, but unfortunately I was still preparing my own talks.

Hypermedia’s Secret SauceSecretSauce2

My first talk was a demonstration of how to build native client applications that use hypermedia to drive the application workflow.  The first demo was a slightly enhanced version of the sample that I show in my Hypermedia Client/Server Dance post.

The second demo was a more involved client application that had multiple screens and has an explicit ClientState class and specialized link classes to encapsulate the interaction behaviour of the client.  This client is very much a work in progress and will continue to evolve as I try and demonstrate more hypermedia capabilities.  You can find the source code for both the demos in my Github repository.  Be warned, if you are looking for something polished, you will be disappointed!

You can find the slides for the talk here on OneDrive.

Crafting Evolvable API Responses

My second talk was on designing representations for APIs that can evolve.  I spent some time explaining the disadvantages of using object serializers to build your wire representations and then went through a variety of different representation examples that attempt to address many of the common issues when doing API design.  The slides are available here, however the commentary on the representations is currently missing from the slides and we also did a number of examples based on questions from the audience.  If you happen to live near Burlington VT, I’ll be doing this talk again next Saturday at the Vermont Code Camp.

Vermont

Kudos

I’d like to thank Steve Bohlen and Erik Stepp and the huge team of volunteers for putting on this event.  It is great to see so much participation in the developer community.


Image credit : New York https://flic.kr/p/dauWoe
Image credit : Secret Sauce https://flic.kr/p/ag8CoD
Image credit: Vermont https://flic.kr/p/8BReje


Filip Woj: Things you didn’t know about action return types in ASP.NET Web API

When you are developing an ASP.NET Web API application, you can chose whether you want to return a POCO from your action, which can be any type that will then be serialized, an instance of HttpResponseMessage, or, since Web API … Continue reading

The post Things you didn’t know about action return types in ASP.NET Web API appeared first on StrathWeb.


Darrel Miller: HTTP in depth

Over the past few months I have written a number of posts relating to HTTP that have attempted to clarify some of the lesser understood areas of the HTTP specification and provide some practical guidance.

digbighole

Posts that are complete

Posts that are on my backlog

  • Conditional Request Handling
  • Making Conditional Requests
  • The connection header
  • Range based requests

Feedback

If there are posts in the backlog that you would like to see sooner, rather than later, feel free to ping me on twitter.  If there are other areas that think would be worth exploring in more detail, let me know.

Image credit: Digging a big hole https://flic.kr/p/8c6zD5


Darrel Miller: Using Etags and Last-modified headers to improve performance with HTTP conditional requests


In the recent update of the HTTP specification, the details of conditional requests have been split out and given their whole own specification.  Most developers I talk to are familiar with the idea of 304 Not Modified response code, but whenever we start to dig deeper everyone, myself included, are missing pieces of the puzzle. This article is one of a series of blog posts that attempts to dig in to aspects of HTTP and provide practical guidance on their usage.

WaxSeal

Conditional HTTP requests are used to perform an action, unless the target representation has changed, in which case they do something else.  There are two common ways that this mechanism is used:

  • we can prevent a client from having to download bytes that it already has.
  • we can prevent a client from making changes to a resource that has been changed by someone else since they retrieved it

Validators tell you when you should care about change

In order to make a conditional HTTP request, a special type of HTTP header called a validator needs to be sent in the response from the server.  The two validators defined by the HTTP specification are Etag and Last-modified.   Validators are values that allow you to compare if two resource representations are the same. The definition of "same" depends on the flavour of validator and the opinion of the origin server.

What flavour is your validator?

Validator values are considered either strong or weak.  Strong validators tell you if the response body is identical. Weak validators are used to allow an origin server to group multiple slightly different representations together as equivalent.

flavours

A strong validator can be used to identify as equivalent two different representations where the headers differ.  For example, supposing you requested the same resource as text/plain and then as text/html. If the server supported returning both of those media types, then both representations could have exactly the same body bytes and therefore returning a 304 Not modified would be feasible for the second request.  However, the origin server does have the option of changing the validator value if it believes the changed header is semantically significant.

Weak validators are used to deliver new content to a client when the representation has significantly changed, based on what the origin server deems significant.  This capability is interesting because it can enable a server to manage load on a server, by controlling how often it signals that a resource representation has changed.  This might be useful if clients are aggressively polling for changes to a representation.  The server can effectively lie to clients for a short period of time and return 304 in order to reduce the amount of bytes being delivered by the server.

Weak validators can also be used to identify equivalence between two representations that are functionally equivalent.  For example, a cache might contain a compressed copy of a representation and when it receives a conditional request for an uncompressed copy, it can identify that the client already has an up to date version of the representation even though the body bytes do not match.  This saves a cache from having to hold a cached copy of both the compressed and uncompressed version. 

Last Modified validator

The Last-modified header is simply a date and time using the HTTP date format. The value is considered to be the time when the representation was last changed.   The Last-modified validator is normally considered a weak validator because the HTTP date format only has the resolution of one second and it is often possible for multiple different representations to be retrieved within one second.  However, there are scenarios where a Last-modified header can be considered strong.

Making an Etag

There are no defined rules of how to manufacture an Etag value.  The guideline would be just to do whatever is the easiest thing that can identify a “version” of a resource representation.  Sometimes people will create a hash of the response body.  A timestamp value is another way of generating an Etag value.  If your internal entity maintains some kind of revision number, then that can be a very useful component of an Etag.  Sometimes internal entities are naturally immutable and have an internal identifier, in which case those identifiers can be used in an Etag.  It is important to remember that if there are multiple representations of the resource then the internal identifier needs to be combined with some kind of representation identifier to ensure the Etag is unique for each representation.

Making an Etag Header

An Etag header requires putting quotes around the Etag value.  There are also constraints on what characters can be an Etag value.  If you feel a burning desire to put unusual characters in your Etag value, you might want to check the spec first.  The recent update of the HTTP specification now removes the possibility of using escaped values in Etag values.

Below is a request from the Uber API with an Etag header.

UberAPIWithEtag

If you want to identify a value as a Weak Etag then you simply put W/ in front of the quoted Etag value.

Putting your validators into use

When I started this post, I had intended to make this a single post.  The more I read RFC 7232, the more I realized there is way more that needs to be said about handling conditional requests and making conditional requests, so I’m going to leave those discussions for follow-up posts.  In the meanwhile, if you are hungry for more HTTP insight, I’ve made an index of the HTTP related posts that I have done to-date.

Image credit: Wax seal https://flic.kr/p/7piVnt
Image credit: Flavors https://flic.kr/p/nm6sps


Darrel Miller: Caching resources with query strings

This afternoon Scott Hanselman posted a fairly innocuous question on twitter.  However, the question involved versioning of a RESTful API, which is a subject that is sure to bring out lots of opinions.  This post is less about the versioning question and more about the commonly held belief that caches do things differently with URLs that have query strings.

Query strings deserve more love

Putting a version number into a query string parameter is actually quite an interesting idea.  For one, it can be made optional, so that a consumer can choose to always consume the latest version, or request a specific version.  Secondly, I like it because I can selectively version just the resources that I want to.  The part I dislike about putting a version as the first segment of the URL is that it blindly versions every resource in the API whether there has been breaking changes or not.   Putting a version at the end of the URL is much better, but putting it in the path can be tricky for both client and server implementations.  Particularly if you are not using hypermedia.

Caching is king

The last reason I like the version number in the query string is that it makes the specific version a separately cacheable resource.

When I mentioned my opinion to Scott on twitter, @jeremymiller responded with,

This is not the first time that I’ve heard this guidance.  In the past when I investigated this, I discovered that a number of the HTTP caches provide configuration options that allow you avoid caching resource with query string parameters from particular domains.  I recall reading about reasons like corporate proxy caches getting filled up with tiles from google maps, pushing out all the content that get high hit rates with stuff that have very low hit rates.

As far as I understood, it was a configuration option that someone explicitly had to set to filter out certain sites. This didn’t seem like sufficient justification for the pervasiveness of the belief that query strings break caching.  So I decided to go hunting again.

A search for the source

My search kept bringing me back to a blog post by Steve Souders on how to update files that have been released with extremely long expiry times.  In this article Steve demonstrates when using a version number in the query string, the Squid proxy cache does not cache the static file at all.  He goes on to say that Squid can be configured to cache these files, but it is not the default behaviour.  Based on this information, he rightly suggested that people don’t use versions in their query string if they want to cache static resources.

squid

That was in August 2008.  Earlier that year, in May 2008, Squid released version 2.7 which changed their default behaviour to no longer refuse to cache URLs that contained a query string.  The Squid documentation explains the changes, and claims that one of the reasons for the change was because sites like YouTube were intentionally putting stuff in the query string to prevent caches from reducing traffic to their site.  I guess someone had investors they needed to impress Annoyed

We are six years down the road and the guidance based on a default setting in a HTTP cache is still with us, discouraging developers from using a significant architectural component of a resource identifier.

I don’t doubt that there are numerous other web frameworks and output caching mechanisms that apply similar constraints to resources with query strings.  However, these components should be under the developer’s control.  There is no need to artificially constraint ourselves to describing cacheable resources using only the path component of a URL.

Since RFC 3986 was released in 2005 the role of the query string has been well defined:

The query component contains non-hierarchical data that, along with data in the path component, serves to identify a resource within the scope of the URI's scheme and naming authority

Let us move forward and start treating query strings with the respect that they deserve.

Image Credit: Squid https://flic.kr/p/79fueL



Filip Woj: Strongly typed direct routing link generation in ASP.NET Web API with Drum

ASP.NET Web API provides an IUrlHelper interface and the corresponding UrlHelper class as a general, built-in mechanism you can use to generate links to your Web API routes. In fact, it’s similar in ASP.NET MVC, so this pattern has been … Continue reading

The post Strongly typed direct routing link generation in ASP.NET Web API with Drum appeared first on StrathWeb.


Darrel Miller: A drive by review of the Uber API

Uber recently announced the availability of a public API.  I decided to take it for a spin and provide some commentary.  The quick version is that it is a fairly standard HTTP API and that is both a good thing and a bad thing.

You can find the official documentation for the Uber API on their developer site.  In general the documentation is easy to read and it seems fairly comprehensive for what is, at the moment, a pretty simple API.  From what I can see, it is just a read-only API at the moment, but they do advertise that "more endpoints are coming".

uber

Versioning

The API reference document starts with this,

All API requests are made to https://api.uber.com/<version>, where version is currently v1

It is unfortunate that the Uber API developers have not spent more time at conferences like API Craft, RESTFest, APIDays, EndpointCon, where it is becoming increasingly common knowledge that putting a v1 at the front of your URI is not a best practice.  There many other more finely grained ways of doing versioning, when you really must introduce breaking changes.  Having a version number as a first path segment creates a huge cliff where potentially everything changes in v2 and can become a nightmare for client and server developers.

HTTP Status Codes

The documentation then lists the HTTP status codes.  I'm really not sure why the writers of the documentation feel the need to rewrite what is supposed to be standardized.  However, it is interesting that they chose to use 422 to distinguish between "invalid content" and a "malformed request".   It will be interesting to see how they make that distinction.

It does amuse me that they only include the 500 error in the 5XX range.  I'm pretty sure most clients are going to need to account for 502, 503 and 504 as well.  Enumerating out the response messages that a server supports is very misleading to client developers.  Clients need to be built to account for every HTTP status code because you never know what other status code returning intermediary is going to be sitting between you and the origin server.  There is no harm in defining actions based on ranges of status code values.  It's not as if every status code needs explicit handling code.

Error Messages

Once again, we have another API who has decided they need to re-invent the "error message" wheel.  There a number of efforts underway to create a standardized format, such as http-problem and vnd-error .  API providers should get behind one and not invent their own.

404

Rate Limiting

It is great that Uber has chosen to use the new 429 status code to indicate that rate limits have been exceeded and it is commendable that they have re-used the headers from the Twitter API for indicating the rate limit status.  However, it would have been nice if they could have dropped the X- as has been recommend in RFC 6648.

I'm not really sure why there is a need to return the rate limiting information on every request.  Why not provide a resource I can query when I want to know what the rate limit is.  Why send those extra bytes over the wire? 

Authentication

Reading the authentication section is almost a delight, because I almost don't need to read it.  For resources that a specific to a particular user, it is OAuth 2.  This is the way it is supposed to be with HTTP APIs.  By taking advantage of the uniform interface, all the infrastructure issues are just supposed to work the same way.  I don't need to learn anything new.  At least I shouldn't.  Unfortunately when testing the API we identified a number of nits related to the OAuth2 process.  I suspect they will be ironed out soon enough though.

For resources that are not specific to a user then you use a server_token which is supplied when you register your application.  Interestingly the documentation states that you MUST pass the token using an Authorization header using the authorization scheme Token.  This is awesome, just the way it should be done.  However, the reality is a bit different.  If you look at the tutorial example the server_token is passed as a query string parameter.  This is convenient but you may find your server_token littered throughout other peoples log files.  Both ways work, so just do the right thing!

Resources

The API documentation chooses to call these "Endpoints" in the heading but then uses the term Resource within the actual documentation page.  It's one of those things that doesn't matter once you already know what they mean, but it can be confusing for people who are new and trying understand which words are significant and which are not.

I am never very good at getting a grasp of APIs from looking through a list of URIs.  I much prefer a visual representation.  I'm used to building hypermedia APIs which are a bit easier to draw pictures of because they naturally have links between resources.  However, for non-hypermedia APIs like the Uber API I have found that a hierarchical diagram of the URI space by path segment can be a good visualization tool.

image

From what I understand from the documentation, this is how the URI space is defined.  The documentation does a decent job at explaining what each of these resources represent.

Media Typesreceipts

Unsurprisingly, the API simply returns application/json for all representations.  This means that it would be difficult for clients do anything other than use the request URI to identify the structure and semantics of the response.  Even sniffing the content to determine semantics is tricky because resources like /v1/me don't have a root object name.  Coupling representation structure to the request URI is common place within the HTTP API world, I just wish developers had a better understanding of the price that they are paying for taking this shortcut.

Caching

I am disappointed that we don't see any caching directives on the responses coming back from the API.  As all of the requests require an Authorization header it makes sense to choose not to make the responses publicly cacheable.  However, private caching would be perfectly viable for responses.  Especially for things like list of products.  Even more so considering the current performance of the API.  To retrieve the list of locations is currently taking around 350ms in my tests and once an HTTPS connection is established it drops down to around 150ms.  For a single request that isn't terrible, but I am doing this on a desktop with a decent broadband connection.

One mitigating factor is that there is an Etag on the products list, so at least it allows client to perform conditional GET requests and spare the bytes over the wire.  However, the current list of products weighs in at around 1KB so, chances are it would all fit in a network packet anyway!

Summary

In general, it is a fairly simple HTTP API, that uses techniques that most API developers will be familiar with.  I'm happy that we are starting to see some stabilization around security mechanisms, but I do wish that there was a little more forward thinking in API design in general.

Hypermedia potential

Interestingly, there is quite a bit of opportunity here to take of advantage of hypermedia to define workflows in this kind of API.  There are likely a few fairly well defined paths through the process of selecting a product, verifying the prices, determining time to arrival and then selecting a car.  Along the way, the client application accumulates state: where the user is located, what type of car they want, which driver they want and finally accept a request for pickup.  This is an ideal scenario for hypermedia as the engine of application state to accumulate the information selected by the user whilst leading them on to the next step of the process.

 

Image credit: Uber https://flic.kr/p/evc5a9
Image credit: 404 sign https://flic.kr/p/ca95Ad
Image credit: receipts https://flic.kr/p/35oDiF


Filip Woj: ASP.NET Web API 2: Recipes is out!

My long promised book, ASP.NET Web API 2: Recipes has been published by Apress last week. I announced the book a while ago, when I also tried to explain the general idea behind the book. I nshort, I really wanted … Continue reading

The post ASP.NET Web API 2: Recipes is out! appeared first on StrathWeb.


Darrel Miller: Centralized exception handling using a ASP.NET Web API MessageHandler

ASP.NET Web API 2.1 introduced some significant improvements to the mechanisms that support global error handling. Before this release there were a number of different types of errors that would be handled directly by the runtime and there was no easy way to intercept these errors and add your own custom behavior.  The standard guidance suggests you register these new handlers as services, but I prefer a different approach that seems more natural to me.

The pipe that all flows through

Every request that is processed by Web API goes through the HttpMessageHandler pipeline until it is dispatched to a controller.  The message handler pipeline works in a Russian doll approach where the request goes through each handler from first to last and then the response returns back through the same handlers in reverse. 

pipe

A trap at the end of the pipe

If a controller cannot process a request for some reason and decides that the appropriate response is to throw an exception then my gut tells me that somewhere up the call stack should be the place where that exception is caught.  If I want to have a place where I can catch all exceptions generated by message handlers, the framework dispatching code, or the controllers itself, then having a ErrorHandlingMessageHandler at the front of the message handler pipeline seems like the most natural place. 

    public class ErrorHandlerMessageHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
CancellationToken cancellationToken) { try { return await base.SendAsync(request, cancellationToken); } catch (Exception ex) { return GlobalErrorHandler.ConvertExceptionToHttpResponse(ex); } } }

It will not work when…

With this approach there are two types of exceptions that my message handler will not catch: the first is connectivity errors detected by the HttpServer.  For example the client closed the TCP connection whilst waiting for the response.  The second is serialization errors generated when the HttpServer finally asks the HttpContent to serialize its bytes to a stream and for some reason it fails.  I discussed a workaround to this scenario in another post about debugging serialization errors.

Wipeout

Turn off the default behaviour

By default if you have registered a IErrorHandler and IErrorLogger server those services will be called when exceptions are trapped in framework code.  The expected behavior is that the registered services will create a HttpResponseMessage and set the context object Result property to direct the framework to return response.  That response will be returned back up the pipeline and the message handlers in the pipeline will be somewhat ignorant of the failed request.

public class GlobalErrorHandlerService : IExceptionHandler
{
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        if (context.CatchBlock != ExceptionCatchBlocks.HttpServer)
        {
            context.Result = null;
        }
        return Task.FromResult(0);
    }
}

However, if your registered services explicitly set the Result property to Null, then the framework will take that as an indication that your service have not handled the error and will re-throw the exception that was initially raised.  This will allow each message handler in the pipeline the opportunity to catch the exception and do any processing before allowing the error handling message handler to convert the exception to an actual HTTP response message.  If the exception is caught up in the HttpServer framework code, then it is too late for the message handler to catch it.

 SurfStyle

It's a style thing

I'm not going to claim any major benefits of this approach to centralizing error handling over the use of IErrorHandler service mechanism.  The advantage I see is that it is just one less interaction protocol to deal with.  I already deal with the message handler pipeline, I understand how it works,  and I know how to intercept requests and responses using it and there is nothing really about it that is Web API specific.  With the new mechanisms introduced by WebAPI, I feel like I need to learn a new set of interfaces, how the framework interacts with those interfaces and what my responsibilities are as an interface implementer.  I get especially frustrated by the pattern of passing in context objects that require me to set properties as return values.  It just feels hokey.

One slightly less touchy feely difference between the two approaches relates to how and exception handling message handlers are able to intercept some of the error responses generated by the Web API framework. For example, when the routing mechanism fails to identify an appropriate action method, no exception is thrown, instead a response is created with a 404 status code and a HTTP body that contains certain property values.  An error handling message handler, could intercept those responses and update the body of the response to be something more standardized.  Something like http-problem for example.

Web API your way

Although this approach is not going to appeal to everyone, it does demonstrate an important aspect of the Web API framework.  ASP.NET Web API was never intended to be a particularly opinionated framework.  It was designed to allow people to build HTTP based applications in many different ways.  There are many different extensibility points and components that can be completely swapped out and replaced.  This is a key strength of the framework.  You should take advantage of it.

Image Credit: Pipe https://flic.kr/p/9GuHGn
Image Credit: Wipeout https://flic.kr/p/8vfZYQ
Image Credit: Surf Style https://flic.kr/p/5GNhLA


Darrel Miller: These 8 lines of code can make debugging your ASP.Net Web API a little bit easier.

I think most us ASP.Net Web API developers have, at some point, experienced the problem where their API is returning a 500 Internal Server Error, but tracing through with Visual Studio doesn't reveal any exceptions in our code.  This problem is often caused when a MediaTypeFormatter is unable to serialize an object.  This simple message handler can take away some of the pain of debugging these scenarios.

ButterflyNet

The code

I'll start with the solution, and try and explain why the problem occurs and show how this MessageHandler solves the problem.

public class BufferNonStreamedContentHandler : DelegatingHandler
{
  protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
CancellationToken cancellationToken) { var response = await base.SendAsync(request, cancellationToken); if (response.Content != null) {
var services = request.GetConfiguration().Services; var bufferPolicy = (IHostBufferPolicySelector)services.GetService(typeof(IHostBufferPolicySelector));
// If the host is going to buffer it anyway
if (bufferPolicy.UseBufferedOutputStream(response)) {
// Buffer it now so we can catch the exception await response.Content.LoadIntoBufferAsync(); } } return response; } }

This message handler is installed by adding it to the collection of MessageHandlers on the Web API configuration object.

config.MessageHandlers.Add(new BufferNonStreamedContentHandler());

Just do it sooner

HighSpeedTrain

The message handler uses the IHostBufferPolicySelector to determine if the Host will buffer the response body before sending it over the wire.  For the vast majority of cases this will be true, and definitely will be true if an API returns a CLR object that will be serialized using the JsonMediaTypeFormatter or the XmlMediaTypeFormatter.

If we know the Host is going to buffer it, then we force the content to be buffered early so that we can trigger any exceptions that will occur during serialization via user code.  This will allow Visual Studio to trap the exception.  Or if you are using an trapping errors with a message handler, the exception can be trapped and dealt with there.

Why does Web Api do that?

Normally, this check against IHostBufferPolicySelector is only done once all the message handlers have completed and control is returned to the Http Server Host.  At this point you there is no-longer user code anywhere in the call stack and therefore Visual Studio doesn't break unless you have configured it to break in framework code.

The buffering of content is deferred by default just in case the host decides it wants to stream the content directly to the network stream.  HTTP headers need to be written out before body bytes can be written out and message handlers might want to change HTTP headers, so Web API has to wait until all the message handlers have completed before it can start streaming content.

It's virtually free

If we have buffered the content early, then the Host is smart enough to know not to try and serialize the content again, so adding this handler will add a minimal amount of overhead.  We are paying the price of checking IHostBufferPolicySelector an extra time so that we can catch exceptions for content that will be buffered.

FreeHugs

This solution does not help if you really are serializing content directly to the network stream.  However, if you are already writing body bytes over the wire, then the status code has already been sent and there is little that can be done at that point to handle an exception cleanly. 

It can't hurt to try it

I suspect this little trick has saved me hours of head scratching, hopefully it will do the same for others.

Image Credit: Butterfly hunter https://flic.kr/p/nqGeY7
Image Credit: High speed train https://flic.kr/p/7suAc4
Image Credit: Free hugs https://flic.kr/p/4k3eAY


Dominick Baier: Announcing Thinktecture IdentityServer v3 – Beta 1

It’s done – and I am happy (and a bit exhausted) – a few minutes ago I closed the last open issue for Beta 1.

What’s new
It’s been 424 commits since we released Preview 1 – so there is quite a lot of new stuff, but the big features are:

  • A completely revamped configuration system that allows replacing bits and pieces of the core server itself – including a DI system
  • A plugin infrastructure that allows adding new endpoints (WS-Federation support is a plugin e.g.)
  • Refresh tokens
  • Infrastructure that allows customizing views and UI assets for re-branding as well as extensibility to insert your own workflows like registration or EULAs
  • Support for CORS and HTTP strict transport security
  • Content Security Policy (CSP) & stricter caching rules
  • Protection against click-jacking
  • Control over cookies (lifetime, naming etc)
  • more extensibility points

Repositories
We also split up the solution into separate repos and nugets for better composability:

Samples and documentation
We also have a separate repo for samples and added quite a bit of content to the wiki.

With that I am now leaving for holidays! ;) Give IdentityServer a try and give us feedback. A big thanks to all contributors and the people that engaged with us over the various channels!!!

Have a nice summer!


Filed under: .NET Security, ASP.NET, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, Uncategorized, WebAPI


Filip Woj: Dependency injection directly into actions in ASP.NET Web API

There is a ton of great material on the Internet about dependency injection in ASP.NET Web API. One thing that I have not seen anywhere though, is any information about how to inject dependencies into the action, instead of a … Continue reading

The post Dependency injection directly into actions in ASP.NET Web API appeared first on StrathWeb.


Darrel Miller: Everything you need to know about HTTP Header syntax but were afraid to ask

If you use HTTP then the chances are good that you have to deal with HTTP headers.  The syntax of HTTP headers has a long and tortured history, originating from the syntax of email headers.  All too often I see headers that don't conform to the specifications.  This makes everyone's job a little bit harder.  The recent releases of the HTTP specifications have done a fair amount of clarification and consolidation to make getting the syntax right.RaiseHand

Two stage parsing

HTTP Header parsing is broken down into two phases.  In phase one, the headers are extracted from the HTTP message into a set of name/value pairs.   The name is a case-insensitive token that is defined in the HTTP specification and registered in the Message Header registry, and the value is a string whose syntax is defined specifically for that header name in the HTTP specification.  The syntax of a HTTP header always looks like this:

header-field   = field-name ":" OWS field-value OWS

OWS means "optional whitespace" and header fields are delimited using CRLF.  Note that RFC7230 now recommends that there should be no whitespace between the header name and the colon.

It is a header, that's all I need to knowOLYMPUS DIGITAL CAMERA

The ability to generically parse HTTP headers into these name value pairs without concern for the syntax of the field value is critical for performance and extensibility.  Not every component needs to look at every header, so the requirement for every intermediary in the path of the HTTP request to parse the header value contents would be wasteful.  Also, new headers are created regularly, so needing to update HTTP libraries whenever new header definitions are added would be problematic.

Wrapped lines are no more

There are a couple of additional issues relating to parsing the header lines.  In the past it was possible to allow header values to wrap onto the next line by prefixing the wrapped line with a whitespace character[1].  The most recent HTTP header specifications recommend to no longer do this[2].   

Multiple header instances

The second major issue is related to headers that contain lists of values separated by a comma.  These headers can appear multiple times in a message.  A header parsing routine can aggregate these multiple headers into a single list of values.  The one exception to this rule is the Set-Cookie header.  Set-Cookie headers are allowed to appear multiple times despite not being a comma separated list.

The building blocks

Splitting the header field names and values is the easy part.  Unfortunately, that is where most HTTP frameworks that I've seen seem to give up, or only provide support for the most commonly used headers.  They lay the burden of parsing the semantics out of headers on the application developer.  This can be painful because every header field-value has its own syntax definition Fortunately, the HTTP specification provides some basic building blocks for defining the syntax of HTTP headers.

buildingblocks

Most headers, when simplified down to primitives, are a combination of token, quoted-string, comment, OWS (optional whitespace), RWS (required whitespace), and literalsThere are also several rules for defining lists of expressions.

  • Tokens are are string of characters that avoid certain delimiter characters.
    Quoted-strings are surrounded by double quotes and have a slightly different set of rules for what characters are allowed.
    Comment is a string surrounded by parentheses with yet again another set of valid characters.

For a quick review of which characters are allowed and which are not, I created a chart below[3].

Syntax Rules

As i mentioned each header has its own syntax rules.  For example, User-Agent is defined as,

User-Agent = product *( RWS ( product / comment ) )

Where,

product         = token ["/" product-version]
product-version = token

and *(x) means "zero or more x", (x/y) means "either x or y" and [x] means "x is optional".  This is a standardized syntax definition language called ABNF.  Many of the headers rules are summarized in appendices of the specification in which they are defined.

Lists of things

The most common way that HTTP headers allow you to specify lists of tokens is using the  #(x)  syntax[4] which means you can have zero more x delimited with a comma.  As you can see from the example above, you can also have whitespace delimited lists. Parameters, which are often lists within a single element of a comma delimited list,  will be delimited by semi-colons.

An implementation

The various HTTP frameworks that I have reviewed have varying support for parsing of header values.  Considering that it is just a bunch of grammar rules for parsing and production of strings, it would seem useful to me if there was a library that allowed developers to ensure that the headers they are sending conform to the specification without needing to constantly refer to the specification rules.

I believe the key requirements of a .Net framework library for HTTP header parsing and generating are:

  • support for all standard headers
  • support for creating new headers that use the standard header primitives
  • allow for parsing/generating individual headers
    generate warnings for invalid headers when parsing and do best guess parsing.
  • have no external dependencies other than the .net framework
  • make efficient use of memory and be fast enough that its usage is negligible on the overall processing time of the message.

I'm currently working on a OSS library to do this, with the hope of being able to use it within OWIN middleware.  I'll blog about it when I have something to show.

[1] I suspect the reason header wrapping exists is based on the fact that headers were originally defined to be part of email messages that were limited to a 80 character line length.  It's really not relevant for headers in a HTTP message where there is no need to wrap.

[2] When specifications make a change to deprecate certain behaviour it is important to remember Postel's law.  When parsing headers, we have to assume that old clients/servers are going to continue doing the line folding, so it is essential that we write components that accept folded headers but we should never do it when generating headers.

[3]

Allowed Characters

Hex

Chars

Token

Quoted String

Comment

00-08        
09 <tab>   y y
1A-1F        
20 <Space>      
21 ! y y y
22 "     y
23-27 #$%&' y y y
28-29 ()   y  
2A-2F *+ y y y
2C ,   y y
2D-2E -. y y y
2F / y   y
30-39 <digit>   y y
3A-40 :;<=>?@   y y
41-5A <ALPHA> y y y
5B [   y y
5C \      
5D ]   y y
5E-60 ^_` y   y
61-7A <alpha> y y y
7B-7E {   y y
7C | y y y
7D }   y y
7E - y y y

 

[4] The #() list syntax is an extension to the standard ABNF rules that is defined with the HTTP specification.

Image credit: Raise hand https://flic.kr/p/2vgyWN
Image credit: Package https://flic.kr/p/8sgnwu


Henrik F. Nielsen: More Updates to Azure Mobile Services (Link)

Just posted the blog Azure Mobile Services .NET Updates describing new features now available for Azure Mobile Services including:

  • Support for CORS using ASP.NET Web API CORS enabling first class support for specifying CORS policy at a per-service, per-controller, or per-action level.
  • An extensible authentication model enabling you to control which authentication mechanisms are available for your mobile service clients. For example, you can add your own authentication mechanisms in addition to or in place of the default support for Azure Active Directory, Twitter, Facebook, Google, and Microsoft Account.
  • Support for Azure Active Directory Authentication using a server-side flow simplifying client authentication significantly.

If you are building cloud connected mobiles apps then check out Microsoft Azure Mobile Services and let us know what you think!

Have fun!

Henrik


Radenko Zec: How to fake session object / HttpContext for integration tests

Sometimes when we write integration tests we need to fake HttpContext to test some functionality proper way.

In one of my projects I needed a possibility to fake some session variables such as userState and maxId.

A project that is tested in this example is an ASP.NET Web API with added support for session but you can use the same approach in any ASP.NET/ MVC project.

Implementation is very simple. First, we need to create FakeHttpContext.

 

 public HttpContext FakeHttpContext(Dictionary<string, object> sessionVariables,string path)
{
    var httpRequest = new HttpRequest(string.Empty, path, string.Empty);
    var stringWriter = new StringWriter();
    var httpResponce = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponce);
    httpContext.User = new GenericPrincipal(new GenericIdentity("username"), new string[0]);
    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("username"), new string[0]);
    var sessionContainer = new HttpSessionStateContainer(
      "id",
      new SessionStateItemCollection(),
      new HttpStaticObjectsCollection(),
      10,
      true,
      HttpCookieMode.AutoDetect,
      SessionStateMode.InProc,
      false);

   foreach (var var in sessionVariables)
   {
      sessionContainer.Add(var.Key, var.Value);
   }

   SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);
   return httpContext;
}


 

After we have FakeHttpContext we can easily use it in any integration tests like this.

 

 [Test]
public void DeleteState_AcceptsCorrectExpandedState_DeletesState()
{
   HttpContext.Current = this.FakeHttpContext(
      new Dictionary<string, object> { { "UserExpandedState", 5 }, 
                                        { "MaxId", 1000 } },    
                                          "http://localhost:55024/api/v1/");

   string uri = "DeleteExpandedState";
   var result = Client.DeleteAsync(uri).Result;
   result.StatusCode.Should().Be(HttpStatusCode.OK);

   var state = statesRepository.GetState(5);
   state.Should().BeNull();
}

 

This is an example of integration test that tests Delete method of WebAPI.

WebAPI is this example hosted in memory for the purpose of integration testing.

If you like this article don’t forget to subscribe to this blog and make sure you don’t miss new upcoming blog posts.

 
 

The post How to fake session object / HttpContext for integration tests appeared first on RadenkoZec blog.


Radenko Zec: Replace JSON.NET with Jil JSON serializer in ASP.NET Web API

I have recently come across a comparison of fast JSON serializers in .NET, which shows that Jil JSON serializer is one of the fastest.

Jil is created by Kevin Montrose developer at StackOverlow and it is apparently heavily used by Stackoveflow.

This is only one of many benchmarks you can find on Github project website.

JilSpeed

You can find more benchmarks and the source code at this location https://github.com/kevin-montrose/Jil

In this short article I will cover how to replace default JSON serializer in Web API with Jil.

Create Jil MediaTypeFormatter

First, you need to grab Jil from NuGet

PM> Install-Package Jil

 

 

After that, create JilFormatter using code below.

    public class JilFormatter : MediaTypeFormatter
    {
        private readonly Options _jilOptions;
        public JilFormatter()
        {
            _jilOptions=new Options(dateFormat:DateTimeFormat.ISO8601);
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

            SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
            SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
        }
        public override bool CanReadType(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            return true;
        }

        public override bool CanWriteType(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            return true;
        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
        {
            var task= Task<object>.Factory.StartNew(() => (this.DeserializeFromStream(type,readStream)));
            return task;
        }


        private object DeserializeFromStream(Type type,Stream readStream)
        {
            try
            {
                using (var reader = new StreamReader(readStream))
                {
                    MethodInfo method = typeof(JSON).GetMethod("Deserialize", new Type[] { typeof(TextReader),typeof(Options) });
                    MethodInfo generic = method.MakeGenericMethod(type);
                    return generic.Invoke(this, new object[]{reader, _jilOptions});
                }
            }
            catch
            {
                return null;
            }

        }


        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
        {
            using (TextWriter streamWriter = new StreamWriter(writeStream))
            {
                JSON.Serialize(value, streamWriter, _jilOptions);
                var task = Task.Factory.StartNew(() => writeStream);
                return task;
            }
        }
    }

 

This code uses reflection for deserialization of JSON.

Replace default JSON serializer

In the end, we need to remove default JSON serializer.

Place this code at beginning of WebApiConfig

config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new JilFormatter());

 

Feel free to test Jil with Web API and don’t forget to subscribe here and don’t miss a new blog post.

 
 

The post Replace JSON.NET with Jil JSON serializer in ASP.NET Web API appeared first on RadenkoZec blog.


Darrel Miller: Hypermedia as the engine of application state, the client-server dance

We are currently seeing a significant amount of discussion about building hypermedia APIs.  However, the server side only plays part of the role in a hypermedia driven system.  To take full advantage of the benefits of hypermedia, the client must allow the server to take the lead and drive the state of the client.  As I like to say, it takes two to Tango.

So you think you can dance? Tango

Soon after I was married, my wife convinced me to take dance lessons with her.  Over the couple of years we spent taking lessons, I learned there were three types of people who join a dance studio.  There are people who want to get better at dancing, there are couples who are getting married who don't want to look like idiots during their 'first dance' and there are divorcees.  I'll leave it to you to figure out why the divorcees are there as I'll just be focusing on the other two groups.

The couples who are preparing for their weddings usually are under time and budgetary constraints, so they usually opt to learn a choreographed sequence of steps to a particular song.  They both learn the sequence of steps and, to an extent, dance their own independent steps whilst hanging on to each other.  It is a process that serves a purpose. It meets the goals of the couple, but it is a vastly inferior result to the approach taken when people's goal is simply to learn how to dance.

FirstDance

In order to learn to dance there are a number of basic fundamentals that are required. It is essential to be able to follow the beat of whatever music you are trying to dance to.  There are a set of basic dance primitives that can be combined to make up dance sequences.  It is also important to understand the role of the man vs that of the woman when dancing (Note: these are traditional role names, and no longer necessarily correlate with gender). The man leads the dance, the woman follows. 

RumbaSteps As the dance progresses the man chooses the sequences of primitives to perform and uses hand signals, body position and weight change to communicate with the women what steps are coming next.  There is no predefined, choreographed set of sequences. The man basically does whatever he wants within the constrains of dance style. The woman follows. 

When done right, it looks like magic

Watching a talented couple do this freestyle dance is often indistinguishable from a choreographed dance.  When people learn to dance this way, they can dance to any piece of music as long as the beat matches a style of dance they know and they can dance with any partner.   Whereas, couples who learn their wedding dance, know one sequence to one piece of music and can only dance it with one partner.

The Client-Server dance

Building a client that can consume a HTTP API can be done in different ways.  You can build your application to be like a choreographed dance, where both the client and sever know in advance what is going to happen.  When the client makes an HTTP request to a particular resource it knows in advance how the server will respond.  The challenge with this approach is that both parties need to have knowledge of the sequences, and more importantly, where they are up to in the sequence. If someone decides to make any changes the other party is likely to get confused by the unplanned change.Duel_of_the_Fates[1]

A choreographed client

The last twenty years of building clients for distributed applications has taught us how to build highly choreographed clients.  We first learn the API that the server exposes and then teach our clients an intricate pattern of interactions in order to achieve our desired goals.  Our application is the dance we perform.

Frequently when building clients like this we will create a facade over the remote service and a view model to manage the state of the sequence of interactions. Consider the following example of a distributed application that is designed to perform the dance of turning on and off a light switch.

The service facade:

    public class SwitchService
    {
        private const string SwitchStateResource = "switch/state";
        private const string SwitchOnResource = "switch/on";
        private const string SwitchOffResource = "switch/off";

        private readonly HttpClient _client;

        public SwitchService(HttpClient client)
        {
            _client = client;
        }

        public async Task<bool> GetSwitchStateAsync()
        {
            var result = await _client.GetStringAsync(SwitchStateResource).ConfigureAwait(false);

            return bool.Parse(result);
        }

        public Task SetSwitchStateAsync(bool newstate)
        {
            if (newstate)
            {
                return _client.PostAsync(SwitchOnResource,null);
            }
            else
            {
                return _client.PostAsync(SwitchOffResource, null);
            }
        }
    }

The view model:

    public class SwitchViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        
        private readonly SwitchService _service;
        private bool _switchState;

        public SwitchViewModel(SwitchService service)
        {
            _service = service;
            _switchState = service.GetSwitchStateAsync().Result;
        }

        
        private bool SwitchState {
            get
            {
                return _switchState; 
            }
             set
            {
                _service.SetSwitchStateAsync(value).Wait();
                _switchState = value; 
                OnPropertyChanged();
                OnPropertyChanged("CanTurnOn");
                OnPropertyChanged("CanTurnOff");
            }
        }

        public bool On
        {
            get { return SwitchState; }
        }

        public void TurnOff()
        {
            SwitchState = false;
        }

        public void TurnOn()
        {
            SwitchState = true;
        }


        public bool CanTurnOn
        {
            get { return SwitchState == false; }
        }

        public bool CanTurnOff
        {
            get { return SwitchState; }
        }
        

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

In our client view model we maintain the current SwitchState.  The client needs to know at any point in time, whether the switch is on or off.  This information will be provided to the View to present a visual representation to the user and it is also used to drive the application logic that determines if we are allowed to turn the switch on or off again.  Our application wishes to prevent someone from trying to turn on the switch if it is already on and turn off the switch if it is already off.  This is an extremely simple example but will be sufficient to illustrate differences between the two approaches.

The important point to note,  that just like our engaged couple doing their dance, both the client and server must keep track of the current application state in order to know what they can and must do next.  SkippingRope

Sometimes you just have to let go

In this next example, we take away the responsibility from the client of keeping track of state that is already being tracked by the server.  The client simply follows the lead of the server and trusts the server to provide it the necessary guidance.

basejump

We no longer need to provide a facade over the server API and instead we focus on understanding the messages communicated to by the server.  For that we have created a class called SwitchDocument that allows the client to parse and interpret the message. 

    public class SwitchDocument
    {
        public static SwitchDocument Load(Stream stream)
        {
            var switchStateDocument = new SwitchDocument();
            var jObject = JObject.Load(new JsonTextReader(new StreamReader(stream)));
            foreach (var jProp in jObject.Properties())
            {
                switch (jProp.Name)
                {
                    case "On":
                        switchStateDocument.On = (bool)jProp.Value;
                        break;
                    case "TurnOnLink":
                        switchStateDocument.TurnOnLink = new Uri((string)jProp.Value, UriKind.RelativeOrAbsolute);
                        break;
                    case "TurnOffLink":
                        switchStateDocument.TurnOffLink = new Uri((string)jProp.Value, UriKind.RelativeOrAbsolute);
                        break;
                }
            }
            return switchStateDocument;
        }

        public bool On { get; private set; }
        public Uri TurnOnLink { get; set; }
        public Uri TurnOffLink { get; set; }

        public static Uri SelfLink
        {
            get { return new Uri("switch/state", UriKind.Relative); }
        }
    }

Our view model now has the reduced role of simply presenting the information contained in the SwitchDocument to the view and providing a way to interact with the affordances described in the SwitchDocument.

    public class SwitchHyperViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private readonly HttpClient _client;
        private SwitchDocument _switchStateDocument = new SwitchDocument();

        public SwitchHyperViewModel(HttpClient client)
        {
            _client = client;
            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/switchstate+json"));
            _client.GetAsync(SwitchDocument.SelfLink).ContinueWith(t => UpdateState(t.Result)).Wait();
        }

        public bool On
        {
            get { return _switchStateDocument.On; }
        }

        public bool CanTurnOn
        {
            get { return _switchStateDocument.TurnOnLink != null; }
        }

        public bool CanTurnOff
        {
            get { return _switchStateDocument.TurnOffLink != null; }
        }

        public void TurnOff()
        {
            _client.PostAsync(_switchStateDocument.TurnOffLink, null).ContinueWith(t => UpdateState(t.Result));
        }

        public void TurnOn()
        {
            _client.PostAsync(_switchStateDocument.TurnOnLink, null).ContinueWith(t => UpdateState(t.Result));
        }

        private void UpdateState(HttpResponseMessage httpResponseMessage)
        {
            if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
            {
                _switchStateDocument = SwitchDocument.Load(httpResponseMessage.Content.ReadAsStreamAsync().Result);

                OnPropertyChanged();
                OnPropertyChanged("CanTurnOn");
                OnPropertyChanged("CanTurnOff");
            }
        }

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

    }

This new hypermedia driven View Model has the same interface as the choreographed one and can be easily connected to the same simple user interface to display the state of the light switch and provide controls that can change the light switch.   The difference is in the way the application state is managed.  In this case, the view model determines if the switch can be turned on or off based on the presence of links that will turn on and off the switch.  Attempting to turn on or off the switch involves making a HTTP request to the server and using the response as a completely new state for the view model. 

You can find a complete WPF example in the Github repository.

The similarity is only skin deep

On the surface it appears that the two different approaches produce pretty much the same results.  It is almost the same amount of code, with a similar level of complexity.  The question has to be asked, what are the benefits?

FakePurse If you watch a couple dance who have learned a choreographed dance, you may think they are very capable dancers.  You may not even be able to tell the difference between them and others doing the same dance who have a much more fundamental understanding of how to dance.  The differences only begin to appear when you introduce change.  Changing dance partners, changing music or adding new steps will quickly reveal the differences.

The impact of change

The same is true with our sample application.  Consider the scenario where new requirements are introduced where a switch could only be turned on during a certain time period, or only users with certain permissions could turn on the switch. 

In the choreographed application, we would need to add a number of other server resources that would allow a client to inquire if a user has permission, or if the time of day permits turning on or off the switch.  The client must call those resources to retrieve the information, which in itself is not terribly complex.  However, deciding when to make those requests can be tricky.  Calling them frequently adds a significant performance hit, but caching the values locally can introduce problems with keeping the local state consistent with the server based resource state.

Windmills In the hypermedia driven client, neither of our new business requirements require additional resources to be created or server roundtrips.  In fact the client code does not need to change.  All the logic that is used to determine if a client can turn on or off a switch can be embedded into the server logic for determining whether to include a "TurnOn" link or a "TurnOff" link. 

The links are always refreshed along with the state of the switch so the client state is always consistent.  The state may be stale, but that is fine because HTTP has all kinds of mechanism for refreshing stale state.  The key thing is the client does not need to deal with the complexity of the permissions being an hour old, the timing schedule being ten minutes old and state of the switch being ten seconds old.

Some constraints can lead to unimagined possibilities

The fact that our client application does not need to change to accommodate these new requirements is far more significant than our analogy might lead us to believe.  When ballroom dancing there usually just one man and one woman.  The implications of making changes to the dance are limited.  In distributed systems, it is not uncommon for a single API to have thousands of client instances and perhaps multiple different types of clients.  The client applications are often created by different teams, in different countries with completely different time constraints. 

Being able to make logic changes on the server that would normally be embedded into the client can potentially have huge benefits.  The example I have shown only scratches the surface of the techniques that be applied using hypermedia, but hopefully it hints at the possibilities.

Hangglider

Image Credit: Tango https://flic.kr/p/7BY638
Image Credit: First Dance https://flic.kr/p/d3vMxG
Image Credit: Rumba Steps https://flic.kr/p/dMrKk
Image Credit: Skipping Rope https://flic.kr/p/6pZSGX
Image Credit: Base jump https://flic.kr/p/df5Nwd
Image Credit: Fake Gucci purse: https://flic.kr/p/9w5Qji
Image Credit: Windmills https://flic.kr/p/96iTMv
Image Credit: Hang Glider https://flic.kr/p/6jfG9m


Radenko Zec: 8 ways to improve ASP.NET Web API performance

ASP.NET Web API is a great piece of technology. Writing Web API is so easy that many developers don’t take the time to structure their applications for great performance.

In this article, I am going to cover 8 techniques for improving ASP.NET Web API performance.

1) Use fastest JSON serializer

JSON serialization  can affect overall performance of ASP.NET Web API significantly. A year and a half I have switched from JSON.NET serializer on one of my project to ServiceStack.Text .

I have measured around 20% performance improvement on my Web API responses. I highly recommend that you try out this serializer. Here is some latest performance comparison of popular serializers.

SerializerPerformanceGraf

Source: theburningmonk

UPDATE: It seams that StackOverflow uses what they claims even faster JSON serializer called Jil. View some benchmarks on their GitHub page Jil serializer.

2) Manual JSON serialize from DataReader

I have used this method on my production project and gain performance benefits.

Instead reading values from DataReader and populating objects and after that reading again values from those objects and producing JSON using some JSON Serializer,  you can manually create JSON string from DataReader and avoid unnecessary creation of objects.

You produce JSON using StringBuilder and in the end you return StringContent as the content of your response in WebAPI

var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jsonResult, Encoding.UTF8, "application/json");
return response;

 

You can read more about this method on Rick Strahl’s blog

3) Use other formats if possible (protocol buffer, message pack)

If you can use other formats like Protocol Buffers or MessagePack in your project instead of JSON do it.

You will get huge performance benefits not only because Protocol Buffers serializer is faster, but because format is smaller than JSON which will result in smaller and faster responses.

4) Implement compression

Use GZIP or Deflate compression on your ASP.NET Web API.

Compression is an easy and effective way to reduce the size of packages and increase the speed.

This is a must have feature. You can read more about this in my blog post ASP.NET Web API GZip compression ActionFilter with 8 lines of code.

5) Use caching

If it makes sense, use output caching on your Web API methods. For example, if a lot of users accessing same response that will change maybe once a day.

If you want to implement manual caching such as caching tokens of users into memory please refer to my blog post Simple way to implement caching in ASP.NET Web API.

6) Use classic ADO.NET if possible

Hand coded ADO.NET is still the fastest way to get data from database. If the performance of Web API is really important for you, don’t use ORMs.

You can see one of the latest performance comparison of popular ORMs.

ORMMapper

The Dapper and the  hand-written fetch code are very fast, as expected, all ORMs are slower than those three.

LLBLGen with resultset caching is very fast, but it fetches the resultset once and then re-materializes the objects from memory.

7) Implement async on methods of Web API

Using asynchronous Web API services can increase the number of concurrent HTTP requests Web API can handle.

Implementation is simple. The operation is simply marked with the async keyword and the return type is changed to Task.

[HttpGet]  
public async Task OperationAsync()  
{   
    await Task.Delay(2000);  
}

8) Return Multiple Resultsets and combined results

Reduce number of round-trips not only to database but to Web API as well. You should use multiple resultsets functionality whenever is possible.

This means you can extract multiple resultsets from DataReader like in the example bellow:

// read the first resultset 
var reader = command.ExecuteReader(); 

// read the data from that resultset 
while (reader.Read()) 
{ 
	suppliers.Add(PopulateSupplierFromIDataReader( reader )); 
} 

// read the next resultset 
reader.NextResult(); 

// read the data from that second resultset 
while (reader.Read()) 
{ 
	products.Add(PopulateProductFromIDataReader( reader )); 
}

 

Return as many objects you can in one Web API response. Try combining objects into one aggregate object like this:

public class AggregateResult
{
     public long MaxId { get; set; }
     public List<Folder> Folders{ get; set; }
     public List<User>  Users{ get; set; }
}

 

This way you will reduce the number of HTTP requests to your Web API.

Thank you for reading this article.

Leave a comment below and let me know what other methods you have found to improve Web API performance?

 
 

The post 8 ways to improve ASP.NET Web API performance appeared first on RadenkoZec blog.


Dominick Baier: NDC London: Identity and Access Control for modern Web Applications and APIs

I am happy to announce that NDC will host our new workshop in London in December!

Join us to learn everything that is important to secure modern web applications and APIs using Microsoft’s current and future web stack! Looking forward to it!

course description / ndc london / tickets


Filed under: .NET Security, ASP.NET, IdentityModel, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Dominick Baier: Updated IdentityServer v3 Roadmap (and Refresh Tokens)

Brock and I have been pretty busy the last months and we did not find as much time to work on IdentityServer as we wanted.

So we have updated our milestones on github and are currently planning a Beta 1 for beginning of August.

You can check the github issue tracker (or open new issues when you find bugs or have suggestions) or you can have an alternative view on our current work using Huboard.

I just checked in initial support for refresh tokens, and it would be great if you could give that a try and let us know if it works for you – see here.

That’s it – back to work.


Filed under: ASP.NET, IdentityServer, OAuth, OpenID Connect, WebAPI


Filip Woj: Building a strongly typed route provider for ASP.NET Web API

ASP.NET Web API 2.2 was released last week, and one of the key new features is the ability to extend and plug in your own custom logic into the attribute routing engine. Commonly known as “attribute routing”, it’s actually officially … Continue reading

The post Building a strongly typed route provider for ASP.NET Web API appeared first on StrathWeb.


Darrel Miller: The Insanity of the Vary Header

In my first deep dive into a HTTP header on the user-agent header I said that I would try and produce a series of posts going under the covers on certain HTTP headers.  This post is about the Vary header.  The Vary header both wonderful and sad at the same time.  I'll discuss how to make it work for you and where it fails miserably.

The Vary header is used for HTTP caching.  If you want the really gory details of HTTP caching, you can find them here in,  Caching is hard, draw me a picture.  The short and pertinent part of that story is, when you make an HTTP request, it is possible that the response will come from a cache, rather than being generated by the origin server.  For the cache to know whether it can satisfy a response it needs a cache key.

Anatomy of a cache key

KeyCache entries have a primary cache key and potentially a secondary cache key.  The primary cache key is made up of a HTTP method and a URL.  For the vast majority of cases the HTTP method is a GET.  So, for the purposes of our discussion about the vary header, we can assume that the primary cache key is the URL of the HTTP resource. 

Assuming a resource identifies itself as cacheable, or at least, does not explicitly prevent it, a cache that sits somewhere between the client and the origin server, could hold on to a copy of the representation returned from the origin server and store it for satisfying future requests to the same URL. 

But we have variants

The challenge that we have is other HTTP headers can be used to request variations of the representation.  If we were to send Accept-encoding: gzip in our request, we are telling the server that we can handle the response being compressed.  What should the cache do?  Should it ignore the request and pass it along to the server.  Should it return the uncompressed version?  For compressed content, it might not be a big deal because if the client can handle compressed responses, it can also handle uncompressed responses, so whatever happens the client will be happy.  But what should the cache do with a compressed response that comes back from the origin server? Should it update the representation stored in the cache  with the new compressed one?  That would be a problem for future request from clients that do not have the ability to decompress responses.

The example of Accept-Encoding has lots of possible solutions.  However, a header like Accept-Language is more challenging.  If one user asks for a French version of a resource and another asks for an English version of a resource, only one can be stored in the cache if we limit ourselves to just the primary cache key.

We have the same problem if we just use the Accept header to do transparent negotiation between media types.  If one user asks for application/calendar+json and another asks for application/calendar+xml then we can only cache one of these at once.

Vary to the rescue

So far we have mentioned three different HTTP headers that could cause different variations of the resource to be returned.  We can use the Vary header in a response from a server to indicate which HTTP headers were used to produce the variation.

This is the LA County Sheriff Department's Rescue 5 helicopter. The first time I saw it was at the air show but ever since then, I see it all the time on the local news. At the air show the crew performed a mock rescue by lowering a rescuer down to the ground and then lifting someone up into the helicopter. It was pretty impressive!

ABOUT THE SERIES

In 2008 I went to the American Heroes Air Show with my friend Ryan. The air show exhibits helicopters from law enforcement, fire departments, search and rescue, and other government agencies.

When a HTTP cache goes to store the representation it needs to look at the Vary header and for each header listed, look at the request headers that generated the response.  The values of those request headers are used as the secondary cache key.  The cache then uses this secondary cache key to store multiple variants for the same primary cache key.

When trying to satisfy a request from those stored, the cache will use the headers named in the Vary header of the stored variant to generate a new secondary cache key from the request.  If the secondary cache key generated from the request, match that of the stored representation then the stored representation can be served to the client.

Bingo! We can now cache all kinds of variants of our resource and the cache will know which one to serve up based on what the request asks for.

Sounds like a great idea, but...

Consider this request

> GET /test HTTP/1.1
> Host: example.com
> Accept-Encoding: gzip,deflate
>
< HTTP/1.1 200 OK
< Vary: Accept-Encoding
< Content-Encoding: gzip
< Content-Type: application/json
< Content-Length: 230
< Cache-Control: max-age=10000000

followed by

> GET /test HTTP/1.1 
> Host: example.com 
> Accept-Encoding: gzip 
> 
< HTTP/1.1 200 OK 
< Vary: Accept-Encoding
< Content-Encoding: gzip 
< Content-Type: application/json 
< Content-Length: 230 
< Cache-Control: max-age=10000000 

The first request would generate a secondary cache key of "gzip,deflate" because the Vary header declared by the server says that the representation was affected by the value of the Accept-Encoding header. 

In the second request, the Accept-Encoding header is different, because this client does not support the "deflate" method of compression.  Even though the cache is holding onto a perfectly good copy of the representation that is gzip compressed and the second client can process gzipped representations, the second client will not get that stored response served because the Accept-Encoding header of the request does not match the value in the secondary cache key.

Translated into English, if you don't ask for exactly the same thing, you won't get the cached copy even if is what you want.

Wait, it gets worse

accident

Time passes, representations are cached, the origin server code is updated to be multilingual, and now the vary header that is returned includes both Accept-Encoding and Accept-Language.

A client makes the following request,

> GET /test HTTP/1.1
> Host: example.com
> Accept-Encoding: gzip,deflate
> Accept-Language: fr
>
< HTTP/1.1 200 OK
< Vary: Accept-Encoding, Accept-Language
< Content-Encoding: gzip
< Content-Language: fr
< Content-Type: application/json
< Content-Length: 230
< Cache-Control: max-age=10000000

The cache stores the representation using a secondary cache key of "gzip,deflate:fr".  The same client then makes exactly the same request. Can you see a problem?

If we assume that the representation we stored, back when the vary header only contained Accept-Encoding, is still fresh then we now have two stored representations that match.  This is because when we compare this new request with the old stored representation, the vary header of the old representation only tells us to look at the Accept-Encoding header.

The guidance provided by the HTTP Caching specification tells us that we  MUST use the most recent matching response to satisfy these ambiguous requests.   This isn't really a major problem for developers writing clients and servers, but it's a pain for people trying to write caches.  In fact, I haven't found a private cache implementation that actually does this yet.

Its not as simple as I make it out to be

I glossed over a number of additional issues mentioned in the spec.  When the vary header contains an asterisk, no variants are allowed to match.  I'm still trying to figure out why you would want to store a variant that will never match a request.

Also, I talked about generating the secondary cache key from the values in the request header.  Technically, before creating the secondary cache key, those header values should be normalized.  Which is a fancy term for stripping unnecessary whitespace, removing differences of letter casing when a header value is deemed case insensitive and other more insane requirements like re-ordering field values where the order is not significant.  You can imagine doing a vary on an accept header that lists a bunch of different media types and having to parse them and sort them before being able to do a comparison!

If you think the specification is bad, you should see the implementations

I can't speak for implementations on all platforms, but the support for the vary header on the Windows platform is less than ideal.  Eric Lawrence covers the details of Vary in IE in a blog post.  It would not surprise me in the slightest if other platforms are similarly limited in their support for Vary.

Is there a point to this post?

I believe there are three points to this post: 

  • Vary is a widely used HTTP header, so ideally developers should understand how it is supposed to work.
  • Lots of people are gung-ho on transparent content negotiation.  Without a good working vary implementation, caching is going to be difficult.  That's not good for performance.
  • I'd like to point to a proposed alternative that solves many of the problems of the vary header, the Key Response Http Header.  I'll have to save discussion of this solution for a future post.
Road

Image Credit: Key https://flic.kr/p/56DLot
Image Credit: Rescue https://flic.kr/p/9w9doc
Image Credit: Accident https://flic.kr/p/5XfRKk
Image Credit: Road https://flic.kr/p/8GokGE


Radenko Zec: Simple way to share Dependency Resolvers between MVC and Web API

I had several projects in past using ASP.NET MVC 4 and 5 and ASP.NET Web API that reside in same project. When you want to share DI container between MVC and Web API things can become complicated.

Reason for this is because ASP.NET MVC 5 uses interface System.Web.Mvc.IDependencyResolver for implementing dependency resolver and  ASP.NET Web API uses System.Web.Http.Dependencies.IDependencyResolver interface which has the same name but resides in different namespace.

These two interfaces are different, even they have a same name.

Why should you use MVC and Web API in the same project

There could be many reasons for this. For me the main reason was simplifying the way to securing Web API access by implementing session support in ASP.NET Web API even it is not recommended.

This way we can detect request coming from our MVC Application without need to protect API Key and API Secret which we use for mobile access to Web API. Protecting API Key and API Secret on web application can be very complicated.
 
If you want to learn more about ASP.NET Web API I recommend a great book that I love written by real experts:
BookWebAPIEvolvable
Designing Evolvable Web APIs with ASP.NET

Simple implementation

I am usually using Ninject as DI container of my choice. First we need to reference Ninject in our project.

After that we create class called NinjectRegistrations which inherits NinjectModule and will be used for registering types into container.

public class NinjectRegistrations : NinjectModule
    {
        public override void Load()
        {
            Bind<IApiHelper>().To<ApiHelper>();
        }
    }

 

After that we will create class NinjectDependencyResolver that will implement both required interfaces mentioned above:

 public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver, System.Web.Mvc.IDependencyResolver
    {
        private readonly IKernel kernel;

        public NinjectDependencyResolver(IKernel kernel)
            : base(kernel)
        {
            this.kernel = kernel;
        }

        public IDependencyScope BeginScope()
        {
            return new NinjectDependencyScope(this.kernel.BeginBlock());
        }
    }

 

 
We also need to implement class NinjectDependencyScope which is inherited from NinjectDependencyResolver:

    public class NinjectDependencyScope : IDependencyScope
    {
        private IResolutionRoot resolver;

        internal NinjectDependencyScope(IResolutionRoot resolver)
        {
            Contract.Assert(resolver != null);

            this.resolver = resolver;
        }

        public void Dispose()
        {
            var disposable = this.resolver as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }

            this.resolver = null;
        }

        public object GetService(Type serviceType)
        {
            if (this.resolver == null)
            {
                throw new ObjectDisposedException("this", "This scope has already been disposed");
            }

            return this.resolver.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (this.resolver == null)
            {
                throw new ObjectDisposedException("this", "This scope has already been disposed");
            }

            return this.resolver.GetAll(serviceType);
        }
    }

 

That is entire implementation. Usage is very simple. To use the same container in MVC and Web API project we just create Ninject container in Global.asax.cs and pass same Ninject resolver to MVC and Web API.

 
NinjectModule registrations = new NinjectRegistrations();
var kernel = new StandardKernel(registrations);
var ninjectResolver = new NinjectDependencyResolver(kernel);

DependencyResolver.SetResolver(ninjectResolver); // MVC
GlobalConfiguration.Configuration.DependencyResolver = ninjectResolver; // Web API
 

You can use the same method for any kind of DI container not only Ninject.

And if you liked this post, go ahead and subscribe here to my RSS Feed to make sure you don’t miss other content like this.

 
 

The post Simple way to share Dependency Resolvers between MVC and Web API appeared first on RadenkoZec blog.


Darrel Miller: REST Agent - Lessons learned in building generic hypermedia clients

Several years ago when I was beginning to work on a large hyper media driven client, I recognized frequently recurring patterns and decided that I could raise the level of abstraction from an HTTP client to a hypermedia client.  It took about a year to realize that it was not as good an idea as I had first thought.

Mountaintop

Introducing RESTAgent

Four years ago I developed the RESTAgent library, created some samples, wrote some blog posts (an intro, basic usage, and more advanced) to try and make it easier to deal with hypermedia on the client by providing generic support for any hypermedia type.  It was designed to provide two methods for navigating links.  Navigate(Link link) and Embed(Link link).  The returned representation is stored as state in the RESTAgent class.

If the media type was recognized then RESTAgent would parse the content looking for additional links contained in the response.  In order for RESTAgent to know how to construct an HTTP request when following a link, a Link class was developed that would encapsulate all the link attributes defined in RFC5988.  This Link class could then be used to construct a complete HTTP request.

The combination of the Link class, the RESTAgent request generator and pluggable media type parsers allowed RESTAgent to navigate all over a hypermedia API using just a few simple methods.

Abstractions need to make things simpler

The challenge, as I discovered, is that HTTP is an extremely flexible protocol.  There are many different valid ways of dealing with the wide variety of HTTP status codes.  Dealing with client errors, redirects and server errors are all situations where the right solution is, "it depends".  Trying to encapsulate that behaviour inside RESTAgent left me with two choices.  Be opinionated about the behaviour, or build a sophisticated interface to allow users of RESTAgent, to configure or replace the default RESTAgent behaviour. 

lightswitch

Being opinionated about the way HTTP is used is fine for server frameworks, but for a client library you need to be able to accommodate the chosen approaches of all of the APIs that you want to interact with.  Flexibility is a critical feature for clients.

Trying to build a lot of flexibility into an abstraction ends up with a solution just as complex as the thing that you are trying to abstract.  At this point the value that you are adding is negated by requiring people to learn the new abstraction.

Generic content is genericpackage

Another significant limitation of a generic hypermedia client is that the only semantics that it understands are links.  Links can add a huge amount of value to a distributed systems, but it is quite difficult to do useful tasks with only links.  Client applications need some domain semantics to work with.  Having RESTAgent only able to partially handle content ended up creating content being managed in multiple places.  Which is less than ideal.

The Link is where the magic is

Further experimentation showed me that the real value of the RESTAgent library was in the Link abstraction.  It's ability to provide a place to encapsulate the interaction semantics related to a particular link relation type was critical to making dealing with hypermedia easier.

ChainLink

By creating various media type parsers that expose their links using this standardized link class, we can obtain a large amount of the value that was provided by RESTAgent without needing to abstract away the HTTP interface.  My recent efforts in this area have been on building out a more useful Link class.

Managing Client State

The other work that RESTAgent was trying to help with was managing client state.  However, I realized that with a full blown client application there tends to be lots of "mini" client state machines that have different lifetimes and work together to form the complete client application.  I initially described these mini state machines as missions.  They used a single RESTAgent to achieve a goal through a set of client server interactions.  Once I actually formalized the notion of this encapsulating mission into an actual implementation , I decided that the mission itself was a better place to manage state than within the RESTAgent where all state had to be handled generically.  I will write more on the concept of missions in a future post.

My advice

I've seen a few people recently talking about building generic hypermedia clients.  Hopefully, if they read about my experiences, they may avoid making the same mistakes I did, and get a better result.  I would definitely be interested to hear if anyone else is experimenting with concepts similar to Links and Missions.

Photo credit: Chain https://flic.kr/p/3fdHLE
Photo credit: Package https://flic.kr/p/4A15jm
Photo credit: Mountain top https://flic.kr/p/883WpP
Photo credit: Light switch https://flic.kr/p/6mZCc4


Darrel Miller: Composing API responses for maximum reuse with ASP.NET Web API

In Web API 2.1 a new mechanism was introduced for returning HTTP messages that appeared to be a cross between HttpResponseMessage and the ActionResult mechanism from ASP.NET MVC.  At first I wasn't a fan of it at all.  It appeared to add little new value and just provide yet another alternative that would a be a source of confusion.  It wasn't until I saw an example produced by Brad Wilson that I was convinced that it had value.

The technique introduced by Brad was to enable a chain of action results to be created in the controller action method that would then be processed when the upstream framework decided it needed to have an instance of a HttpResponseMessage.

A composable factory

BuildingBlocks

The IHttpActionResult interface is a single asynchronous method that returns a HttpResponseMessage.  It is effectively a HttpResponseMessage factory.  Being able to chain together different implementations of IHttpActionResult allows you to compose the exact behaviour you want in your controller method with re-usable classes.  With a little bit of extensions method syntax sugar you can create controller actions that look like this,

 public IHttpActionResult Get()
        {
            var home = new HomeDocument();

            home.AddResource(TopicsLinkHelper.CreateLink(Request).WithHints());
            home.AddResource(DaysLinkHelper.CreateLink(Request).WithHints());
            home.AddResource(SessionsLinkHelper.CreateLink(Request).WithHints());
            home.AddResource(SpeakersLinkHelper.CreateLink(Request).WithHints());


            return new OkResult(Request)
                .WithCaching(new CacheControlHeaderValue() { MaxAge = new TimeSpan(0, 0, 60) })
                .WithContent(new HomeContent(home));
        }

The OkResult class implements IHttpActionResult and the WithCaching and WithContent build the a chain with other implementations.  This is similar to the way HttpMessageHandler and DelegatingMessageHandler work together.

Apply your policies

In the example above, the CachingActionResult didn’t add a whole lot of value over just setting the CacheControl header directly. However, I think could be a good place to start defining consistent policies across your API.  Consider writing a bit of infrastructure code to allow you to do,

 public IHttpActionResult Get()
 {
          var image = /* ... Get some image */

            return new OkResult(Request)
                .WithCaching(CacingPolicy.Image)
                .WithImageContent(image);
 }

This example is a bit of a thought experiment, however the important point is, you can create standardized, re-usable classes that apply a certain type of processing to a generated HttpResponseMessage.

Dream a little

If I were to let my imagination run wild, I could see all kinds of uses for this methods,

new CreatedResult(Request)
.WithLocation(Uri uri)
.WithContent(HttpContent content)
.WithEtag()

new ServerNotAvailableResult(Request)
.WithRetry(Timespan timespan)
.WithErrorDetail(exception)

new AcceptResult(Request)
.WithStatusMonitor(Uri monitorUrl)

new OkResult(Request)
 .WithNegotiatedContent(object body)
 .WithLastModified(DateTime lastModified)
 .WithCompression()

Some of these methods might be able to be created as completely general purpose “framework level” methods, but I see them more as being able to apply your API standards to controller responses. 

More testable

One significant advantage of using this approach over using ActionFilter attributes is that when unit testing your controllers, you will be able to test the effect of the ActionResult chain.  With ActionFilter attributes, you need to create an in-memory host to get the full framework infrastructure support in order for the ActionFilter objects to execute.

Another advantage of this approach over action filters for defining action-level behaviour is that by constructing the chain, you have explicit over the order in which the changes are applied to your response. 

More reusable

It may also be possible to take the abstraction one step further and create a factory for pre defined chains.  If the same sets of behaviour are applicable to many different actions then you can create those chains in one place and re-use a factory method.  This can be useful in controllers where there are a variety of different overloads of a method that take different parameters, but the response is always constructed in a similar way.   The method for creating the action result chain can be in the controller itself.

The implementation

The CachingResult class looks like this,

public class CachingResult : IHttpActionResult
    {
        private readonly IHttpActionResult _actionResult;
        private readonly CacheControlHeaderValue _cachingHeaderValue;


        public CachingResult(IHttpActionResult actionResult, CacheControlHeaderValue cachingHeaderValue)
        {
            _actionResult = actionResult;
            _cachingHeaderValue = cachingHeaderValue;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {

            return _actionResult.ExecuteAsync(cancellationToken)
                .ContinueWith(t =>
                {
                    t.Result.Headers.CacheControl = _cachingHeaderValue;
                    return t.Result;
                }, cancellationToken);
        }
    }

and the extension method is simply,

  public static IHttpActionResult WithCaching(this IHttpActionResult actionResult, CacheControlHeaderValue cacheControl)
  {
            return new CachingResult(actionResult, cacheControl);
  }

A more refined implementation might be to create an abstract base class that takes care of the common housekeeping.  It can also take care of actually instantiating a default HttpResponseMessage if the ActionResult is at the end of the chain.  Something like this,

public abstract class BaseChainedResult : IHttpActionResult
    {
        private readonly IHttpActionResult _NextActionResult;

        protected BaseChainedResult(IHttpActionResult actionResult)
        {
            _NextActionResult = actionResult;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            if (_NextActionResult == null)
            {
                var response = new HttpResponseMessage();
                ApplyAction(response);
                return Task.FromResult(response);
            }
            else
            {

                return _NextActionResult.ExecuteAsync(cancellationToken)
                    .ContinueWith(t =>
                    {
                        var response = t.Result;
                        ApplyAction(response);
                        return response;
                    }, cancellationToken);
            }
        }

        public abstract void ApplyAction(HttpResponseMessage response);
    
    }

A more complete usage example

If you are interested in seeing these classes in use in a complete project you can take a look at the Conference API project on Github.

Image credit: Building blocks https://flic.kr/p/4r9zSK


Darrel Miller: An HTTP Resource is a lot simpler than you might think

Unfortunately, I still regularly run into articles on the web that misunderstand the concept of an HTTP resource.  Considering it is a core piece of web architecture, having a clear understanding of what it means can make many other pieces of web architectural guidance considerably easier to understand.

To try and keep this post as practical as possible, let’s first consider some URLs.

http://customers example.org/10 
http://example.org/customers?id=10 
http://example.org/customers 
http://example.org/customers?active=true 
http://example.org/customers/10/edit

How many resources are being identified by these five URLs? 

DogTags

If all of those requests return some kind of 2XX response, then there are five distinct information resources.  The presence of query strings parameters, or path parameters, or verbs or nouns, or plurals or singular terms, has no bearing on the fact that that these are distinct web identifiers that identify distinct resources. 

Time to set the record straight

Let me give a few examples that seem to confuse people:

Resources > Entities

Another common misconception is that resources are limited to exposing entities from your application domain.  Here are some examples of resources that are perfectly valid despite what you might read on the internet:

http://example.org/dashboard
http://example.org/printer 
http://example.org/barcodeprocessor
http://example.org/invoice/32/status 
http://example.org/searchform
http://example.org/calculator

It’s very simple

A resource is some piece of information that is exposed on the web using an URL as an identifier.  Try not to read anything more into the definition than that. 


Radenko Zec: Simple way to implement caching in ASP.NET Web API

This article is not about caching the output of APIControllers.
Often in ASP.NET Web API you will have a need to cache something temporarily in memory probably to improve performance.

There are several nice libraries that allow you to do just that.

One very popular is CacheCow and here you will find a very nice article how to use this library.

But what if you want to do caching without third party library in a very simple way?
 
If you want to learn more about ASP.NET Web API I recommend a great book that I love written by real experts:
 
BookWebAPIEvolvable
Designing Evolvable Web APIs with ASP.NET 

Caching without third party library in a very simple way

I had a need for this. I implemented some basic authentication for the ASP.NET Web API with Tokens and wanted to cache Tokens temporarily in memory to avoid going into the database for every HTTP request.

The solution is very simple.
You just need to use Microsoft class for this called MemoryCache which resides in System.Runtime.Caching dll.

 

I created a simple helper class for caching with few lines of code:

 

public class MemoryCacher
{
  public object GetValue(string key)
  {
    MemoryCache memoryCache = MemoryCache.Default;
    return memoryCache.Get(key);
  }

  public bool Add(string key, object value, DateTimeOffset absExpiration)
  {
    MemoryCache memoryCache = MemoryCache.Default;
    return memoryCache.Add(key, value, absExpiration);
  }

  public void Delete(string key)
  {
    MemoryCache memoryCache = MemoryCache.Default;
    if (memoryCache.Contains(key))
    {
       memoryCache.Remove(key);
    }
  }
}

When you want to cache something:

memCacher.Add(token, userId, DateTimeOffset.UtcNow.AddHours(1));

 

And to get something from the cache:

var result = memCacher.GetValue(token);

 

 
NOTE: You should be aware that MemoryCache will be disposed every time IIS do app pool recycle.

If your Web API :

  • Does not receive any request for more that 20 minutes
  • Or hit default IIS pool interval 1740 minutes
  • Or you copy a new version of your ASP.NET Web API project into an IIS folder (this will auto-trigger app pool recycle)

So you should have a workaround for this. If you don’t get value from the cache you should grab it for example from a database and then store it again in the cache:

 

 var result = memCacher.GetValue(token);
 if (result == null)
 {
     // for example get token from database and put grabbed token
     // again in memCacher Cache
 }

 

And if you liked this post, go ahead and subscribe here to my RSS Feed to make sure you don’t miss other content like this.

 
 

The post Simple way to implement caching in ASP.NET Web API appeared first on RadenkoZec blog.


Radenko Zec: ASP.NET Web API GZip compression ActionFilter with 8 lines of code

If you are building high performance applications that consumes WebAPI, you often need to enable GZip / Deflate compression on Web API.

Compression is an easy way to reduce the size of packages and in the same time increase the speed of communication between client and server.

Two common algorithms used to perform this on the Web are GZip and Deflate. These two algorithms are recognized by all web browsers and all GZip and Deflate HTTP responses are automatically decompressed.

On this picture you can see the benefits of GZip compression.

 

compression

Source : Effects of GZip compression

How to implement compression on ASP.NET Web API

There are several ways to do this. One is to do it on IIS level. This way all responses from ASP.NET Web API will be compressed.

Another way is to implement custom delegating handler to do this. I have found several examples of how to do this on the internet but it often requires to write a lot of code.

The third way is to implement your own actionFilter which can be used on method level, controller level or for entire WebAPI.
 

 

Implement ASP.NET Web API GZip compression ActionFilter

For this example with around 8 lines of code I will use very popular library for Compression / Decompression called DotNetZip library .This library can easily be downloaded from NuGet.

Now we implement  Deflate compression ActionFilter.

 public class DeflateCompressionAttribute : ActionFilterAttribute
 {

    public override void OnActionExecuted(HttpActionExecutedContext actContext)
    {
        var content = actContext.Response.Content;
        var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;
        var zlibbedContent = bytes == null ? new byte[0] : 
        CompressionHelper.DeflateByte(bytes);
        actContext.Response.Content = new ByteArrayContent(zlibbedContent);
        actContext.Response.Content.Headers.Remove("Content-Type");
        actContext.Response.Content.Headers.Add("Content-encoding", "deflate");
        actContext.Response.Content.Headers.Add("Content-Type","application/json");
        base.OnActionExecuted(actContext);
      }
  }

 

We also need a helper class to perform compression.

public class CompressionHelper
{ 
        public static byte[] DeflateByte(byte[] str)
        {
            if (str == null)
            {
                return null;
            }

            using (var output = new MemoryStream())
            {
                using (
                    var compressor = new Ionic.Zlib.DeflateStream(
                    output, Ionic.Zlib.CompressionMode.Compress, 
                    Ionic.Zlib.CompressionLevel.BestSpeed))
                {
                    compressor.Write(str, 0, str.Length);
                }

                return output.ToArray();
            }
        }
}

 

For GZipCompressionAttribute implementation is exactly the same. You only need to call GZipStream instead of DeflateStream in helper method implementation.

If we want to mark some method in controller to be Deflated just put this ActionFilter attribute above method like this :

public class V1Controller : ApiController
{
  
    [DeflateCompression]
    public HttpResponseMessage GetCustomers()
    {

    }

}

 

If you find some better way to perform this please let me know.

 

The post ASP.NET Web API GZip compression ActionFilter with 8 lines of code appeared first on RadenkoZec blog.


Darrel Miller: Single purpose media types and reusability

The one great thing about twitter is that you quickly find out what you failed to explain clearly :-)  My efforts in advocating for single purpose media types failed to clarify that by single purpose, I am not suggesting that these media types should not be re-usable.  Let me try and explain.

My realization was triggered by @inadarai 's tweet to me,

I'm going to take the liberty of assuming that this tweet was slightly tongue-in-cheek.  However, it did highlight to me the part of my explanation that I was missing.

It is a whacky world out there

For those who have better things to do than keep up with daily craziness in Silicon Valley, the significance of this image may not be immediately apparent.  A new start-up called Yo is making the news with an application that simply sends the message "Yo" to someone in your social network.  The joke of this tweeted image is that many people are likely to copy this idea and we will have many apps on our phone where each one will send just a single one word message.

My response to @inadarei included these two tweets,

Although still not a particularly serious suggestion, the example is extremely illustrative.  By single purpose media types, I am not suggesting that each and every API should invent media types that are designed to solve just their specific problems.  It is critical to realize that media types should be targeted to solve a single generic problem that is faced by many APIs.  It is only by doing this can we achieve the level of re-usability and interoperability that make the web successful.

Generalize the problem

By generalizing our problem space to the notion of a "salutation" we can define a single hypothetical media type and name it application/salutation+json.

To satisfy the functional requirements of an application that simply displays a single word message to an end user, all we need is a payload that looks something like:

{
   "message" : "Yo"
}

This media type could then be delivered by any API that wishes to transmit a single word message.  Now that the message has been generalized, there is no need to have a different client for each API.  In the same way that RSS feeds allowed us to use one client application to consume blog posts from many different blogs, so our salutation media type enables just a single client application for all APIs that support the format.

But that was a dumb example

Let me provide a more realistic scenario.   For many years I've been building ERP systems and for the last 7 years I've been working on a building an ERP API that uses media types and link relations to communicate information to a desktop client application.  For a period of time, I considered inventing my own media types for Invoices, Sales orders, Customers, Purchase Orders, etc, etc.  However, I quickly realized that the overhead of creating written specifications for the 500 or so entities that were in our ERP product  would be a mammoth and very painful task.  I would also never likely see any re-use out of those media types.  It is highly unlikely that I could convince any other ERP vendor that they should re-use our Invoice format as it would likely contain many capabilities that were specific to our API, and I'm sure they would believe that their format is better!

Don't those standards already exist?

As an industry we have tried on numerous occasions to create universal standards for interchange of business documents.  (e.g Edifact, ANSI X12, UBL).  None of these efforts have come close to having the adoption like HTML has, despite having massive amounts of money poured into convincing people to adopt them.

The problem with these previous efforts is they tried to bite off a bigger problem than they could chew.  In order to manage the size of problem they were trying to address, they first invented a meta-format and then applied schemas to that format to produce consistent documents for each business scenario.  The result was horribly complicated, with a huge barrier to entry.  If you don't believe me, here is the list of fields used by a UBL invoice.

Be less ambitious

Now imagine a much simpler scenario for just invoicing information.  Imagine if we could agree on a simple read-only format containing invoice information.  If services like Amazon, NewEgg, Staples, Zappos, etc, could expose their invoice information in this shared format, as well as the normal HTML and PDF, then this new format could then be consumed easily by services like Expensify, Mint, Quicken and what ever other services might help you manage your finances.   This scenario would be an achievable goal in my opinion and one that could quickly deliver real value.

Profiles can do that

There is no theoretical reason why this same goal could not be achieved by using generic hypermedia types and profiles .  However, you could now have the situation where Amazon likes using Hal, Staples decide on Siren for their company standard and NewEgg chose JSON-LD.  The theory of profiles, as I understand it, is that everyone should be able to consistently apply the same "invoice" profile across multiple base generic media types.  However, the consumers like Expensify and Mint are now faced with dealing with all these different base formats combined with profiles.  This seems like a significant amount of complexity for minimal gain.

But what about exploding media types

A common objection to creating media types that have a limited scope is the fear of "an explosion of media types".  The main concern here is multiple people creating media types that address the same purpose but have trivial differences.  Having one invoice format that has a property called "InvoiceDate" and another that has "dateInvoiced" is really not helping anyone. 

bigbang

Ironically, the competing generic hypermedia types that were partly a result of people trying to avoid creating an explosion of media types are now suffering from the "trivially different" problem.  Also, it is quite likely that the wide usage of schemas and profiles will suffer from APIs defining their own variants of semantically similar documents.

The important goal

Regardless of whether developers choose to use single purpose media types or generic hypermedia types with profiles, it is essential that we focus on creating artifacts that can be re-used across multiple APIs to enable sharing and integration that is "web scale".

Image Credit: Big bang https://flic.kr/p/cS8Hed 


Dominick Baier: Resource/Action based Authorization for OWIN (and MVC and Web API)

Authorization is hard – much harder than authentication because it is so application specific. Microsoft went through several iterations of authorization plumbing in .NET, e.g. PrincipalPermission, IsInRole, Authorization configuration element and AuthorizeAttribute. All of the above are horrible approaches and bad style since they encourage you to mix business and authorization logic (aka role names inside your business code).

WIF’s ClaimsPrincipalPermission and ClaimsAuthorizationManager tried to provide better separation of concerns – while this was a step in the right direction, the implementation was “sub-optimal” – based on a CLR permission attribute, exception based, no async, bad for unit testing etc…

In the past Brock and me worked on more modern versions that integrate nicer with frameworks like Web API and MVC, but with the advent of OWIN/Katana there was a chance to start over…

Resource Authorization Manager & Context
We are mimicking the WIF resource/action based authorization approach – which proved to be general enough to build your own logic on top. We removed the dependency on System.IdentityModel and made the interface async (since you probably will need to do I/O at some point). This is the place where you will centralize your authorization policy:

public interface IResourceAuthorizationManager

{

    Task<bool> CheckAccessAsync(ResourceAuthorizationContext context);

}

 

(there is also a ResourceAuthorizationManager base class with some easy to use helpers for returning true/false and evaluations)

The context allows you to describe the actions and resources as lists of claims:

public class ResourceAuthorizationContext
{
    public IEnumerable<Claim> Action { get; set; }
    public IEnumerable<Claim> Resource { get; set; }
    public ClaimsPrincipal Principal { get; set; }
}

 

Middleware
The corresponding middleware makes the authorization manager available in the OWIN enviroment:

public void Configuration(IAppBuilder app)
{
    var cookie = new CookieAuthenticationOptions
    {
        AuthenticationType = "Cookie",
        ExpireTimeSpan = TimeSpan.FromMinutes(20),
        LoginPath = new PathString("/Login"),
    };
    app.UseCookieAuthentication(cookie);
 
    app.UseResourceAuthorization(new ChinookAuthorization());
}

 

Usage
Since the authorization manager is now available from the environment (key: idm:resourceAuthorizationManager) you can get ahold of it from anywhere in the pipeline, construct the context and call the CheckAccessAsync method.

The Web API and MVC integration packages provide a ResourceAuthorize attribute for declarative checks:

[ResourceAuthorize(ChinookResources.AlbumActions.View, ChinookResources.Album)]

 

And several extension methods for HttpContextBase and HttpRequestMessage, e.g.:

if (!HttpContext.CheckAccess(
    ChinookResources.AlbumActions.Edit,
    ChinookResources.Album,
    id.ToString()))
{
    return new HttpUnauthorizedResult();
}

 

or..

var result = Request.CheckAccess(
    ChinookResources.AlbumActions.Edit,
    ChinookResources.Album,
    id.ToString());

 

Testing authorization policy
Separating authorization policy from controllers and business logic is a good thing, centralizing the policy into a single place also has the nice benefit that you can now write unit tests against your authorization rules, e.g.:

[TestMethod]
public void Authenticated_Admin_Can_Edit_Album()
{
    var ctx = new ResourceAuthorizationContext(User("test", "Admin"),
        ChinookResources.AlbumActions.Edit,
        ChinookResources.Album);
    Assert.IsTrue(subject.CheckAccessAsync(ctx).Result);
}

 

or…

[TestMethod]
public void Authenticated_Manager_Cannot_Edit_Track()
{
    var ctx = new ResourceAuthorizationContext(User("test", "Manager"),
        ChinookResources.TrackActions.Edit,
        ChinookResources.Track);
    Assert.IsFalse(subject.CheckAccessAsync(ctx).Result);
}

 

Code, Samples, Nuget
The authorization manager, context, middleware and integration packages are part of Thinktecture.IdentityModel – see here.

The corresponding Nuget packages are:

..and here’s a sample using MVC (if anyone wants to add a Web API to it – send me a PR).


Filed under: ASP.NET, IdentityModel, Katana, OWIN, WebAPI


Darrel Miller: Single purpose media types and caching

My recent post asking people to refrain from creating more generic hypermedia types sparked some good conversation on twitter between @mamund, @cometaj2, @mogsie, @inadarei and others.  Whilst thinking some more on the potential benefits of single purpose media types versus generic hypermedia types, realized there is a correlation between single purpose media types and representation lifetimes.  I thought it might be worth adding to the conversation, but there is no way I could fit it in 140 chars, so I’m posting it here.

Age matters

When I say representation lifetime, I am referring to how long a representation can be considered to be still fresh, from the perspective of caching.   The lifetime of a representation can be explicitly defined by either setting the Expires header or by setting the max-age parameter of the cache-control header.  If neither of these values are set then a client can choose to use heuristics to determine how long the response could still be fresh for.

BestBeforeDateWhen using Single purpose media types, those types often hint at representations that should have different lifetimes.  If you are building an HTML dashboard that contains images of charts showing KPIs (key performance indicators), then the HTML will likely have a much longer lifetime than that of the images.

However, if you are building a dynamic HTML application, then the HTML is likely to have a shorter lifespan than the images displayed on it.  Media types that provide metadata like CSS, or API discovery documents are likely to have long lifetimes, whereas media types that display status information are likely to be very short lived.

Hints for client heuristics

When I was reading the specification for apisjson I noticed that they had explicitly added a clause to say that if no lifetime information was provided then a lifetime of 7 days would be an appropriate value.  I think the idea of a media type specification explicitly stating suggested lifetime values is very interesting.  When chatting with Steven Wilmott at API Craft Meetup SF he mentioned that they had got the idea from the standard convention of caching robots.txt for 24 hours. 

Just a thought

As I mentioned, this is simply an overly long tweet, rather than a blog post.  Nothing ground breaking, but I find that developers often forget about the value of setting caching headers.  If media type designers can provide guidance on what appropriate values might be then developers might pay a little more attention and the Internet might just get a little faster.

Image Credit: Best before date https://flic.kr/p/6MAMum


Darrel Miller: XSLT is easy, even for transforming JSON!

Most developers I talk to will cringe if they hear the acronym XSLT.  I suspect that reaction is derived from some past experience where they have seen some horrendously complex XML/XSLT combination.  There is certainly lots of that around. However, for certain types of document transformations, XSLT can be a very handy tool and with the right approach, and as long as you avoid edge cases, it can be fairly easy.

When I start building an XSLT transform, I always start with the “identity” transform,

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" indent="yes" />
<xsl:template match="/ | @* | node()"> <xsl:copy> <xsl:apply-templates select="* | @* | node()" /> </xsl:copy> </xsl:template>
</xsl:stylesheet>

OptimusPrimeThe identity transform simply traverses the nodes in the input document and copies them into the output document.

Make some changes

In order to make changes to the output document you need to add templates that will do something other than simply copy the existing node.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
   
<xsl:output method="xml" indent="yes" />
<xsl:template match="/ | @* | node()"> <xsl:copy> <xsl:apply-templates select="* | @* | node()" /> </xsl:copy> </xsl:template>
<!-- Change something --> <xsl:template match="foo"> <xsl:element name="bar"> <xsl:apply-templates select="* | @* | node()" /> </xsl:element> </xsl:template>
</xsl:stylesheet>

This template matches on any element named foo and in it’s place creates an element named bar that contains a copy of everything that foo contained.  XSLT will always use the template that matches most specifically.

Given the above XSLT, an input XML document like this,

<baz>  
    <foo value=”10text=”Hello World/>
</baz>

would be transformed into

<baz>
     <bar value=”10text=”Hello World/>
</baz>

And add more changes…

The advantage of XSLT over doing transformations in imperative code, is that adding more transformations to the document doesn’t make the XSLT more complex, just longer. For example, I could move the foo element inside another element by adding a new matching template.  The original parts of the template stay unchanged. 

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
        <xsl:output method="xml" indent="yes" />

        <xsl:template match="/ | @* | node()">
            <xsl:copy>
                <xsl:apply-templates select="* | @* | node()" />
           </xsl:copy>
        </xsl:template>

        <xsl:template match="foo">
           <xsl:element name="bar">
                <xsl:apply-templates select="* | @* | node()" />
           </xsl:element>
        </xsl:template>

        <!-- Additional template that does not change previous -->
        <xsl:template match="baz">
            <xsl:element name="splitz">
               <xsl:copy>
                 <xsl:apply-templates select="* | @* | node()" />
              </xsl:copy>
            </xsl:element>
        </xsl:template>

</xsl:stylesheet>

With imperative code, adding additional transformations often requires doing refactoring of existing code.  Due to XSLT being from a more functional/declarative heritage, it tends to stay cleaner when you add more to it.

Just because I can…

And for those of you love JSON too much to ever go near XSLT, below is some sample code that takes a JSON version of my sample document and applies the XSLT transform to it using the XML support in JSON.NET.

Starting with this JSON

{
    "baz": {
        "foo": {
            "value": "10",
            "text": "HelloWorld"
        }
    }
}

we end up with

{
    "splitz": {
        "baz": {
            "bar": {
                "value": "10",
                "text": "Hello World"
            }
        }
    }
}

Here’s the code I used to do this.  Please don’t take this suggestion too seriously.  I suspect the performance of this approach would be pretty horrific.  However, if you have a big chunk of JSON that you need to do a complex, offline transformation on, it might just prove useful.

var jdoc = JObject.Parse("{ 'baz' : { 'foo' : { 'value' : '10', 'text' : 'Hello World' } }}");
            
// Convert Json to XML
var doc = (XmlDocument)JsonConvert.DeserializeXmlNode(jdoc.ToString());

// Create XML document containing Xslt Transform
var transform = new XmlDocument();
transform.LoadXml(@"<?xml version='1.0' encoding='utf-8'?>
                    <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' >
                        <xsl:output method='xml' indent='yes' omit-xml-declaration='yes' />

                        <xsl:template match='/ | @* | node()'>
                            <xsl:copy>
                                <xsl:apply-templates select='* | @* | node()' />
                            </xsl:copy>
                        </xsl:template>

                        <xsl:template match='foo'>
                            <xsl:element name='bar'>
                                <xsl:apply-templates select='* | @* | node()' />
                            </xsl:element>
                        </xsl:template>
                        <xsl:template match='baz'>  
                            <xsl:element name='splitz'>
                                <xsl:copy>
                                    <xsl:apply-templates select='* | @* | node()' />
                                </xsl:copy>
                        </xsl:element></xsl:template>
                    </xsl:stylesheet>");

//Create compiled transform object that will actually do the transform.
var xslt = new XslCompiledTransform();
xslt.Load(transform.CreateNavigator());

// Transform our Xml-ified JSON
var outputDocument = new XmlDocument();
var stream = new MemoryStream();
xslt.Transform(doc, null, stream);
stream.Position = 0;
outputDocument.Load(stream);

// Convert back to JSON :-)
string jsonText = JsonConvert.SerializeXmlNode(outputDocument);

Duck-billed Platypus

Image credit: Transformer https://flic.kr/p/2LK2ph
Image credit: Platypus https://flic.kr/p/8tYptD


Darrel Miller: Please, no more generic hypermedia types

This opinion has been stewing for a couple of years now, but following an excellent conversation I had with Ted Young the other evening at the API Craft San Francisco event, I think it is time to have more discussion around this subject.

A little bit of history

I have been a big supporter of the HAL media type ever since Mike Kelly showed me his first sample on the freenode #REST IRC channel. I actively pushed for the use of HAL within several teams at Microsoft and a number of other large corporations. I saw HAL as an opportunity to introduce people to hypermedia using a simple, flexible, standardized format.  HAL has its flaws, but it served my purpose.

Since HAL was introduced, a number of other hypermedia types have been created, including Collection+JSON, Siren, JSON-LD, JsonAPI, Mason, UBER, OData and probably a few others that I have forgotten.

I think it is excellent that there is experimentation going on in this area. Much of this work can be used as the basis for future media type designs. The more people who have experience creating media types the better. However, there is a trend emerging where we are repeatedly creating general purpose hypermedia types that attempt to provide a single solution for all the resources in a API.

VanillaIceCream

What's the problem?

Developers who wish to build a hypermedia API are now required to make a decision up front on whether they want to use HAL, or Siren, or Mason, or JSON-LD, or OData, or UBER. All these designs are only incrementally different than each other and simply reflect the preferences and priorities of their authors.

The fragmentation of our already fairly small community of developers who are using hypermedia formats is really not helping us advance the adoption of hypermedia. Additionally, by trying to build hypermedia types that are sufficiently generic to support a wide range of use-cases, we have been forced to introduce secondary mechanisms to convey application semantics. Once a developer has chosen a hypermedia format, they must now choose a profile format, or a schema language, or create extension link relations in order to communicate the remainder of the semantics that the general purpose hypermedia formats do not support.

IceCreamChoices

I intentionally left Collection+JSON out of the list of competing media types because I see C+J as different, as it was designed to represent a simple lists of things. This a very focused goal and yet one that almost every application has the need for.

So what does work?

I realize that this example is going to turn off many people, but there is an elephant in the room that we just can't continue to ignore. The human web is built around a fairly small set of media types that have narrowly focused goals.

  • text/html provides read-only textual content to be presented to an end user.
  • application/x-www-form-urlencoded provides a way of transmitting user input to an origin server.
  • text/css provides hints to the user-agent on how to render the content of the HTML document.
  • image/(png|jpeg|gif) provides bitmap based images
  • image/svg provides vector based images
  • application/javascript provides source code for client side scripts

It is the combination of these narrowly focused media types that enable web applications to produce a huge variety of user experiences.

The UNIX philosophy

In my opinion the best media types are the ones that are designed to solve a single problem, solve it well and then allow the combination of those media types. This allows the media type to remain fairly simple. Simple to create, simple to parse and simple to replace if a better format comes along. It is also easier to support multiple similar formats. The web only supports one text/html format, but it supports several image formats.

IceCreamToppings

Examples of potential media types

During my years of building hypermedia based systems, I have run into many situations that would have benefited from having specialized media types. Here are some examples:

  • Discovery document : An entry point document that allows a client to discover other resources that exist within a system. e.g json-home
  • List of things : A tabular list of pieces of data. e.g. Collection+Json, text/csv
  • Data entry form : A representation of a set of data elements that have types, constraints, validation rules, intended for capturing information from the user. e.g. HTML forms are a very primitive example
  • Captured event stream : A sequence of events captured by a client application potentially used for replaying on some remote system. e.g. ActivityStreams, Json-patch
  • Error document : document used for reporting errors resulting from a HTTP Request. e.g. http-problem, vnd.error+(xml|json)
  • Operation Status document : Document which describes the current status of a long running operation. application/status+(xml|json)
  • Banded Report document : Representation of the set of data used by report writing tools to generate printed reports
  • Query description : Query language that selects and filters a subset of data e.g. application/sql, application/opensearchdescription+xml
  • Datapoints : for driving dashboard widgets and graphs
  • Security permissions management : tasks, claims, users
  • Patch format : Apply a delta set of updates to a target resource Json-patch Sundae

Call to action

I'd like to see those developers who do have experience building hypermedia types working on these kinds of focused media types instead of creating competing, one-size-fits-all formats.
I'd like to see widget and component developers building native support for consuming these specialized media types.
I'd like to see more application developers identifying opportunities for creating these specialized media types.
I'd like to see API Commons filled with a wide variety of media type specifications that I can pick and choose as building blocks for building my API.

I want to have a future where I can expose my data in a standardized format and then simply connect hypermedia enabled client components that will consume those formats. Now that would improve productivity.

That's my opinion, I'd love to hear yours.

Image Credit: Vanilla Ice cream https://flic.kr/p/9JyfVG
Image Credit: Sundae https://flic.kr/p/3aK9TU
Image Credit: Toppings https://flic.kr/p/fuY7GZ


Darrel Miller: Self-descriptive, isn't. Don't assume anything.

With the recent surge of interest in hypermedia APIs I am beginning to see the term “self-descriptive” thrown around quite frequently.  Unfortunately, the meaning of self-descriptive is not exactly self-descriptive, leading to misuse of the term. 

Consider the following HTTP requests,

Example 1:

GET /address/99
=> 200 OK
Content-Type: application/json
Content-Length: 508

{
"_meta" : {
	"street" : { 	"type" : "string", 
		     	"length" : 80, 
		     	"description" : "Street address"},
	"city" :   { 	"type" : "string", 
		     	"length" : 20, 
		     	"description" : "City name"},
	"postcode" : { 	"type" : "string", 
		       	"length" : 11, 
		       	"description" : "Postal Code / Zip Code"},
	"country" : {	"type" : "string", 
			"length" : 15, 
			"description" : "Country name"},
	},
"address" : {
	"street" : "1 youville way",
	"city" : "Mysteryville",
	"postcode" : "H3P 2Z9",
	"country" : "Canada"
	}
}


Example 2:

GET /address/99
=> 200 OK
Content-Type: application/vnd.gabba.berg
Content-Length: 90

<berg>
   <blurp filk="iggy">ababa</blurb>
   <bop>
      <bip>yerk</bip>
     </bop>
  <berg>


I suspect a fair number of people will be surprised when I make the claim that from the perspective of self-descriptive HTTP messages, the first message is not self-descriptive and the second one is. 

The first may contain more descriptive content, but it doesn't use the standardized methods provided to us by HTTP to identify the semantics of the content.  The client is forced to make assumptions.  The second one is explicit about identifying the meaning of the payload.

Nametag

Identify yourself

Self-descriptive in HTTP does not mean the message describes itself.  It means that the message depends on semantic identifiers, using mechanisms defined by HTTP (e.g. media-types and link relations) to convey the complete meaning of the message. This allows client application to know whether it can understand the incoming message. 

The first example contains all kinds of metadata which attempts to describe the actual data in the message.  However, how can the client know if it is able to interpret the metadata?   It reminds me of the first French language course I took in Quebec, where the teacher started providing instruction in French!  Fortunately, humans are pretty intelligent creatures, software applications, not so much. 

Declare your semantics

In example 1, the media type in the content type header is declared as "application/json".  Unfortunately that tells me nothing about the meaning of the information in the message body.  The client can process the content as JSON, but the message is telling it nothing else about the meaning of the message.  Allowing a client to assume that because you have retrieved the representation from /address/99 that the response will contain information about an address is a violation of the self-descriptive constraint.

Why yes, I do speak Klingon

In example 2, which at first glance appears completely unintelligible to a developer, provides a media type, which, in theory, should be registered with IANA and therefore I should be able to find a written specification that explains what all those weird attributes and elements mean.  Once I have read the specification, I can write code in my client application to be able to process content that is identified as "application/vnd.gabba.berg". 

There is no magic

I get the impression that some developers perceive hypermedia and self-descriptiveness as some magical property that will allow clients to perform tasks that they previously had no idea how to do. 

A client can only process media types it understands.  A web browser knows how to render HTML, follow links, fill forms and run script.  The browser is completely ignorant of the fact that one HTML page might be doing banking transactions and another submitting an order for a year's supply of Shamwow products. 

The effect might be magical, but the reality is that the hypermedia driven clients can only do exactly what they have been coded to do. 

 

Image credit: Name tag https://flic.kr/p/27Y1J9


Ali Kheyrollahi: BeeHive Series - Part 3: BeeHive 0.5, RabbitMQ and more

Level [T4]

BeeHive is a friction-free library to do Reactor Cloud Actors - effortlessly. It defines abstractions for the message, queue and the actors and all you have to do is to define your actors and connect their dots using subscriptions. If it is the first time you read about BeeHive, you could have a look at previous posts but basically a BeeHive Actor (technically Processor Actor) is very simple:

[ActorDescription("TopicName-SubscriptionName")]
public class MyActor : IProcessorActor
{
public Task<IEnumerable<Event>> ProcessAsync(Event evnt)
{
// impl
}
}
All you do is to consume a message, do some work and then return typically one, sometimes zero and rarely many events back.
A few key things to note here.

Event

First of all Event, is an immutable, unique and timestamped message which documents a significant business event. It has a string body which normally is a JSON serialisation of actual message object - but it does not have to be.

So usually messages are arbitrary bytes, why here it is a string? While it was possible to use byte[], if you need to send binary blobs or you need custom serialisation, you are probably doing something wrong. Bear in mind, BeeHive is targeted at solutions that require scale, High Availability and linearisation. If you need to attach a big binary blob, just drop it in a key value store using IKeyValueStore and put the link in your message. If it is small, use Base64 encoding. Also your messages need to very simple DTOs (and by simple I do not mean small, but a class with getters and setters), if you are having problem serialising them then again, you are doing something wrong.

Queue naming

BeeHive uses a naming conventional for queues, topics and subscriptions. Basically it is in the format of TopicName-SubscriptionName. So there are a few rules with this:
  • Understandably, TopicName or SubscriptionName should not contain hyphens
  • If the value of TopicName and SubscriptionName is the same, it is a simple queue and not a publish-subscribe queue. For example, "OrderArrived-OrderArrived"
  • If you leave off the SubscriptionName then you are referring to the topic. For example "OrderArrived-".
Queue name is represented by the class QueueName. If you need to construct queue names using static methods:

var n1 = QueueName.FromSimpleQueueName("SimpleQ"); // "SimpleQ-SimpleQ"
var n2 = QueueName.FromTopicName("Topic"); // "Topic-"
var n3 = QueueName.FromTopicAndSubscriptionName("topic", "Sub"); // "Topic-Sub"

There is a QueueName property on the Event class. This property defines where to send the event message. The queue name must be the name of the topic or simple queue name.

IEventQueueOperator

This interface got some make over in this release. I have not been happy the interface as it had some inconsistencies - especially in terms of creating . Thanks to Adam Hathcock who reminded me, now this is done.

With QueueName ability of differentiating topics and simple queue, this value needs to be either name of the simple queue (in the example above "SimpleQ") or the conventional topic name (in the example above "Topic-").

So here is the interface(s) as it stands now:

public interface ISubscriptionOperator<T>
{
Task<PollerResult<T>> NextAsync(QueueName name);
Task AbandonAsync(T message);
Task CommitAsync(T message);
Task DeferAsync(T message, TimeSpan howLong);
}

public interface ITopicOperator<T>
{
Task PushAsync(T message);
Task PushBatchAsync(IEnumerable<T> messages);
}

public interface IQueueOperator<T> : ITopicOperator<T>, ISubscriptionOperator<T>
{
Task CreateQueueAsync(QueueName name);
Task DeleteQueueAsync(QueueName name);
Task<bool> QueueExists(QueueName name);
}

public interface IEventQueueOperator : IQueueOperator<Event>
{
}
Main changes were made to IQueueOperator<T> passing the QueueName which made it simpler.

RabbitMQ Roadmap

BeeHive targets cloud frameworks. IEventQueueOperator and main data structures have been implemented for Azure. Next is AWS.

Amazon Web Services (AWS) provides Simple Queue Service (SQS) which only supports simple send-receive scenarios and not Publish-Subscribe cases. With this in mind, it is most likely that other message brokers will be used although a custom implementation of pub-sub based on Simple Notification Service (SNS) has been reported. Considering RabbitMQ is by far the most popular message broker out there (is it not?) it is sensible to pick this implementation first.

RabbitMQ client for .NET has a very simple API and working with it is very easy. However, the connection implementation has a lot to be desired. EasyNetQ has a sophisticated connection implementation that covers dead connection refreshes and catering for round-robin in case of High-Availability scenario. Using a full framework to just the connection is not really an option hence I need to implement something similar.

So for now, I am realising an alpha version without the HA and connection refresh to get community feedback. So please do ping me what you think.

Since this is a pre-release, you need to use -Pre to get it installed:

PM> Install-Package BeeHive.RabbitMQ -Pre


Dominick Baier: DotNetRocks on OpenID Connect with Brock and Me

Recorded at NDC Oslo:

http://www.dotnetrocks.com/default.aspx?ShowNum=993


Filed under: Conferences & Training, IdentityServer, OAuth, OpenID Connect, OWIN, WebAPI


Dominick Baier: NDC Oslo 2014 Slides, Samples and Videos

As always – NDC was a great conference! Here’s the list of resources relevant to my talks:

IdentityServer v3 preview: github

Web API Access Control & Authorization: slides / video

OpenID Connect: slides / video

 


Filed under: ASP.NET, Conferences & Training, IdentityServer, OAuth, OpenID Connect, WebAPI


Henrik F. Nielsen: Fresh Updates to Azure Mobile Services .NET (Link)

Posted the blog Fresh Updates to Azure Mobile Services .NET on the Azure Mobile Services Team Blog describing new features released today for Azure Mobile Services .NET. If you are building cloud connected mobiles apps then check out Microsoft Azure Mobile Services and let us know what you think!

Have fun!

Henrik


Ali Kheyrollahi: Cancelling an async HTTP request Task sends TCP RESET packet

Level [T4]

This blog post did not just happen. In fact, never, if ever, something just happens. There is a story behind everything and this one is no different. Looking back, it feels like a nice find but as the story was unfolding, I was running around like a headless chicken. Here we have the luxury of the hindsight so let's take advantage of it.

TLDR; If you are a sensible HTTP client and make your HTTP requests using cancellable async Tasks by passing a CancellationToken, you could find your IP blocked by legacy bridge devices blacklisting clients sending TCP RESET packets.

So here is how it started ...

So we were supposed to go live on Monday - some Monday. Talking of live, it was not really live - it was only to internal users but considering the high profile of the project, it felt like the D-Day. All VPs knew of the release and were waiting to see a glimpse of the project. Despite the high profile, it was not properly resourced, I despite being so called architect , pretty much singled handedly did all the API and the middleware connecting the Big Data outputs with the Single Page Application.

We could not finish going live on Monday so it moved to Tuesday. Now on Tuesday morning we were all ready and I set up my machine's screen like traders with all performance monitors up on the screen looking at users. With using the cloud Azure, elasticity was the option although the number of internal users could hardly make a dent on the 3 worker roles. So we did go live, and, I could see traffic building up and all looked fine. Until ... it did not.

I saw requests queuing up and loading the page taking longer and longer. Until it was completely frozen. And we had to take the site down. And that was not good.

Server Analysis

I brought up DebugView and was lucky to see this (actual IP and site names anonymised):

[1240] w3wp.exe Error: 0 :
[1240] <html>
[1240] <h1>Access Administratively Blocked</h1>
[1240] <br>URL : 'http://www.xyz.com/services/blahblah'
[1240] <br>Client IP address : 'xyz.xx.yy.zzz'
[1240] </html>

So we are being blocked! Something is blocking us and this could be because we used an UI data endpoint as a Data API. Well I knew it is not good but as I said we had a limited time and in reality that data endpoint was meant to support our live traffic.

So after a lot of to and fro with our service delivery and some third party support, we were told that our software was recognised as malicious since it was sending way too many TCP RESET packets. Whaa?? No one ain't sending no TCP whatever packets, we are using a high level language (C#) and it is the latest HttpClient implementation. We are actually using many optimising techniques such as async calls, parallelisation, etc to make the code as efficient as possible. We also used short timeout+ retry which is Netflix's approach to improve performance.

But what is TCP RESET packets? Basically a RESET packet is one that has the RESET flag set (which is otherwise unset) and tells the server to drop the TCP connection immediately and reclaim all the resources associated with it. There is an RFC from back in 2002 that considers RESET harmful. Wikipedia's article argues that when used as designed, it is useful but forged RESET can disrupt the communication between the client and server. And Microsoft's technet blog on the topic says "RESET is actually a good thing".

And in essence, I would agree with the Microsoft (and Wikipedia's) account that sending RESET packet is what a responsible client would do. Let's imagine you are browsing a site using a really bad wifi connection. The loading of the page takes too long and you frustrated by the slow connection, cancel browsing by pressing the X button. At this point, a responsible browser should tell the server it has changed its mind and is not interested in the response. This will let the server use its resources for a client that is actually waiting for the server's response.

Now going back to the problem at hand, I am not a TCP expert by any stretch - I have always used higher level constructs and never had to go down so deep in the OSI model. But my surprise was, what is different now with my code that with a handful calls I was getting blocked while the live clients work well with no problem with significantly larger number of calls?

I had a hunch that it probably has to do with the some of the patterns I have been using on the server. And to shorten the suspense, the answer came from the analysis of TCP packets when cancelling an async HTTP Task. The live code uses the traditional synchronous calls - none of the fancy patterns I used. So let's look at some sample code that cancels the task if it takes too long:

var client = new HttpClient();
var buffer = new byte[5 * 1000 * 1000];
// you might have to use different timeout or address
var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300)); /
try
{
var result = client.GetAsync("http://www.google.com",
cts.Token).Result;
var s = result.Content.ReadAsStreamAsync().Result;

var result1 = s.ReadAsync(buffer, 0, buffer.Length, cts.Token).Result;
ConsoleWriteLine(ConsoleColor.Green, "Got it");
}
catch (Exception e)
{
ConsoleWriteLine(ConsoleColor.Red, "error! " + e);
}

In this snippet, we are calling the google server and set a 300ms timeout (which you might have to modify the timeout or the address based on your connection speed, in order to see the cancellation). Here is a WireShark proof:



As you can see above a TCP RESET packet has been sent - if you have set the parameters in a way that the request does not complete before its timeout and gets cancelled. You can try this with a longer timeout or use a WebClient which is synchronous and make sure you will never ever see this RST packet.

Now the question is, should a network appliance pick on this responsible cancellation and treat it as an attack? By no means. But in my case, it did and it is very likely that it could do that with yours.

My solution came by whitelisting my IP against "TCP RESET attacks". After all, I was only trying to help the server.

Conclusion

Cancelling an HTTP async Task in the HttpClient results in sending TCP RESET which is considered malicious by some network appliances resulting in blacklisting your IP.

PS. The network appliance belonged to our infrastructure 3rd party provider whose security managed by another third party - it was not in Azure. The real solution would have been to remove such crazy rule, but anyhow, we developers don't always get what we want.



Henrik F. Nielsen: Real-time with ASP.NET SignalR and Azure Mobile .NET Backend (Link)

Posted the blog Real-time with ASP.NET SignalR and Azure Mobile .NET Backend on the Azure Mobile Services Team Blog explaining how to enable real-time communications between your mobile apps and Azure Mobile Services .NET backend.

Have fun!

Henrik


Filip Woj: Announcing ASP.NET Web API Recipes

It is my pleasure to announce that this summer my ASP.NET Web API book will be released. It’s entitled "ASP.NET Web API Recipes", and will be published by Apress. While the publication date is not set in stone yet (probably … Continue reading

The post Announcing ASP.NET Web API Recipes appeared first on StrathWeb.


Dominick Baier: IdentityServer v3 Nuget and Self-Hosting

Thanks to Damian and Maurice we now have a build script for IdSrv3 that creates a Nuget package *and* internalizes all dependencies. So in other words you only need to reference a single package (well strictly speaking two) to self host the STS (including Autofac, Web API, various Katana components etc). Pretty cool. Thanks guys!

A picture says more than 1000 words (taken from the new self host sample in the repo).

image


Filed under: IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Dominick Baier: Covert Redirect – really?

In the era where security vulnerabilities have logos, stickers and mainstream media coverage – it seems to be really easy to attract attention with simple input validation flaws. Quoting:

“Covert Redirect is an application that takes a parameter and redirects a user to the parameter value WITHOUT SUFFICIENT validation. This is often the of result of a website’s overconfidence in its partners.”

Oh yes – and amongst a myriad of other scenarios this also applies to URLs of redirect based authentication/token protocols like OAuth2, OpenID Connect, WS-Federation or SAML2p. And guys like Egor Homakov have already shown a number of times that you are bound to be doomed if you give external parties too much control over your redirect URLs.

The good thing is, that every serious implementer of the above protocols also reads the specs and accompanying threat model – e.g. quoting the OpenID Connect spec (section 3.1.2.1) :

redirect_uri
REQUIRED. Redirection URI to which the response will be sent. This URI MUST exactly match one of the Redirection URI values for the Client pre-registered at the OpenID Provider, with the matching performed as described in Section 6.2.1 of [RFC3986] (Simple String Comparison)”

Or my blog post from over a year ago:

“If you don’t properly validate the redirect URI you might be sending the token or code to an unintended location. We decided to a) always require SSL if it is a URL and b) do an exact match against the registered redirect URI in our database. No sub URLs, no query strings. Nothing.”

So this type of attack is really a thing of the past – right?


Filed under: .NET Security, AuthorizationServer, IdentityServer, OAuth, OpenID Connect, Uncategorized, WebAPI


Filip Woj: Ignoring routes in ASP.NET Web API

If you use centralized routing, it is occasionally needed to ignore a greedy Web API route so that the request can be processed by some other component or handler. One of the tiny overlooked features of Web API 2.1 was … Continue reading

The post Ignoring routes in ASP.NET Web API appeared first on StrathWeb.


Don't contact us via this (fleischfalle@alphasierrapapa.com) email address.