Scott Hanselman

Carter Community for ASP.NET Core means enjoyable Web APIs on the cutting edge

August 19, 2021 Comment on this post [4] Posted in ASP.NET | DotNetCore | Open Source
Sponsored By

I blogged about the open source Carter Community Project in 2019. Let's check in and see what's going on today in 2021!

With .NET 6 on the near horizon, one notes that Carter has a net6 branch. Per their website, this is the goal of the Carter framework:

Carter is framework that is a thin layer of extension methods and functionality over ASP.NET Core allowing code to be more explicit and most importantly more enjoyable.

As of today you can bring Carter into your .NET 6 projects like this:

dotnet add package Carter --version 6.0.0-pre2

And the .NET 6 samples are under active development! Let's bring it down with a clone, switch to the net6 branch and give it a go.

Here's as simple Web API sample with Carter that returns a list of actors at localhost:5001/actors

using Carter;
using CarterSample.Features.Actors;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;


var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IActorProvider, ActorProvider>();
builder.Services.AddCarter();

var app = builder.Build();

app.MapCarter();
app.Run();

Nice! This is using new .NET 6 features so there's no Main(), it's implied. The builder has an ActorProvider added as a Singleton. I bet we'll use that when we ask for /actors in our browser or favorite HTTP API client.

public class ActorsModule : ICarterModule
{
public void AddRoutes(IEndpointRouteBuilder app)
{
app.MapGet("/actors", (IActorProvider actorProvider, HttpResponse res) =>
{
var people = actorProvider.Get();
return people;
});
...
}
}

This is nice and clean. Everything is using Dependency Injection so no one is "newing up" an Actor. You'll note also that returning the Actors as JSON is implied when we return the IEmumerable<Actor> that comes from actorProvider.Get().

In fact, the whole Actor Module is just 80 lines so I'll include it here:

public class ActorsModule : ICarterModule
{
public void AddRoutes(IEndpointRouteBuilder app)
{
app.MapGet("/actors", (IActorProvider actorProvider, HttpResponse res) =>
{
var people = actorProvider.Get();
return people;
});

app.MapGet("/actors/{id:int}", (int id, IActorProvider actorProvider, HttpResponse res) =>
{
var person = actorProvider.Get(id);
return res.Negotiate(person);
});

app.MapPut("/actors/{id:int}", async (HttpRequest req, Actor actor, HttpResponse res) =>
{
var result = req.Validate<Actor>(actor);

if (!result.IsValid)
{
res.StatusCode = 422;
await res.Negotiate(result.GetFormattedErrors());
return;
}

//Update the user in your database

res.StatusCode = 204;
});

app.MapPost("/actors", async (HttpContext ctx, Actor actor) =>
{
var result = ctx.Request.Validate<Actor>(actor);

if (!result.IsValid)
{
ctx.Response.StatusCode = 422;
await ctx.Response.Negotiate(result.GetFormattedErrors());
return;
}

//Save the user in your database

ctx.Response.StatusCode = 201;
await ctx.Response.Negotiate(actor);
});

app.MapDelete("/actors/{id:int}", (int id, IActorProvider actorProvider, HttpResponse res) =>
{
actorProvider.Delete(id);
return Results.StatusCode(204);
});

app.MapGet("/actors/download", async (HttpResponse response) =>
{
using (var video = new FileStream("earth.mp4", FileMode.Open)) //24406813
{
await response.FromStream(video, "video/mp4");
}
});

app.MapGet("/empty", () => Task.CompletedTask);

app.MapGet("/actors/sample", () => Task.CompletedTask);

app.MapPost("/actors/sample", () => Task.CompletedTask);

app.MapGet("/nullable", () => Task.CompletedTask);
}
}

Note the API example at /actors/download that shows how to return a file like an MP4. Nice and simple. This sample also includes thoughtful validation code with FluentValidation extension methods like ctx.Request.Validate().

Carter is opinionated but surprisingly flexible. You can use two different routing APIs, or clean and performant Endpoint routing:

