VSTS Extension Template (w/ React and Webpack)

It is pretty clear to me nowadays that I always have a hard time trying to focus myself in a single subject to learn. Every time I start to study something cool, something, which is usually also pretty cool, gets my attention. This time VSTS extensions decided to get my attention.

Recently I realized that a feature that is pretty awesome on GitHub is not present on VSTS, and it is not even being tracked on VSTS UserVoice, so I decided to give it a shot and develop it myself, as an extension.

I am still working on my extension, but I realized that it took me some effort to put together the pieces I needed to develop this extension, and I decided that it would be a good idea to share this template with everyone who is interested in developing a new extension.

The template code can be accessed here. On the project README file you should find all the information you need to start creating your own extension!

To start a very simple VSTS extension is really easy, but on this template I already setup some nice tools that should make your life much easier and your development much more productive.

Wait… What is VSTS?

VSTS, which stands for Visual Studio Team Services, is a Cloud Based service offered by Microsoft for collaboration on code development.

As simple as it may sound, VSTS is actually a robust service that allows you to manage the entire flow of your application development. You can read a lot more about it on the links at the end of this post.

And, up to a certain limit, is free! 🙂

Why would I need this template?

You don’t really need it. Starting a new VSTS extension is a really straightforward process, and you can start one in 10 minutes, probably. The problem, or at least the hard and repetitive work, is in setting up the tools to make your development process decent and productive. That is where the template can help you.

The whole point of the template is to allow you to focus on your extension code, not having to worry about setting up the tools that you are going to need.

The tools setup on the template are:

  • React
    • For the user interface
    • It is, of course, setup with compiling JSX
  • Webpack
    • Webpack the module bundler that will take care of transpiling all the JSX code (and some other resources) to their final state
  • Jest
    • This is the Unit Testing Framework for our extensions 🙂
    • I didn’t even knew Jest until I decided to start this extension! It is created by Facebook and looks really nice and simple
  • TFX-CLI
    • This is the command line tool used by TFS and VSTS to do a lot of smaller tasks, and that includes managing extensions
    • This tool a simple npm package, so it will be installed with all the rest of the tools
  • Travis CI/CD
    • There is also a Travis CI/CD build partially setup on the project
    • This will require a little bit of manual work to make it work perfectly for your project
  • ESLint
    • To make our code look nice and follow minimum good practices.

The Code Editor

I must mention that the template also contains some configurations that would make it much easier to use with Visual Studio Code.

It is not really a requirement, but it will give you some extras, like a couple of suggested extensions to make it easier to use and some pre-configured tasks for running builds and tests with the default shortcut.

Feedback

Please, let me know if you have any feedback on the template, and specially if you face some problem, I will definitively do my best to try to help.

You can also use the repository issues panel to report any problem or give any suggestions.

That is it, for now 🙂 I hope to be back really soon with more content

Sources

Playing with pandas in Jupyter

So, today I would like to talk with you about the fun time I had playing with pandas in Jupyter 🙂

What a nice and misleading title 😀 haha
Let me add some context.

TL;DR;

I decided to spend some time playing with data using python, just to have a feeling on how easy it is, giving that python is the language of choice of many data scientists.

“Why is this guy talking about python in the first place? Isn’t this an Azure/.NET Blog?”

Mainly, yes, but Python has a special place in my heart <3 and it is my second language, I could say. So, whenever I am not learning Azure/.NET I am most likely learning python 🙂

What did I do?

I found a Data Analysis tool called pandas and a web application that allows you to visualize this data while you play with code called Jupyter Notebooks.

Let me make it clear that I am NOT an expert in any of the tools that I am going to list below and I was learning most of what I used while creating this post! So, if you see something terribly wrong, go easy on me and enlighten me, please! I would love to learn more from other people about this whole Data Science world.

The tools that I choose to do this are:

pandas

an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.

Jupyter Notebooks

an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.

matplotlib

a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

data.gov

The home of the U.S. Government’s open data

I was always told that this is an awesome place to get some nice datasets with data that you can use to generate visualizations, and now I can confirm this.

Before we begin

All the code that I wrote for this post can be found on my GitHub, where I also plan to add more code to this repository, as I am still learning new things.

Also, I created a Twitter account for the blog, just to separate it from my personal account. You can find it here: @AzureCoderBlog and my personal account is: @lucas_lra

Let’s begin.

Setting up the Environment

First thing we need to do is to set up our environment with all the tools.

If you are on window, you can use the CreateEnvironment.bat script that is available as part of the source code. This script will create the entire environment for you. But if you don’t want to miss the fun, just follow the step-by-step.

    1. Install Python 3
      • If you don’t know anything about python, just download the installer from this page.
      • You are going to LOVE it.
    2. Clone the GitHub repository
    3. Navigate to the project folder
    4. Create a Python Virtual Environment
    5. Activate your Virtual Environment
    6. Install the required packages (this step may take a while, and needs internet connection)
    7. Finally, start Jupyter Notebooks!

