Scott Hanselman

Adding a Custom Inline Route Constraint in ASP.NET Core 1.0

June 23, '16 Comments [10] Posted in ASP.NET | ASP.NET MVC
Sponsored By

ASP.NET supports both attribute routing as well as centralized routes. That means that you can decorate your Controller Methods with your routes if you like, or you can map routes all in one place.

Here's an attribute route as an example:

[Route("home/about")]
public IActionResult About()
{
//..
}

And here's one that is centralized. This might be in Startup.cs or wherever you collect your routes. Yes, there are better examples, but you get the idea. You can read about the fundamentals of ASP.NET Core Routing in the docs.

routes.MapRoute("about", "home/about",
new { controller = "Home", action = "About" });

A really nice feature of routing in ASP.NET Core is inline route constraints. Useful URLs contain more than just paths, they have identifiers, parameters, etc. As with all user input you want to limit or constrain those inputs. You want to catch any bad input as early on as possible. Ideally the route won't even "fire" if the URL doesn't match.

For example, you can create a route like

files/{filename}.{ext?}

This route matches a filename or an optional extension.

Perhaps you want a dateTime in the URL, you can make a route like:

person/{dob:datetime}

Or perhaps a Regular Expression for a Social Security Number like this (although it's stupid to put a SSN in the URL ;) ):

user/{ssn:regex(d{3}-d{2}-d{4})}

There is a whole table of constraint names you can use to very easily limit your routes. Constraints are more than just types like dateTime or int, you can also do min(value) or range(min, max).

However, the real power and convenience happens with Custom Inline Route Constraints. You can define your own, name them, and reuse them.

Lets say my application has some custom identifier scheme with IDs like:

/product/abc123

/product/xyz456

Here we see three alphanumerics and three numbers. We could create a route like this using a regular expression, of course, or we could create a new class called CustomIdRouteConstraint that encapsulates this logic. Maybe the logic needs to be more complex than a RegEx. Your class can do whatever it needs to.

Because ASP.NET Core is open source, you can read the code for all the included ASP.NET Core Route Constraints on GitHub. Marius Schultz has a great blog post on inline route constraints as well.

Here's how you'd make a quick and easy {customid} constraint and register it. I'm doing the easiest thing by deriving from RegexRouteConstraint, but again, I could choose another base class if I wanted, or do the matching manually.

namespace WebApplicationBasic
{
public class CustomIdRouteConstraint : RegexRouteConstraint
{
public CustomIdRouteConstraint() : base(@"([A-Za-z]{3})([0-9]{3})$")
{
}
}
}

In your ConfigureServices in your Startup.cs you just configure the route options and map a string like "customid" with your new type like CustomIdRouteConstraint.

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.Configure<RouteOptions>(options =>
options.ConstraintMap.Add("customid", typeof(CustomIdRouteConstraint)));
}

Once that's done, my app knows about "customid" so I can use it in my Controllers in an inline route like this:

[Route("home/about/{id:customid}")]
public IActionResult About(string customid)
{
// ...
return View();
}

If I request /Home/About/abc123 it matches and I get a page. If I tried /Home/About/999asd I would get a 404! This is ideal because it compartmentalizes the validation. The controller doesn't need to sweat it. If you create an effective route with an effective constraint you can rest assured that the Controller Action method will never get called unless the route matches.

If the route doesn't fire it's a 404

Unit Testing Custom Inline Route Constraints

You can unit test your custom inline route constraints as well. Again, take a look at the source code for how ASP.NET Core tests its own constraints. There is a class called ConstrainsTestHelper that you can borrow/steal.

I make a separate project and setup xUnit and the xUnit runner so I can call "dotnet test."

Here's my tests that include all my "Theory" attributes as I test multiple things using xUnit with a single test. Note we're using Moq to mock the HttpContext.

public class TestProgram
{

[Theory]
[InlineData("abc123", true)]
[InlineData("xyz456", true)]
[InlineData("abcdef", false)]
[InlineData("totallywontwork", false)]
[InlineData("123456", false)]
[InlineData("abc1234", false)]
public void TestMyCustomIDRoute(
string parameterValue,
bool expected)
{
// Arrange
var constraint = new CustomIdRouteConstraint();

// Act
var actual = ConstraintsTestHelper.TestConstraint(constraint, parameterValue);

// Assert
Assert.Equal(expected, actual);
}
}