this.Get("/", (req, res) => res.WriteAsync("There's no place like 127.0.0.1")).RequireAuthorization();

It even supports OpenAPI out of the box! Carter has an active Slack as well as Templates you can add to make your next File | New Project easier!

dotnet new -i CarterTemplate
The following template packages will be installed:
CarterTemplate

Success: CarterTemplate::5.2.0 installed the following templates:
Template Name Short Name Language Tags
--------------- ---------- -------- ------------------------------
Carter Template carter [C#] Carter/Carter Template/NancyFX

There's a lot of great innovation happening in the .NET open source space right now.

Carter Source Code

Carter is just one cool example. Go check out Carter on GitHub, give them a Star, try it out and get involved in open source!


Sponsor: YugabyteDB is a distributed SQL database designed for resilience and scale. It is 100% open source, PostgreSQL-compatible, enterprise-grade, and runs across all clouds. Sign up and get a free t-shirt

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
Hosting By
Hosted in an Azure App Service

Hanselminutes is Fresh Air for Developers and has over 800 episodes of fresh tech from fresh faces

August 17, 2021 Comment on this post [0] Posted in
Sponsored By

Hanselminutes PodcastHey friends! I wanted remind you about my podcast! It's http://hanselminutes.com/ and just a few weeks ago I published my 800th episode! My first episode was in January of 2006 so that's over 15 years of shows. And, if I may be a little boastful for a moment, they are pretty darn good. Maybe the first 400 were a little rough but these last 400 have been ROCK SOLID. Just kidding.

Seriously, though, this 30 minute long tech show has diverse topics and new faces you haven't heard on other podcasts. If you check out over 800 episodes here https://www.hanselminutes.com/episodes you can search by Title, Guest, OR search all the Transcripts! There's over 400 hours of shows and you can search for the topics you want.

Subscribe with your favorite podcast app, the raw RSS is here. We're also available on basically every podcast app out there, including, but not limited to:

If you enjoy the show, the best thing you can do to help me is SPREAD THE WORD! Tell a friend, share and episode or favorite code, but above all GET FOLSK TO SUBSCRIBE.

The world is littered with podcasts that gave up after 9 episodes. There's a ton of average talks shows that ramble on. I've worked really hard - at night, as this is not my day job! - to not only bring you the best guests, but to read their papers, books, and thesis, and ask the questions that YOU would have if you were here with me!

Sometimes I even put the Hanselminutes Podcast on YouTube and the results are truly special and heartbreakingly emotional.

Thanks for listening, and thanks for sharing!


Sponsor: YugabyteDB is a distributed SQL database designed for resilience and scale. It is 100% open source, PostgreSQL-compatible, enterprise-grade, and runs across all clouds. Sign up and get a free t-shirt

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
Hosting By
Hosted in an Azure App Service

Exploring a minimal Web API with ASP.NET Core 6

August 05, 2021 Comment on this post [1] Posted in ASP.NET | ASP.NET Web API | DotNetCore
Sponsored By

I write about minimal Web APIs in 2016 and my goal has always been for "dotnet server.cs" to allow for a single file simple Web API. Fast forward to 2021 and there's some great work happening again in the minimal API space!

Let's do a 'dotnet new web' with the current .NET 6 preview. I'm on .NET 6 preview 7. As mentioned in the blog:

We updated .NET SDK templates to use the latest C# language features and patterns. We hadn’t revisited the templates in terms of new language features in a while. It was time to do that and we’ll ensure that the templates use new and modern features going forward.

The following language features are used in the new templates:

  • Top-level statements
  • async Main
  • Global using directives (via SDK driven defaults)
  • File-scoped namespaces
  • Target-typed new expressions
  • Nullable reference types

This is pretty cool. Perhaps initially a bit of a shock, but this a major version and a lot of work is being done to make C# and .NET more welcoming. All your favorite things are still there and will still work but we want to explore what can be done in this new space.

Richard puts the reasoning very well:

The templates are a much lower risk pivot point, where we’re able to set what the new “good default model” is for new code without nearly as much downstream consequence. By enabling these features via project templates, we’re getting the best of both worlds: new code starts with these features enabled but existing code isn’t impacted when you upgrade.

This means you'll see new things when you make something totally new from scratch but your existing stuff will mostly work just fine. I haven't had any trouble with my sites.

Let's look at a super basic hello world that returns text/plain:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

if (app.Environment.IsDevelopment()){ app.UseDeveloperExceptionPage(); }

app.MapGet("/", () => "Hello World!");

app.Run();

Slick. Note that I made line 3 (which is optional) just be one line to be terse. Not needed, just trying on these new shoes.

If we make this do more and support MVC, it's just a little larger. I could add in app.MapRazorPages() if I wanted instead of MapControllerRoute, which is what I use on my podcast site.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Back to the original Web API one. I can add Open API support by adding a reference to Swashbuckle.AspNetCore and then adding just a few lines:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseSwagger();
app.MapGet("/", () => "Hello World!");
app.UseSwaggerUI();
app.Run();

Then I hit https://localhost:5001/swagger and I get the SwaggerUI and a little WebAPI Tester:

Minimal WebAPI Tester

Anuraj has a great blog where he goes deeper and pokes around David Fowlers GitHub and creates a minimal WebAPI with Entity Framework and an in-memory database with full OpenAPI support. He put the source at at https://github.com/anuraj/MinimalApi so check that out.

Bipin Joshi did a post also earlier in June and explored in a bit more detail how to hook up to real data and noted how easy it was to return entities with JSON output as the default. For example:

app.UseEndpoints(endpoints => {

endpoints.MapGet("/api/employees",([FromServices] AppDbContext db) =>
{
return db.Employees.ToList();
});
...snip...
}

That's it! Very clean.

Dave Brock did a tour as well and did Hello World in just three lines, but of course, you'll note he used WebApplication.Create while you'll want to use a Builder as seen above for real work.

var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
await app.RunAsync();

Dave does point out how nice it is to work with simple models using the C# record keyword which removes a LOT of boilerplate cruft.

Check this out!

var app = WebApplication.Create(args);
app.MapGet("/person", () => new Person("Scott", "Hanselman"));
await app.RunAsync();

public record Person(string FirstName, string LastName);

That's it, and if you hit /person you'll get back a nice JSON WebAPI with this result:

{
firstName: "Scott",
lastName: "Hanselman"
}

Dig even deeper by checking out Maria Naggaga's presentation in June that's on YouTube where she talks about the thinking and research behind Minimal APIs and shows off more complex apps. Maria also did another great talk in the same vein for the Microsoft Reactor so check that out as well.

Is this just about number of lines of code? Have we moved your cheese? Will these scale to production? This is about enabling the creation of APIs that encapsulate best practices but can give you the "middleware-like" performance with the clarity and flexibility that was previous available with all the ceremony of MVC.

Here's some more resources:

Have fun! Lots of cool things happening this year, even in the middle of the panini. Stay safe, friends.


Sponsor: Pluralsight helps teams build better tech skills through expert-led, hands-on practice and clear development paths. For a limited time, get 50% off your first month and start building stronger skills.

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
Hosting By
Hosted in an Azure App Service

Stringly Typed vs Strongly Typed

August 03, 2021 Comment on this post [17] Posted in Musings
Sponsored By

I used to call this technique "type tunnelling" and noted its use in XML in 2005. When you are using a strongly typed language but instead your types are stringly typed, you are passing strings around when a better type exists.

Here's some examples of stringly typed method calls:

Robot.Move("1","2"); //Should be int like 1 and 2
Dog.InvokeMethod("Bark"); //Dispatching a method passing in a string that is the method's name. Dog.Bark()
Message.Push("TransactionCompleted"); Could be an enum

Stringly TypedThere's reasons to do each of these things, but as a general rule your sense of Code Smell should light up if you smell Stringly Typed things.

Inline SQL is another where one language (a proper language with Syntax) is tunneled as a string within another. There's no good solution for this as most languages don't have a way to express SQL such that a compiler could noticed a problem. Sometimes we'll see Fluent APIs like LINQ try to solve this. RegEx is another example of a string language within a language. Sometimes one will see large switch statements that fundamentally change program flow via "magic strings." One misspelling and your switch case will never fire.

Again, these have valid reasons for existence but you won't catch syntax issues until runtime.

LinqPad has a great post on why strongly typed SQL via LINQ or other fluent syntaxes are often better than SQL. Here's some LINQ in C# that will eventually turn into SQL. You get autocomplete and syntax warnings throughout the authoring process:

from p in db.Purchases
where p.Customer.Address.State == "WA" || p.Customer == null
where p.PurchaseItems.Sum (pi => pi.SaleAmount) > 1000
select p

So why does it matter?

Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b");

This isn't to say all Stringly Typed code is bad. It's to say that you need to make sure it doesn't just happen on its own. Be prepared to justify WHY it was written that way. Is string the only data type the app uses? Are there potential uses where something should be a Message or an Event or a Something and it was just easier or simpler to use a string? And here's the rub - was this Stringly Typed data structure pass to another component or service? Did you intend for its semantic meaning to be retained across this logical (or physical) boundary?

A great litmus test is "how would I catch a misspelling?" Compiler" Unit Test? Production ticket?

What do you think about Stringly Typed code? Do we type Name and Surname? Is that too far? Do we string all the things?


Sponsor: Pluralsight helps teams build better tech skills through expert-led, hands-on practice and clear development paths. For a limited time, get 50% off your first month and start building stronger skills.

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
Hosting By
Hosted in an Azure App Service

Tips and Tricks and Best Practices for Hybrid Meetings with Microsoft Teams and more

July 22, 2021 Comment on this post [4] Posted in Musings
Sponsored By

I've had a number of emails asking questions like

I'm sure you have a ton of tips and learnings on how to create inclusive meetings where some people are remote and some not. Do you happen to have it in written somewhere?

We are discussing what guidance and technology we could use for the teams when coming back to a hybrid world, where meetings will surely have people connected remotely. For example, we were wondering how we can take some things from remote meetings like the chat window – which actually makes so much easier for everybody to participate – to this hybrid world (maybe projecting in the room, maybe assigning somebody to voice comments, etc.). Other areas we are discussing: how to deal with whiteboarding, how to avoid communication not flowing for remote people, recording meetings for people in different time zones…

and while I've written things like

imageI haven't written anything on Hybrid meetings where some folks are remote and others are starting to go back into the office. Fortunately, Mads Torgersen on the team is slowly making his way back into the office and has offered me these words to share with you, Dear Reader! I've paraphrased and edited this some as well. Thanks, Mads!

Mads: Last week I held a hybrid meeting! Which means that I was in the conference room with other people (ok, one other person), and the rest participated remotely via teams. The explicit purpose of the setup was to start gaining experience and learning the tricks for when there are folks back in the office on a more regular basis in phase 6.

This is to share my initial experiences, and encourage any conversation or tips other people have picked up. Feel free to share. There is no formal follow-up, and I know there are conversations around this going on in multiple places; it just feels to me like [a good place to start a] conversation at this point.

The conference room had the usual equipment of a projector and a room camera, ambient audio and a control panel in the middle of the table running a Teams client.

Scott: While we are using Teams at work, much of these tips can be used with Zoom and other video conferencing software.

First do no harm: Mads: The most important goal is to never go back to remote participation being a second-class experience! The remote experience in Teams needs to not deteriorate even one little bit when a conference room joins in. This means that everyone in the room should also be joined to the Teams meeting. Bring a laptop or other Teams-enabled device, turn off audio input and output on it (the room will take care of that) and use the Teams features as you would as a remote participant: Raise hands (Best. Feature. Ever!), participate in chat, send reactions.

Scott: If you're using Zoom or don't have a TV or room system, you can have everyone with laptops in the room join the meeting so their faces are shared, then have just one central person have their mic and speakers on. The idea is to allow the folks who are remote to see the context of what's happening and react to facial expresses as if they were in the room!

Create the space: Mads: At the same time, once several participants are coming to the office again, I think we should be careful not to create a force away from the office, making people stay at home just so they can go to meetings. If you don’t include a room in your meeting, you are compelling people to disturb their team room mates, scramble for sparse focus rooms or give up on coming in. The meeting room isn’t just a nice way to get together (though that is nice!), it is simply the most efficient, realistic and best way for on-site folks to participate in a meeting. So: come phase 6, start adding those meeting rooms again!

Scott: This suggestion won't apply to every company, as not every Enterprise has the idea of 'inviting a room.' This is a good tip though if you have a physical shared space back in the office AND that room can be invited so that you're not joining Teams/Zoom on laptops but with the Poly/TV or shared devices in the office room.

Placement in the room: The meeting leader (or in-room designate) needs to sit next to the [main central] Teams panel, so as to use it actively during the meeting (see below). We experimented with where to face. There’s a conflict between looking at your screen and looking at the projected output, but there’s also an efficiency in being able to have those two screens show different things. Also, it’s distracting for remote participants to see in-the-room folks "from the side” on either the room feed or the individual cameras.

We therefore landed on turning our laptops so we would face them in the same direction as the big screen and room camera. That way folks always see you from the front, you don’t have to turn your head between the shared and private screens. An odd downside (especially when more people are in the room) is that folks physically together don’t face each other! I’m still curious to see how this plays out with half-and-half or even majority in-room participants. But don’t forget to do no harm: Remote folks should not feel as if local folks are huddled in a circle and they are standing outside looking at people’s backs. Teams is the primary meeting venue and the physical room is secondary.

A possible other downside to being turned somewhat sideways is ergonomic. This is the same as when someone is giving a presentation and you’re not optimally seated. The emerging social contract here should come with enough wiggle room for folks to be physically comfortable through long-haul meetings.

Scott: What's important here isn't the implied prescription of what directions to face, but that Mads is making a conscious effort to be actively inclusive. He's trying new things and mixing up camera angles so that folks who are remote are present and included in the meeting.

Leading the meeting: Mads: Many of us have several screens at home, and it’s useful to keep track of all the moving parts across a lot of screen real estate. Having just your laptop can be quite limiting, but the Teams client [Scott: or shared TV] in the room can help a lot. First of all, if the room is not invited to your meeting (maybe you have the room invite separate like I do), its easy to call the room from the Teams meeting on your laptop, then "pick up” on the panel (or have someone in the room do it if you’re remote). From then on, the room is "in" the meeting.

The panel lets you pick different screen layouts for what is projected, and you can use that to differentiate between what’s on the shared and private screens, clawing back real estate. What worked well for us was to project just the faces ("Gallery Mode”) on the big screen; when something was being shared you could read it better on your private screen anyway, and having remote folks’ faces bigger on the wall made for a much better sense of "connection” and reminder of their presence in the meeting. If you’re leading the meeting remotely, have someone in the room be the designated panel operator.

The panel also shows the participant list in hands-raised order like your own Teams client does, and that frees up even more real estate for the meeting leader, if you’re in the room.

Finally the panel has a spare "raise hand” button for the room, so if you end up with one or two in-room folks who for some reason can’t participate on Teams (maybe they don’t have a laptop), you can have them sit nearby and let them use that to raise their hand during the meeting.

All in all this was a much better experience than I expected. I felt I had the tools I needed to run a good meeting for everyone involved, keeping the experience as good for remote folks, and making it pretty decent for those in the room. As more people get in, a lot is going to ride on good habits, so that remote people continue to be fully included and empowered.

I hope that was useful! Any thoughts, additional or countervailing experiences etc, I’d love to hear them! Together we’re gonna nail this hybrid thing!

Scott: What are your best tips and tricks for good hybrid meetings?


Sponsor: Pluralsight helps teams build better tech skills through expert-led, hands-on practice and clear development paths. For a limited time, get 50% off your first month and start building stronger skills.

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
Hosting By
Hosted in an Azure App Service

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