You should now see a screen like this:

Jupyter Notebook
Click on the Image to enlarge

As you can see, this is a file explorer that shows everything on the current folder that you are running, and what we want to do now it open the notebook: World-Population-by-Continent-[1980-2010].ipynb

What should be seeing now is some kind of in-browser text editor filled with text and python code:

Population Notebook
Click on the Image to enlarge

I won’t go into the specifics about how to better navigate on a Jupyter Notebook in this post, but you can learn everything you are going to need into this documentation.

To execute each block of our notebook, we are going to use the shortcut SHIFT+ENTER. This shortcut will execute the current block and jump to the next.

While I tried to make the notebook as self-explanatory as possible, I would like to go over the blocks of code and try to explain what is happening.

We start importing all the packages that we are going to need in the execution of our script.

As mentioned before, pandas is what we are going to use for the Data analysis, matplotlib is responsible for the graph generation and itertools is a default python package used to do lots of awesome stuff with iterable types.

Next we are going to import our dataset.

Really simple, isn’t it? pandas contains lots of those methods to import many different data types, like pd.read_excel() or pd.read_json(). This csv file, as I mentioned before, was obtained on the data.gov website.

The next step is to try to make the data a little better. I started by naming the column with the names of the places.

This was tricky for me on a first sight but, what is happening here is that I am copying the titles of all the columns on the dataset to a separate list object, after that I am renaming the first item of this list and then, finally, I am applying this entire list as a new set of column names for the pandas.DataFrame. Looks weird, but works like a charm.

Next problem we need to address is that the population data on the DataFrame is recognized by the script as str! We need to recognize this data as numeric types if we want to do some operations with it, let’s do this.

So here we are basically iterating through the DataFrame and using the pandas.to_numeric() function to convert the values. Also, we are using the errors='coerse' option to make sure we ignore the ‘NaN’ values.

Great! Now we have all the data into the DataFrame prepared. So I started thinking, what if I wanted to do some Data Analysis based on the type of place? (Like, is it a Country? A Continent?) and I realized that I would need to add one extra piece of data to the DataFrame, and this is how I did it.

I decide that I just wanted to tag the Continents on the DataFrame, so any other register will be tagged with a simple  (dash), which we will ignore later. To be quite honest, I don’t like this approach but, so far, I don’t know any other.

Next! Let’s effectively filter only the continents data out of the dataset.

Ok! Now let’s pause and have a look at the state of our DataFrame:

Splitted DataFrame
Click on the Image to enlarge

Looking good, isn’t it? We only have the five rows for the continents, we have our Region Type column correctly filled and the columns are all there, now what? First let’s setup two small lists of markers and colors that we are going to use in our Graph.

Those are all codes for markers and colors that matplotlib can understand. You can find more documentation about this here. Also, we are using itertools.cycle() to generate this list. Why? Well, the reason is that this object type allows us to iterate through it a random number of times, and it will always go back to the first item of the list, after reaching the last one, that will allow us to have any number of data entries on our DataFrame and still have enough markers and colors.

And with that, our preparations are done. Let’s start setting up our graph by configuring a Figure()

Here we are configuring our font-size in a global way for matplotlib, that will allow us to use relative sizes later. We are also creating the Figure() which will be the canvas for our plotting, and the actual subplot, which will contain our visualization.

Now, let’s effectively plot our Graph to the Figure

I’ll try to explain everything on this not so awesome looking code.

  • Lines 2-3
    • Here we are just converting our data to lists for easier handling
  • Lines 6;33 (Shame on me)
    • I couldn’t find a nice way of fitting all the y axis on the graph width so, my trick was to add two fake and empty axis, just to readjust the graph width and make it better.
    • I am REALLY sorry for this one, it doesn’t look good AT ALL. I’ll find a best solution next time 😛
  • Line 7
    • Our for will iterate through all the columns that represent a year on the DataFrame
  • Lines 8-14
    • This is where we are adding our data ticks to the graph. I should say that this is the most important part of the process.
    • The first two parameters of the execution are the ones that define our data tick, the rest is configuration of which you can learn more here.
  • Lines 16-33
    • This is where we set some annotations (in this case, text) to our data ticks, ensuring that we can really understand the plotted data
  • Lines 36-37
    • Here we enable the Grid and the legend (upper right corner) for our Graph
  • Lines 40-41
    • Here we add some style to the labels around the Graph, even rotating than to 30 degrees.

And this is it! This is the entire code, and where is our final result? (Click on the image to expand it)

Final Graph
Click on the Image to enlarge

HA! It worked! Eureka!

And that is actually everything I have to show for my efforts on Data Science, so far 😀

I can’t stress enough the fact that I am NOT a specialist in any Data-Science related technology so, please, don’t take anything from my code as a best practice.