public class ConstraintsTestHelper
{
public static bool TestConstraint(IRouteConstraint constraint, object value,
Action<IRouter> routeConfig = null)
{
var context = new Mock<HttpContext>();

var route = new RouteCollection();

if (routeConfig != null)
{
routeConfig(route);
}

var parameterName = "fake";
var values = new RouteValueDictionary() { { parameterName, value } };
var routeDirection = RouteDirection.IncomingRequest;
return constraint.Match(context.Object, route, parameterName, values, routeDirection);
}
}

Now note the output as I run "dotnet test". One test with six results. Now I'm successfully testing my custom inline route constraint, as a unit. in isolation.

xUnit.net .NET CLI test runner (64-bit .NET Core win10-x64)
Discovering: CustomIdRouteConstraint.Test
Discovered: CustomIdRouteConstraint.Test
Starting: CustomIdRouteConstraint.Test
Finished: CustomIdRouteConstraint.Test
=== TEST EXECUTION SUMMARY ===
CustomIdRouteConstraint.Test Total: 6, Errors: 0, Failed: 0, Skipped: 0, Time: 0.328s

Lots of fun!


Sponsor: Working with DOC, XLS, PDF or other business files in your applications? Aspose.Total Product Family contains robust APIs that give you everything you need to create, manipulate and convert business files along with many other formats in your applications. Stop struggling with multiple vendors and get everything you need in one place with Aspose.Total Product Family. Start a free trial today.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Forgotten (but Awesome) Windows Command Prompt Features

June 20, '16 Comments [51] Posted in Musings
Sponsored By

It's always the little throwaway tweets that go picked up. Not the ones that we agonize over. I was doing some work at the command line and typed "dotnet --version | clip" to copy the .NET Core version number into the clipboard. Then I tweeted a little "hey, remember this great utility?" and then the plane took off. I landed two hours later and it had over 500 RTs. Madness.

It's funny that 10 year old command prompt utility (this was added in Vista) that everyone's forgotten elicits such an enthusiastic response.

Since you all love that stuff, here's a few other "forgotten command prompt features."

Some of these have been in Windows since, well, DOS. Others were added in Windows 10. What did I miss? Sound off in the comments.

Pipe command output to the clipboard

In Vista they added clip.exe. It captures any standard input and puts in the clipboard.

That means you can

  • dir /s | clip
  • ver | clip
  • ipconfig /all | clip

You get the idea.

Piping to Clip.exe puts the standard output in your clipboard

F7 gives you a graphical (text) history

If you have already typed a few commands, you can press F7 to get an ANSI popup with a list of commands you've typed. 4DOS anyone?

More people should press F7

Transparent Command Prompt

After Windows 10, you can make the Command Prompt transparent!

It's see through

Full Screen Command Prompt

Pressing "ALT-ENTER" in the command prompt (any prompt, cmd, powershell, or bash) will make it full screen. I like to put my command prompt on another virtual desktop and then use CTRL-WIN-ARROWS to move between them.

The Windows 10 Command Prompt supports ANSI natively.

The cmd.exe (conhost in Windows 10 1511+, actually) now supports ANSI directly. Which means BBS Ansi Art, of course.

Word wrapping

Oh, and the Windows 10 command prompt supports active word wrapping and resizing. It's about time.

Little Fit and Finish Commands

  • You can change the current command prompt's title with "TITLE"
  • You can change its size with MODE CON COLS=x LINES=y
  • You can change the colors from a batch file with COLOR (hex)

What did I miss?


Sponsor: Working with DOC, XLS, PDF or other business files in your applications? Aspose.Total Product Family contains robust APIs that give you everything you need to create, manipulate and convert business files along with many other formats in your applications. Stop struggling with multiple vendors and get everything you need in one place with Aspose.Total Product Family. Start a free trial today.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Stop saying learning to code is easy.

June 18, '16 Comments [68] Posted in Musings
Sponsored By
WoC in Tech Stock Photos used under CC

I saw this tweet after the Apple WWDC keynote and had thought the same thing. Hang on, programming is hard. Rewarding, sure. Interesting, totally. But "easy" sets folks up for failure and a lifetime of self-doubt.