I also can’t stress enough that I do love Python, and I bet you are going to like it too, if I don’t ruin it for you with my ugly code.

And that is all for today! Till next time!

Sources

Creating an OData v4 API with ASP.NET Core 2.0

Hallo Mensen 😀 Let’s talk OData, shall we?

In the last few years my work revolved a lot around REST APIs. I think most of us will agree that REST APIs are a really good way of obtaining data from a server without caring too much about details on how to get access to that data.

You call an URL with the proper parameters (including auth or not), headers, and HTTP verb and you get some data back. Easy enough, right?

The negative side is that these APIs are either very rigid on the way they are implemented, meaning that you can only get the data in the exact way defined by the server, or they are very verbose on their implementation, meaning that you will have a lot of code to maintain on the server side to make the API flexible.

Then what?… Use OData!

What is the Open Data Protocol (OData)?

OData Logo
OData Logo

OData, or Open Data Protocol, is a set of ISO approved standards for building and consuming RESTul APIs, but what does it mean, in practice?

It means that OData is not really an implementation that you simply use but documentation specifying how you must implement it yourself. You can read a lot more about OData here.

Why would I want to use OData?

There are a number of benefits that you will obtain from implementing OData standards, from an easier learning path on the usage of your API by your customers/consumers, to the fact that OData is easily readable by machines, and in this post I want to talk about the flexibility that implementing OData gives to your API through the OData URL Conventions.

Using URL Conventions you can expose a much cleaner and generic API and let the consumer specify their needs through the call.

OData URL Conventions

The OData URL Conventions are a set of  commands that you can pass to the API through the HTTP call query string.

An OData URL is typically composed by three parts: service root URL, resource path and query options.

OData Url Format

  • Service Root URL is the root address for the API.
  • Resource Path identifies exactly which resource you are trying to achieve.
  • Query Options is how you define to the API the format in which you need that data to be delivered.

How does that sound? Simple enough, right? but also, with the proper options, extremely powerful. Let me give you a list of possible options within the Query Options block of the call:

  • $select: Allows you to define a subset of properties to return from that Resource.
  • $expand: Allows you to include data from a related resource to your query results.
  • $orderby: Not surprisingly, allows you to define the ordering of the returned dataset.
  • $top: Allows you to select the top X results of the query.
  • $skip: Allows you to skip X results of the query.
  • $count: Allows you to get a count of items that would result from that query.
  • $search: Allows for a free-text search on that particular resource
  • $format: Allows you to define the format for the returned data in some query types
  • $filter: Allows you to define a filter for your dataset.

As you can see, many of the commands are pretty similar to what you have in most of the common query languages.

I will go into a bit more detail in each of those options on the Code sample.

OData and ASP.NET

ASP.NET Core still don’t have a stable library to implement the OData protocol! But worry you not, as Microsoft has been working on it for some time and right now we have a really promising beta version on Nuget. You can find it here.

ASP.NET Framework has a really good library to implement OData, and it is quite stable by now. You can find it here.

Enough with the theory, how can we implement this query protocol in my ASP.NET Core Application?

letscode

Implementing your API

Let’s start creating a simple ASP.NET Core Web API Application on Visual Studio and creating our models.

Also, let’s create our DbContext…

…and configure our Services.

Good! Our plumbing is set, now we are going to seed some initial data to our database.

And now we call our seeder on app startup.

We must not forget to add our migration.

And last, but not least, let’s implement the simplest API possible on our 3 entities.

Done. Now we can test it using Postman:

 


Wow! It certainly looks like a nice API, doesn’t it? What is the problem with it? Why would I ever want to add OData to it?

Well, there are two fundamental problems with this approach to our API: the payload size and the querying of the data from the database.

Payload Size

The payload format is completely defined on the API/Server side of the application and the client cannot define which data he really needs to receive.

This can be made more flexible by adding complexity to the code (more parameters? more calls?) but this is not what we want right?

In the most common scenarios the client will simply have to ignore a lot of data that he doesn’t care about.

Look at the result of our query for Books below and tell me what should we do if I only want the name for the first book on the list?

We have no options here other than accept all this data and filter what we need on client side.

Querying the Data

For much of the same reason, all the queries to the database have to be done in a very rigid way, not allowing for smaller queries whenever possible.

In the same query as above, we just sent a request for a list of books, and let’s have a look at what was sent to the database:

All this huge query just to get the name of one book. That doesn’t sound good, right?

Let’s make it better with OData 🙂

Changing our API to OData

The good news is that we can use much of the same structure for our OData API, we just need to make a few configurations. Let’s start by installing the package.

As you can see the OData package for .NET Core is still in beta, as opposed to the .NET Framework version of the package, who is stable for a long time already. I have high hopes that this package will be out of beta in no time!

Let’s configure our entities to understand the OData commands.

I commented the function of each call on this class, pay close attention to it, as the calls are paramount for the full use of the URL Conventions. And now let’s wire our OData configuration with the rest of the API.

All good! Finally, we must adjust our three controllers and have then accept OData URLs. Things you should notice were changed on the Controllers:

  • All the controllers were renamed to be in the singular form. That is only necessary due to our configuration in the ModelBuilder, they can be configured to be plural.
  • The return types were all changed to IQueryable<T>
  • The .Include() calls were removed, as they are no longer necessary. The OData package will take care of this for you.
  • We are no longer inheriting from Controller but from ODataController
  • We have a new decorator for the API calls: [EnableQuery]

And that is it! Our API is ready to be used with OData URL Conventions. Let’s try it?

New API and Results

You can play with the new API format on Postman:

 

The original call to get books would look like this:

http://localhost:5000/api/books

The new call will look like this

http://localhost:5000/odata/Book

First of all, let’s try to get a list of books and look at the results:

MUCH Cleaner, right? Let’s even make it smaller, as we just want the name of the first book on the list:

http://localhost:5000/odata/Book?$top=1

And let’s have a look at the database query for this call:

Yes! A much more efficient call! But wait… We just need the NAME of the book, why don’t we make it more specific?

http://localhost:5000/odata/Book?$top=1&$select=Name

And that is an awesomely small payload! And the query is also more efficient

What if you want details about and specific Author and all his related books?

http://localhost:5000/odata/Author?$expand=Books&$filter=Name eq ‘J.K. Rowling’

Amazing, isn’t it? That can really increase the quality of our APIs.

As a last piece of information, let’s not forget that OData is designed to be readable by machines! So we have a couple of out-of-the-box urls with documentation on our API:

http://localhost:5000/odata/$metadata

Cool, isn’t it?

What’s Next?

Well, now that you know how simple it is to implement the OData protocol in .NET, I would recommend that you spend some time getting familiar with the Protocol itself, you can find all the guidance that you need here.

Also, if you have the intention to use the protocol with .NET Core, I suggest that you keep a close eye on the Nuget Package page and also the feature request on GitHub.

Source Code

You can find the whole source code for this solution on my GitHub.

And that is all for today folks 🙂

I hope you enjoyed it, and don’t hesitate to use the comments section if you were left with any questions.

Sources:

.NET Core 2.1 is coming! (and I will be back)

Hallo Mensen 🙂
I know I’ve been away from my blog for a long time and I’ll not try to make an excuse for this, but I want to make it clear that I intend to start writing again some time this quarter!

Today I just wanted to share with you two new videos from Channel 9 with some cool demos on the new features for .NET Core 2.1. In particular I would advise you to pay close attention to the improvements on the HttpClient and the Entity Framework support for CosmosDb. Enjoy!

What is new in .NET Core 2.1?

The Demos!!

One last thing to mention. Pay close attention to the benchmarks on the build process for .NET Core 2.1, it is amazing!

Incremental Build Improvements for .NET Core 2.1 SDKReally excited for the Future of .NET Core 😀

.NET Core 2.1 should have its first previews released still in this February and the RTM Version is planned to this Summer!

Source: .NET Core 2.1 Roadmap | .NET Blog

 

[ASP.NET Core MVC Pipeline] Controller Initialization – Action Selection

So, we just finished looking at the Routing Middleware, and that also completes our walk-through the Middleware Pipeline! What happens next? Now we enter the realm of the Controller Initialization, and the first thing we need to do is the Action Selection. Let’s revisit our MVC Core Pipeline flow.

The ASP.NET Core MVC Pipeline
The ASP.NET Core MVC Pipeline

We will now focus on the green part of our pipeline, the Controller Initialization.

Controller Initialization
Controller Initialization

The objective of the process in the green box is:

  1. Find the most suitable Action in the application for that request
  2. Call the Controller Factory informing the required Action
  3. Get an instance of a Controller from the Controller Factory

That is all it does, and it is a very important job 🙂 But, how can we interfere with this process? The first thing we can do is add some rules to make the Action Selection behave as we want it to.

The easiest way

You don't have to customize everything
You don’t have to customize everything

It’s true! You probably already used some alternatives to bend the process of Action Selection towards your objectives. The most common method is to use the Verb Attributes. Let’s imagine you want to create 4 actions in a single controller and each of them will respond to a different HTTP Verb:

What is wrong with this code? All the methods claim the same action path on the route, and the Action Selector has no good way to define which one to call! What will happen when we try to access the /index route?

Ambiguous Exception
Ambiguous Exception

Ambiguous Exception! and that happens, as you can see in the underscored line, because the framework does not have enough information to decide which one is the best candidate action, and that is where we can use a MethodSelectorAttribute:

Now the framework will know the best action to choose based on the HTTP Verb of the Request 🙂

That code exemplifies the kind of intervention that we can do in the process of choosing the most fitting Action Method. But, what if we want to change this behavior in a way that is specific to some kind of logic that we envisioned? That is when you should think about adding an Action Constraint.