When we tell folks - kids or otherwise - that programming is easy, what will they think when it gets difficult? And it will get difficult. That's where people find themselves saying "well, I guess I'm not wired for coding. It's just not for me."

Now, to be clear, that may be the case. I'm arguing that if we as an industry go around telling everyone that "coding is easy" we are just prepping folks for self-exclusion, rather than enabling a growing and inclusive community. That's the goal right? Let's get more folks into computers, but let's set their expectations.

Here, I'll try to level set. Hey you! People learning to code!

  • Programming is hard.
  • It's complicated.
  • It's exhausting.
  • It's exasperating.
  • Some things will totally make sense to you and some won't. I'm looking at you, RegEx.
  • The documentation usually sucks.
  • Sometimes computers are stupid and crash.

But.

  • You'll meet amazing people who will mentor you.
  • You'll feel powerful and create things you never thought possible.
  • You'll better understand the tech world around you.
  • You'll try new tools and build your own personal toolkit.
  • Sometimes you'll just wake up with the answer.
  • You'll start to "see" how systems fit together.
  • Over the years you'll learn about the history of computers and how we are all standing on the shoulders of giants.

It's rewarding. It's empowering. It's worthwhile.

And you can do it. Stick with it. Join positive communities. Read code. Watch videos about code.

Try new languages! Maybe the language you learned first isn't the "programming language of your soul."

Learning to programming is NOT easy but it's totally possible. You can do it.

More Reading


Sponsor: Big thanks to Redgate for sponsoring the feed this week. How do you find & fix your slowest .NET code? Boost the performance of your .NET application with ANTS Performance Profiler. Find your bottleneck fast with performance data for code & queries. Try it free!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

The Promising State of Diabetes Technology in 2016

June 16, '16 Comments [19] Posted in Diabetes | Open Source
Sponsored By

Glucopilot helped PalmPilots users in the 90sI've been a Type 1 Diabetic now for nearly 25 years. The first thing that every techie does once they've been diagnosed with Diabetes is they try to solve the problem with software or hardware. Whatever tool they have, they use that too to "solve their Diabetes." Sometimes it's Excel, sometimes it's writing a whole new system. We can't help ourselves. We see the charts and graphs, we start to understand that this is a solvable problem.

However, innovation in Diabetes technology has two sides. There's the "what can we do within the medical establishment" side, and there's the "what components do I, the actual diabetic, have to work with" side. We are given insulin pumps, glucose meters, and drugs but we aren't involved in the development, which makes sense to a point.

Fifteen years ago (yes, really, 15) I went on a trip with a PalmPilot, OmniSky wireless modem, Blood sugar meter, and insulin pump and quasi-continuously sent my blood glucose numbers back to a server and my doctor. Many many years later I demonstrated on stage at a Microsoft conference (video) how a remote management system like NightScout along with other innovations in IoT are taking these concepts so much further. It's through the work of hundreds of innovators and tinkerers that I think we're on the cusp.

Aside: If you are wholly unfamiliar with how Type 1 Diabetes works, please take a moment and read Diabetes Explanation: The Airplane Analogy. This post pretty clearly explains how blood sugar rises and falls and why fixing this isn't a simple problem.

Four years ago - four years ago this week in fact - I wrote a post called The Sad State of Diabetes Technology in 2012, largely in frustration. It became one of my most popular posts. For some it was a turning point and was called "seminal." For most Diabetics, though, the post said what everyone already thought and already knew. Diabetes sucks deeply, the technology we are given to manage it sucks deeply, and we are pretty much tired of waiting. We've been told a "cure" (or at least, a mostly fool-proof way to manage it) is just 5 years out. I've been told this, personally, every year for the last 25.

Here we are four years after I wrote my angry post and I'm actually feeling like we are on the edge of something big.

I believe that now we are inside a 5 year window of time where we WILL make Type 1 Diabetes MUCH MUCH easier to deal with.

Using this generation diagram from the JDRF, it's totally clear that the open source diabetes community is making Stage 4 happen today.

6 stages of "Artificial Pancreases"

Let's stop and level set for a moment. Here's a generalization of your day if you're not diabetic.

The "Normal Sugared" have it easy.

Here's what a Type 1 diabetic (like me) does:

Diabetics have to constantly manage their sugar, manually

What we need is for the "loop to be closed."