What is an Action Constraint?

An Action Constraint is a way that we have to tell the Action Selection process that some method should be a better candidate than the other options for that request. It is really that simple. An action constraint is a class that implements the following Interface:

The Order property will help you define the priority in which that constraint must be evaluated and the Accept method is where the true logic is implemented. Whenever an ActionConstraint is evaluated and the return of the Accept method is TRUE, then it will tell the Action Selection process that this Action is a better suitable match for the request.

Customizing the Action Selection – Custom Action Constraint

Now let’s implement our own IActionConstraint and force the Action Selection process to work as we want it to. Let’s imagine a scenario where we want to serve specific content to our users who access our application through a Mobile Browser, and we want to handle that on the back-end, as we really will serve different data to this users. In this situation we have the following Action Methods:

That would, again, give us the AmbiguousException because, as it is, is impossible to the framework to choose a better Action between those two, so what can we do to help? Let’s implement our action constraint:

I know, I know… there are sure better ways to implement this behavior and that not fool-proof at all, but it is enough for our intents. We set the Order property of our Action Constraint to “0” so it will be one of the first to be evaluated by the framework, and the implementation of our Accept Method returns true if the request’s user-agent container either “Android” or “iPhone” in its value.

So, how to hookup this component to our pipeline? Easy enough:

Ha! Simple, isn’t it?

Results

Default Content
Default Content

When accessing through a common browser, you are going to be redirected to the default implementation of our View…

Mobile Content
Mobile Content

…and when accessed through a Mobile Browser, you will be presented with the specific implementation of our View. Cool, right?

This is one of my favorite pluggable components in the entire framework pipeline. It doesn’t feel too much invasive, and it can help us bend the flow of the request in a very useful way!

What do you think of it? Can we think of a way to use it on your applications?

Source:

[ASP.NET Core MVC Pipeline] Routing Middleware – Route Handler

Let’s move on with our series about the Core MVC Pipeline. What is the next step? Last time we learned how to point a request to a specific Router, and what if we need to handle a route in a custom way? Let’s create our custom Route Handler.

Middleware Pipeline
Middleware Pipeline

As we can see, the Route Handler is the last step inside our Routing Middleware and, as long as the request matches any of the routes, is also the last step inside the Middleware Pipeline, we are almost ready to move on to the next phase on the Core MVC Pipeline.

But what exactly does the Route Handler do? Let’s think functionally:

  1. Our Web Server received a request and, since it is a valid request, passed it to our application.
  2. Our application passed the request to our Middleware pipeline which running the request through every middleware until one of them decides to end the request.
  3. The request went through a lot of processes and reached our Routing Middleware.
  4. Our routing middleware will pass the request to our Router who will see if this request matches any known route. If it doesn’t, the middleware will pass the request to the next middleware, or initiate the response.

But what if the request matches any known route? What is next? That is where our Route Handler gets to do its magic!

The Route Handler is the component that defines what to do with the Request that matches a Route on our system. The default implementation for this component is the MvcRouteHandler, which usually handle every single request accepted by the Router, but now we are going to implement our own Route Handler.

Let's Code
Let’s Code

The Code

This component suffered a great deal of changes in the way it is structured on the Full .NET Framework in comparison with the .NET Core implementation.

To implement our Route Handler we are simply going to need a RequestDelegate. This request delegate will contain all the logic that must be executed against a matched route and create a response.

The code for this example will be very simple, as this is a very specialized component, and I don’t see it getting overriding frequently.

It is this simple! In this example any request matched and sent to our RouteHandler will redirect the user to this Blog 🙂 The object “c” is a HttpContext object, so anything that can be done with a request/response flow can be done in the RouteHandler as well.

Now we only have to hook up our RouteHandler on the Routing Middleware:

In the case (line 3) we created a Route that will match ANY request in which the URI starts with “blog/” and send it to our custom router, which will redirect the request.

And that is all there is for a simple custom router 🙂
There is of course other ways to implement Route Handlers but this should be more than enough for the very specific cases where this is necessary.

This wraps up our talk about the Middleware part of the MVC Pipeline! In the next post we start the talk on the Controller Initialization!

See you next time 🙂

That's All Folks
That’s All Folks

 

Favor Composition Over Inheritance Part 2 | Source: Coding Delight

And here is the second part of the article


Yesterday I wrote part one of my two-part series on why we should favor the technique of composition over inheritance. I began by looking at how a purely inheritance-based model quickly becomes unworkable as the properties and methods of base classes often lead to an inflexible design. Today, by contrast, I will look at solving the same problem by the use of composition. Specifically, we will look at how using interfaces for composition in C# allows for a highly flexible design.

The problem posed yesterday was to model the behavior of a car when a driver applies changes to it. I want to be able to track the angle of the wheels and the speed at which the wheels have been turned by the engine. The first car to model is the Toyota Corolla.

Yesterday, the first class that was designed was the BaseCar class, which contained a number of abstract methods which defined our behavior. It also contained our wheels. Today, instead, I am going to look at the behaviors of the car. It seems to me that there are two separate behaviors which are independent of each other. There is steering and there is driving (or accelerating). These behaviors will form the basis for our interface design. A car also has a manufacturer, so we will create an interface for that too.

There are a couple of ways that we could look at designing the car interface. We could say that an ICar inherits from both ISteering and IDriving, but instead I think we should say that an ICar has both an ISteering and IDriving. This seems to make the most sense.

Already we can see that simply by thinking about the components and how they logically relate to each other, we have created a different design from before. The interfaces help us think more abstractly than base classes would otherwise had. Now that we have designed our interfaces (and the astute reader might have noticed that the Wheel class has now become an IWheel interface too, though defining either is beyond the scope of these articles) we can get started on defining the functionality of our classes.

First we will create a TwoWheelDrive class which implements the IDriving interface.

Immediately it can be seen that this class can be used for both types of two-wheel drive car – front or rear. All we will have to do is pass either the front or rear wheels to it. Next up we’ll implement the two-wheel steering functionality in much the same way. Note that in this case, the steering class has to be a “front” steering class or a “rear” steering class, as each type of steering requires the wheels to turn in opposite directions to achieve the same outcome for the driver.

And next, my Toyota manufacturer class. I’ve implemented it as a singleton because that will be sufficient for this problem.

Finally, I can create my ToyotaCorolla class.

Now when the customer comes along and asks for the rear wheel drive sports edition, I can create the following class for them.

In fact, it is at this point that you can quite easily see that the only difference between ToyotaCorollas lies in the parameters that are passed into the driving constructor. A pattern is emerging. We now have the ability to do away entirely with our ToyotaCorolla class. The only difference is in our constructor parameters. What I can do instead is refactor my code and use constructor parameters to define our classes.

So as you can see, by using composition we have created a much more flexible design. We can reuse the bits that make sense to be reused and ignore the bits that don’t. The interfaces have helped us think abstractly and separated out how the objects relate to each other from how the objects work. We can use a car without knowing how the steering is implemented or whether it is a front, rear or four-wheel drive. We no longer have a complicated object hierarchy and adding new car designs takes a little effort. When it comes time to design a car with four-wheel drive, all we need to do is create a four-wheel drive class and a factory method.

Far too many professional developers think in an “is-a” mindset when they want to reuse code. I hope that I have sufficiently demonstrated that composition helps us reuse code far more efficiently and with a lot less complexity than using inheritance. As always, leave a comment, I would love to hear your feedback!

I am taking two weeks holiday, after which I will be (hopefully) blogging on a regular basis.

 

Source: Favor Composition Over Inheritance part 2 | Coding Delight

[ASP.NET Core MVC Pipeline] Routing Middleware – Custom IRouter

What if you want to add some custom logic to the routing system?

There are two main components where we can inject our code to bend some rules on the framework. The first one is the IRouter.

Middleware Pipeline - Routing
Middleware Pipeline

In our flow the IRouter is represented by the “Matching to Route Entry” box and that is what it is. The role of the IRouter in the Routing system is to match something on a request, usually on the URI, and point it to the right IRouteHandler. We are going to learn more about the RouteHandler component in a future post.

Why would I do that?

As previously said, the role of the IRouter in the pipeline is to evaluate the request and pass it to the IRouteHandler that is the best fit, but what might be mentioned is that you can also use the IRouter to make modifications to the incoming request. In this way, whenever you have a request that matches a certain criteria you can add, remove or edit some information and let the default RouteHandler do the rest.

In my experience, that is the most common case. I don’t see complete custom implementation of the Routing system so frequently.

The Basics

A bit different from the custom middleware, which is entirely implemented through conventions, the custom Router must implement an Interface called IRouter. This interface is quite simple:

The first method, GetVirtualPath, is used internally by the framework to generate urls based on this route in methods like the HTML.ActionLink one, the second method, RouteAsync, is where our logic will really reside.

Our class should start with something like this:

Routing our Requests

The concept behind the RouteAsync method is quite simple and straightforward, we do all the checking necessary to see if the provided route matches our IRouter context and, if it does, we execute the needed logic and inform the Routing middleware that the request has been handled.

We are doing the checking part on the if statement where we analyze if the request comes from a Mobile User-Agent (there are certainly better and more secure ways to do this but it is enough for the purpose of the demonstration) and if our Router finds that the request comes from such an agent, we apply some logic to change the controller and action values in our RouteData, therefore ensuring that our request will be redirected to the right Action.

If everything works as expected, then we send our modified context to the Default RouteHandler, and let it process it. The RouteHandler will set the value for the Handler property in our context, and it will let the framework know that the request has been Handled by our Router and no longer need to be processed by other Routers.