Is a Closed-Loop System for Diabetes Management like a Self-driving Car?

You know how the press just loves to call the Tesla a "Self-driving car?" It's not. I've driven one for over 15 thousand miles. It has two main features and they are both effectively cruise-control. There's the cruise control that slows down when there's a car in front of you, and then there's the "Tesla Auto-Pilot" feature. Amazing, sure, but realistically it's effectively "side to side cruise control." It will keep you in the lanes, usually, to a limit. You can't go to sleep, you shouldn't be texting. You are in charge. This isn't to minimize the amazing work that Tesla has done, but using a closed-loop insulin stages above as a parallel, a Tesla is barely stage 3 or 4.

However, this is still a fantastic innovation and for a diabetic like myself, I *would* like to take my hand off the diabetic wheel as it were, at least for the easy stuff like staying in the lanes on the freeway while going straight. Automatic basal insulin dosing (background insulin dosing) would free my mind up a LOT.

It's possible and it's happening.

What's required for a closed loop?

In order to close the loop, what are the components we need? For this simple exercise please assume that "safely and securely" applies to all of these statements.

  • The ability to tell an insulin pump to deliver insulin
  • The ability to read data from the insulin pump.
  • The ability to read current blood sugar from a continuous glucose meter
  • Some CPU or "brain" where an algorithm or controller lives to coordinate all this.
  • Storage, cloud or otherwise, to keep all this historical data

There are a number of issues to think about, though, if the open source community wants to solve this before the commercial companies do.

  • Most pump manufacturers don't like the idea of remotely controlling them after a series of insulin pump proof of concept "attacks."
    • This means that some systems require the use of an older pump to allow remote control. We, the community, need to encourage pump manufacturers to create pumps that allow secure remote control.
  • Most CGM manufacturers don't publish their specifications or like 3rd party apps or systems talking to their stuff.
    • We, the community, need to encourage manufacturers to create glucose meters that allow secure access to our sugar data. 'Cause it's our data.
  • Universal concern that someone will accidentally hurt or kill themselves or someone else.
  • Where should the "closed loop brain/algorithm" live? The cloud? Your phone? Another CPU in your pocket?

What happened in the Diabetes Technology Ecosystem in the last 4 years to make this possible?

The interesting part about this problem is that there are many ways to solve this. In fact, there are multiple closed loop OSS systems available now. Lots of things have made this possible.

Here's a rough timeline of the Open Diabetes Ecosystem.

  • Insulaudit -  Ben West starts an open source driver to audit medical devices
  • Decoding CareLink -  Driving an insulin pump with Python, Oct 2012
  • Decoding Dexcom - Pulling data off a Dexcom CGM 3 years ago!
  • CGM-Simple-Reader - Using Windows 8 DLLs from Dexcom Studio to get CGM data. Next step was uploading it somewhere!
  • Pebble - Being able to remotely view Nightscout Data on your wrist on a pebble.
  • Nightscout - Remote viewing of glucose data by pulling from a CGM and uploading to a web app. The addition of a REST API (Web API) was the killer that kick started other apps.
  • Parakeet Google App Engine - Gets data from The Parakeet Unit and talks to xDrip over the cell network. "OnStar for diabetes"
  • Nightscout Share Bridge - Takes Dexcom G5 data and copies it over to Nightscout.
  • xDrip - Talk to a CGM without a Receiver. Pulling the signal off the air itself. Can we improve their algorithm ourselves?
  • PingRF - Talking to the Animas Ping Pump via RF
  • OpenAPS - Open Artificial Pancreas System. A platform for building a closed-loop with open tools. There are almost 100 people running their own closed loops, today.
  • Watch Dana Lewis talk about OpenAPS at OSCON this year!
  • RileyLink - A bridge that can talk a Medtronic Pump. Make a the pump's RF programmatically available via Bluetooth
  • Loop - iPhone-based closed loop that uses RileyLink
  • xDripG5 - iOS Framework for talking to Dexcom CGMs over Bluetooth
  • OmniAPS - Talking to an OmniPod Pump

I realize this isn't comprehensive, but the point here is to understand there are dozens of ways to solve this problem. And there are dozens (hundreds?) of excited and capable people ready to make it happen.

Here's the systems that I have. This is my Dexcom G5 on my iPhone showing my blood sugar in near-realtime. Here I can see my sugar, but I have to make my own decisions about dosing.

Dexcom G5 on an iPhone

Here is a Raspberry Pi running OpenAPS. This is the brain. The algorithm runs here. It's talking to my Dexcom, to Nightscout in the cloud, and to my Medtronic Pump via RF via a USB device called a CareLink.

OpenAPS on a Raspberry Pi

Here is OpenAPS again, this time running on an Intel Edison sitting on a SparkFun Block with a battery and a TI C1111 RF transmitter. The Edison is the brain and has Bluetooth. The TI transmitter can replace the CareLink.

IMG_0058

As an alternative to OpenAPS, here is a RileyLink custom board that can also talk to the pump, but doesn't have a brain. There is no algorithm here. Instead, this is a bridge with RF in one hand and Bluetooth in the other. It makes a pump controllable and readable. The brain lives elsewhere.

RileyLink

Here's the RileyLink in a 3D printed case. I can keep it all in my pocket and it will run all day.

RileyLink in a 3D printed case

Here is a build of Loop from Nathan Racklyeft that uses Bluetooth to talk to both my CGM (Glucose Meter) and the Pump via the Riley Link. In this example, the phone is the brain. This is good and bad. You can't really trust your phone to keep stuff running if it also runs Candy Crush AND has a crappy battery. However, if both my Pump AND CGM spoke Bluetooth, we can imagine a world where the brain of my "artificial pancreas" is just an app on my phone. No additional hardware.

Loop puts the brain on your phone

The most important point here is that a LOT of stress could have been avoided if the manufacturers had just created open APIs in the first place.

There's also amazing work happening  in the non-profit space. Howard shared this common on my original "Sad State" Diabetes Post:

Great article, Scott. You've accurately captured the frustration I've felt since my 12 year old daughter was diagnosed with T1D nine months ago. She also wears a pump and CGM and bravely performs the ritual you demonstrate in your video every three days. The technology is so retro it's embarrassing.

Since then, Howard created Tidepool and recently spoke at the White House! On the commercial side, there are lots of players rushing to market. Medtronic may '>'>'>have a hybrid closed loop called the 670g by spring next year although trials move slowly so I'm thinking later or possibly 2018. Lane Desborough from Bigfoot Biomedical has also closed the loop and they are bringing it to market...soon we hope!

For more information, go watch Mark Wilson's talk at D-Data Exchange 2016. It is an excellent 30 minute overview of the ecosystem and a call to action to everyone involved.

Check out this visualization of 6 years of Hacking Diabetes. These are all the projects and commits as folks dump into Open Diabetes Hacking Community.

What's the take away? It's an exciting time. It's happening. It can't be stopped.

More Diabetes Reading


Sponsor: Big thanks to Redgate for sponsoring the feed this week. How do you find & fix your slowest .NET code? Boost the performance of your .NET application with ANTS Performance Profiler. Find your bottleneck fast with performance data for code & queries. Try it free!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

MSBuild Structured Log: record and visualize your builds

June 4, '16 Comments [9] Posted in MSBuild | Open Source
Sponsored By

MSBuild has been open source for a while (over a year now!) and is used to build .NET and .NET Core projects. In fact, MSBuild is used to build the .NET Core Runtime itself.

MSBuild Structured Log

Recently Kirill Osenkov published a new tool called MSBuild Structured Log that makes it easy to visualize your builds and the build process. Install and run MSBuild Structured Log from here.

It is an MSBuild logger that can be passed to MSBuild during a build and it records information about everything that happens in the build. But instead of just dumping everything into a huge text file it preserves the structure and relationships between elements, and lets you save and open the structured log in .xml format. This has significant advantages to help you understand and navigate large build logs.

It's easy to install and auto-updates itself. You can open a log file directory or it will build your project and show you the results in a friendly and searchable tree format:

MSBuild Log visualized as a tree view

Here's a more complex multi-project example. You can see what ran, what didn't, dependencies, and the logs themselves.

A complex MSBuild example visualized

Tools

There is a great list of MSBuild-related resources and tips and tricks including these tools:


Sponsor: Many thanks to Stackify for sponsoring the feed this week! Stackify knows developers are the center of the universe. That’s why Stackify built Prefix and will give it out free forever. No .NET profiler is easier, prettier, or more powerful. Build better—now!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.