Hooking up to the Routing Middleware

Now we have a nice and functional Custom Router but if you run the application you will see that it is never touched by your request and that is because we never hooked our Router to the Routing Middleware.

The Routing Middleware has a stack of Routers that it will use to try and match a request, hence we need to add our Custom Router to this Stack. Let’s do it.

Now we add a new Router to the Routes collection and we passed the Default Handler, which will be used by our Routing flow.

And that is all we have to do to make our Router capture every request that comes from a mobile User-Agent and redirect them to specific controllers/actions.

To be completely honest, creating a custom Router will usually be a bit of an overkill as you can achieve most of the desired behaviors through the usage of easier components on the pipeline (including the middleware), but I think that is important to go through all the major components that we can customize.

What do you think? Sounds like something that you can use in your application?

Thanks for Reading! Tot ziens 🙂

MVC Pipeline Series
Sources

[ASP.NET Core MVC Pipeline] Middleware Pipeline

Let’s play with the Middleware Pipeline 🙂

Do you guys remember the flow that I showed you in the first post? No? Let’s revisit it:

The ASP.NET Core MVC Pipeline
The ASP.NET Core MVC Pipeline

So, what do we want to do here is to start from the beginning and in this post we are going to focus on the Blue part of the flow, the Middleware Pipeline:

Middleware Pipeline
Middleware Pipeline

What is a Middleware?

So, what is a middleware in the context of the Core MVC Pipeline, and why should we care about it?

Middleware is software that is assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline.

Hmmm… so each middleware is actually a piece of code, which follow some patterns, that we can ‘pile’ forming what we call a pipeline. Each of those pieces of code can (and should) implement its own logic and, that is the most interesting part, can decide whether or not to pass on a request! Because of that, each middleware is empowered to end an HTTP request and ignore every other middleware after if it decides to. Let me draw it for you:

 

Middleware Pipeline
Middleware Pipeline

In the example on the left, the request pass through all the middleware in the Pipeline and finally gets answered by the Routing Middleware.

In the example on the right, the request is cut short by a custom middleware that send the response itself rather than pass it along to next one.

A couple of important things to notice:

  • A middleware can execute successfully its function and still pass the request to next middleware, therefore allowing for more changes before sending the response.
  • The routing middleware is certainly an important one but he is not vital on the middleware pipeline. It is vital to the MVC Framework, but you could have a perfectly working application without the routing middleware.

Our first Middleware

The sequence of middleware is defined on the Configure method of the Startup.cs class.

Each of the “Use…” methods define a middleware. Let’s inject our own super simple middleware on the stack:

In this case we are defining that only the requests sent with the HTTP method GET are going to be pass on to the Routing Middleware. Other HTTP methods will be answered directly by our middleware and will never reach the Routing system. Notice that we defined our middleware inline, inside the Configure method and that is not a good practice because it worsen readability and break the Single Responsibility principle.

Pretty simple, ahn? Let’s get into some details.

Order Matters

Keep it in mind, the order in which your middleware is set up inside the Configure method matters! It matters because this is the order in which they are going to be executed when a request is received. In our example our custom middleware would never be hit if the user requests an existing static resource (like an image, or a JS file) because the UseStaticFiles middleware would have handle the request and sent a response to the user shortcutting the request.

Before AND After the next Middleware

We can see in our example that the execution of the next middleware in the pipeline is represented by a call to the next() delegate, and that means that we can execute some logic before and after the next delegate execution.

Use, Run or Map

Every middleware must run using one those three methods that define a specific behavior for the middleware.

Use

First of all, the most common method, the ‘Use…‘. This method is the one that allows our middleware to receive a request, process it and, if necessary, pass it on to the next middleware on the pipeline.

Use(IApplicationBuilder, Func<HttpContext, Func, Task>)

We receive a delegate with an HTTPContext with all the details available about the request and another delegate, which is actually the call to the next middleware. As a result we can call the next middleware in the pipeline whenever we want or not even call it, if our logic says it is not necessary.

Run

Then we have the ‘Run…‘ method and this method allows us to define a middleware that will always end the execution, simply because it has no knowledge of a next middleware in the pipeline.

Run(IApplicationBuilder, RequestDelegate)

In this case, the only thing we receive is the delegate with the custom logic of our own middleware.

Map & MapWhen

And then we have the ‘Map…‘ method which, as the name implies, allows us to map a request to a middleware depending on the Path of the request.

Map is a little bit different from the previous methods in the sense that you only map the request to a middleware, but you are still going to need to set an ‘Use…‘ or ‘Run…‘ method to actually execute our logic.

Map(IApplicationBuilder, PathString, Action)

So the Map method actually pass on an instance of the IApplicationBuilder interface! Which allows us to define a new middleware depending on the mapped request.

The Map method also has a variant called MapWhen that allows us to map the middleware against some condition on the HttpContext.

So, those four methods are supposed to give us all the flexibility that we need to create our middleware.

I think it is possible to notice that creating a middleware inline is not a great idea, right? It gets messy really quick and we don’t want that. Let’s start creating a real Middleware in a more decent way.

Creating our Custom Middleware

First of all we need to do is to create a new class and, to do that, we are going to follow some simple conventions. Our Middleware’s class and filename must end with the word ‘Middleware’:

This code, by itself, is already a working middleware. It won’t do anything, except calling the next middleware, but it will work. 🙂

Now I expect you to be asking “Where is the Base Class?”, “You forgot to implement the interface?” or “Where are the overridden methods?” and believe, I asked myself these exact same questions. The answer is simple, the framework will understand and use our Middleware based on the conventions we followed:

  • The Middleware must have a Constructor that accepts one RequestDelegate
  • The Middleware must have a public Method that receives an HttpContext as parameter and returns a Task type.

Pretty straightforward, right?

Let’s implement some logic to our Middleware. Worth mentioning that there should be better ways to implement what we are doing here, but for the purpose of the Post Series, it should be enough.

Basically what our middleware is doing is making sure that only requests with the “GET” method ever reach the next middleware and if any other method is used than the request will be shortcut.

Looks much better than having all this code inline right? But we are not ready yet!

Hookup with the Middleware Pipeline!

While this is a working code for a middleware we haven’t hooked this up to our pipeline. Let’s do this now. Back to our Startup.cs Class, in our configure method, we want our new middleware to be added like this:

Looking really good now, isn’t it? Let’s make look more like the rest of the middleware pipeline by creating one extension method for our middleware.

And now we can set up our Middleware like this:

And that is it! We have a custom middleware setup and working. Our pipeline now should work like this:

Middleware Samples
Middleware Samples

And that is it for the first post of the Core MVC Pipeline. What do you think? Can you imagine some scenarios where changing the Middleware Pipeline would be useful for your application?

On the next post we will start talking about the Routing Middleware, where we can introduce some logic to change the Routing rules 🙂

Tot ziens!

Source:

The ASP.NET Core MVC Pipeline

Hallo Iedereen 🙂
I decided to start a series of posts about custom components for the ASP.NET Core MVC Pipeline.

Most of you should know by now that ASP.NET Core was mostly redesigned to be more modular, extensible and to deal with the ‘platform agnostic’ nature of the new framework. This redesign also allows us to customize the way every request is processed, adding custom components in each step of the pipeline.

The ASP.NET Core MVC Pipeline

The ASP.NET Core MVC Pipeline
The ASP.NET Core MVC Pipeline

The idea is to have one post for each of the small blocks on the pipeline, precisely because it is possible to hook up your custom code in any of those points.

I’ll start by providing a brief overview of which is the role of each block on the pipeline:

Middleware Pipeline

Middleware Pipeline
Middleware Pipeline

The middleware pipeline is the entry point for each request in an HTTP Request, it is basically a stack of components that can execute some logic and decide whether to pass the request to the next middleware, or to send the response back to the client.

Routing Middleware

The routing middleware is just one of many that can be used by the ASP.NET Core but is of major importance to the Core MVC Pipeline. The reason for this it that this is the Middleware that ‘captures’ an incoming request and really starts the MVC Pipeline. If an incoming request url does not match any registered Route the request is passed onward to the next Middleware, ignoring the MVC Pipeline, but when the request url matches a known route, that is when the MVC Pipeline really begins.

Controller Initialization

Controller Initialization
Controller Initialization

Once a route is found by the Routing middleware, the next step is to find a controller that matches the route and instantiate it. The process of finding the best suitable Controller and Action for a Route can also be customized.

Action Execution

Action Execution
Action Execution

Now we are in the core of what really is the MVC pattern. The Action Execution is the process that will really process the incoming request and, after that, generate a Result. This is also the process where we can hook up most of our components.

Model Binding

One of the greatest features on the MVC Framework is the ability to bind request data to POCO Objects. I’ll try to explain a bit about how the standard Models Binders work, and how you can create your own Model Binder.

Filters

Filters are components that can be injected at many stages of the Action Execution and that will allow us to define behaviors that we want in our Actions, but that are not necessarily part of the LOB Logic.

Action Result

Finally, the action result is the last step of the Action Execution, and it involves basically to create a ‘Result’ type that will be processed by the Result Execution.

Result Execution

Result Execution
Result Execution

And the last step in the Core MVC Pipeline has arrived! Here is where our ‘Result’ will be analysed and processed accordingly. Here we can also inject some filters before and after our processing, allowing us to change the way the result will be processed.

Where do we start?

From the beginning! Of course 🙂 We will start creating a Custom Middleware that will be executed before the Routing Middleware.

The first post will be up very soon!

Tot ziens! (And I just spent all my Dutch in this post)

Source: