Scott Hanselman

Trying out Container Tools in Visual Studio 2019

January 24, 2020 Comment on this post [60] Posted in Docker
Sponsored By

I've been doing more and more work in Docker containers (rather than on the metal) and I noticed recently that Visual Studio 2019 added updated support for containers within VS itself so gave it a try.

When you make a new ASP.NET Core web app, make sure to check "enable docker support" when you click create.

Enable docker support

You'll need Docker for Windows first, of course. I'm using the new Docker Desktop for Windows that uses WSL2 for its backend rather than a utility VM that's visible in Hyper-V.

Now, within Visual Studio 2019, go to the View Menu and click "Other Windows | Containers." I like to dock this new tool window at the bottom.

Container Tool Window in Visual Studio 2019

Note in my screenshot above I'm starting up SQL Server on Linux within a container. This window is fantastic and includes basically everything you'd want to know and see when developing within a container.

You can see the ports exposed, the container's local file system, the environment, and the logs as they happen.

Docker Environment Variables

You can even right-click on a container and get a Terminal Window into that running container if you like:

Terminal in a running Container

You can also see https://aka.ms/containerfastmode to understand how Visual Studio uses your multistage Dockerfile (like the one below) to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["WebApplication1/WebApplication1.csproj", "WebApplication1/"]
RUN dotnet restore "WebApplication1/WebApplication1.csproj"
COPY . .
WORKDIR "/src/WebApplication1"
RUN dotnet build "WebApplication1.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "WebApplication1.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApplication1.dll"]

Go read about the new Container Tools in Visual Studio. Chances are you have a dockerfile in your project but you haven't brought this Containers Tool Window out to play!


Sponsor: Organizations that scan their code more than 300 times a year have 5x less security debt than those with sporadic testing processes. The 2019 SOSS X report from Veracode digs into this data—and more.

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

My views on community, productivity, kindness, and mindfulness on the Hanselminutes Fresh Tech Podcast

January 22, 2020 Comment on this post [4] Posted in Musings | Podcast
Sponsored By

Scott HanselmanAt the start of a new decade and over 700 episodes of my tech podcast, I did something weird. I had myself on the show. Egotistical, perhaps, given the show literally has my name in it, but the way it happened was interesting.

This episode wasn't supposed to be an episode! I was invited by Jeff Fritz of Twitch fame to talk to his community team of Live Coders on Discord. They recorded it, and mentioned several times that it was useful content! I didn't go into the private meeting thinking I'd record a show. It was effectively a conference call with friends old and new. It's unedited and off the cuff.

So, why not try something new and make this an episode! Let me know on Twitter if you find my views on community, productivity, and life useful to you!

I talk about:

  • Longevity - Sticking to your goals
  • Relationships - Business plans/goals/life settings/culture
  • Living Life By Design rather than By Default
  • Setting the Tone
  • Positivity and how to maintain it
  • Scaling yourself and your community
  • Why Kindness Matters
  • Blogging - it's a marathon not a sprint
  • Feeding your spirit
  • Why do we do something and why do we procrastinate?
  • Removing Mental Clutter
  • Why do I blog/create? Why do you?
  • Conserving your keystrokes
  • Advice to my 20 year old self
  • Willpower and catching up
  • What can you talk about? What can you write about?
  • A question is a gift
  • Why would I allow someone who doesn't love me ruin my day?
  • Interviewing techniques and empathy
  • The importance of improv and "yes, and"
  • Charisma On Command
  • Dealing with Imposter Syndrome
  • Deliberate Practice
  • Mindfulness
  • Owning what you're good at
  • Freaking Out
  • Acceptance
  • Priorities - family and life
  • What's important?
  • Plan, execute on the plan, make a new plan

Please go listen to Episode 719 of the Hanselminutes Podcast, it's just 54 minutes long.

Hanselminutes Podcast

It's called "Myself: It's not weird at all" and I'm actually kind of proud of it. Let me know what you think in the comments!

if you like this show, you can give ME a gift by SHARING it with your people!


Sponsor: Veracode analyzed 1.4 million scans for their 2019 SOSS X report. The findings? 83% of apps have flaws like cross-site scripting, injection, and authentication—all adding to rising security debt.

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

.NET everywhere apparently also means Windows 3.11 and DOS

January 17, 2020 Comment on this post [24] Posted in DotNetCore
Sponsored By

I often talk about how .NET Core is open source and runs "everywhere." MonoGame, Unity, Apple Watches, Raspberry Pi, and Microcontrollers (as well as a dozen Linuxes, Windows, etc) is a lot of places.

Michal Strehovský wants C# to run EVERYWHERE and I love him for it.

C# running on Windows 3.11

He recently got some C# code running in two "impossible" places that are now added to our definition of everywhere. While these are fun experiments (don't do this in production) it does underscore the flexibility of both Michals' technical abilities and the underlying platform.

Running C# on Windows 3.11

In this 7 tweet thread Michael talks about how he got C# running in Windows 3.11. The app is very simple, just calling MessageBoxA which has been in Windows since Day 1. He's using DllImport/PInvoke to call MessageBox and receive its result.

I'm showing this Windows 3.11 app first because it's cool, but he started where his DOS experiment left off. He's compiling C# native code, and once that's done you can break all kinds of rules.

In this example he's running Win16...not Win32. However (I was alive and coding and used this on a project!) in 1992 there was a bridge technology called Win32s that was a subset of APIs that were in Windows NT and were backported to Windows 3.11 in the form of Win32s. Given some limitations, you could write 32 bit code and thunk from Win16 to Win32.

Michal learned that the object files that CoreTR's AOT (ahead of time) compiler in 2020 can be linked with the 1994 linker from Visual C++ 2.0. The result is native code that links up with Win32s that runs in 16-bit (ish) Windows 3.11. Magical. Kudos Michal.

Simple Hello World C# app

Running C# in 8kb on DOS

I've blogged about self-contained .NET Core 3.x executables before and I'm a huge fan. I got my app down to 28 megs. It's small by some measurements, given that it includes the .NET runtime and a lot of accoutrements. Certainly one shouldn't judge a VM/runtime by its hello world size, but Michal wanted to see how small he could go - with 8000 bytes as the goal!

He's using text-mode which I think is great. He also removes the need for the garbage collector by using a common technique - no allocations allowed. That means you can't use new anywhere. No reference types.

He uses things like "fixed char[]" fields to declare fixed arrays, remembering they must live on the stack and the stack is small.

Of course, when you dotnet publish something self-contained, you'll initially get a 65 meg ish EXE that includes the app, the runtime, and the standard libraries.

dotnet publish -r win-x64 -c Release

He can use ILLinker and PublishedTrimmed to use .NET Core 3.x's Tree Trimming, but that gets it down to 25 megs.

He tries using Mono and mkbundle and that gets him down to 18.2 megs but then he hits a bug. And he's still got a runtime.

So the only runtime that isn't a runtime is CoreRT which includes no virtual machine, just functions to support you.

dotnet publish -r win-x64 -c Release /p:Mode=CoreRT

And this gets him to 4.7 megs, but still too big. Some tweaks go to about 3 megs. He can pull out reflection entirely and get to 1.2 megs! It'll fit on a floppy now!

dotnet publish -r win-x64 -c Release /p:Mode=CoreRT-ReflectionFree

This one megabyte size seems to be a hardish limit with just the .NET SDK.

Here's where Michal goes off the rails. He makes a stub reimplementation of the  System base types! Then recompiles with some magic switches to get an IL only version of the EXE

csc.exe /debug /O /noconfig /nostdlib /runtimemetadataversion:v4.0.30319 MiniBCL.cs Game\FrameBuffer.cs Game\Random.cs Game\Game.cs Game\Snake.cs Pal\Thread.Windows.cs Pal\Environment.Windows.cs Pal\Console.Windows.cs /out:zerosnake.ilexe /langversion:latest /unsafe

Then he feeds that to CoreIT to get the native code

ilc.exe zerosnake.ilexe -o zerosnake.obj --systemmodule zerosnake --Os -g

yada yada yada and he's now here

"Now we have zerosnake.obj — a standard object file that is no different from object files produced by other native compilers such as C or C++. The last step is linking it."

A few more tweaks at he's at 27kb! He then pulls off a few linker switches to disable and strip various things - using the same techniques that native developers use and the result is 8176 bytes. Epic.

link.exe /debug:full /subsystem:console zerosnake.obj /entry:__managed__Main kernel32.lib ucrt.lib /merge:.modules=.rdata /merge:.pdata=.rdata /incremental:no /DYNAMICBASE:NO /filealign:16 /align:16

a

What's the coolest and craziest place you've ever run .NET code? Go follow Michal on Twitter and give him some applause.


Sponsor: Like C#? We do too! That’s why we've developed a fast, smart, cross-platform .NET IDE which gives you even more coding power. Clever code analysis, rich code completion, instant search and navigation, an advanced debugger... With JetBrains Rider, everything you need is at your fingertips. Code C# at the speed of thought on Linux, Mac, or Windows. Try JetBrains Rider 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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

My Interview and Podcast Production Process on the Hanselminutes Podcast

January 15, 2020 Comment on this post [9] Posted in Podcast
Sponsored By

artwork 300x300Hey! Did you know I have a podcast? A few actually but Hanselminutes has been doing for over 700 episodes over 13 years and it's pretty good if I may say so myself. It's a 30 min show meant for your commute. It offers fresh faces and a fresh perspective on lots of topics. While it's often tech and programming-focused, I do often have guests on to talk about less techie things like relationships, mental health, life hacks and more. I model the show after Fresh Air with Terry Gross.

I recently got a tweet from Xi Xaio asking how I host my show. The planning, the content, the restricted timing, the energy, avoiding wasted time and words, etc. Getting a good question is a gift as it leads to a blog post! So thank you Xi for this gift.

If you work for NPR, you're welcome to put all 350 hours of the show on any public radio station. I'm also available to host Fresh Air or, ahem, Science Friday, and I'd do a good job at it.

Here are Xi's questions and my answers. You might also like my article How to start your first podcast - equipment, editing, publishing and more as well.

How do you keep up the number of guests for a weekly podcast?

I haven’t had too much trouble as I just watch hacker news, Reddit, Twitter, etc and if I see someone cool I will invite them. I have 8 guests "in the can"right now so I like to stay a month or two ahead. I also prioritize quieter people. Lots of folks have a PR or press person (I get a dozen pitches a week) but the most interesting people aren't doing podcasts because they are making amazing art/tech. So I like to talk to them. I know I've gotten someone good when their response is "me? Why me?" Well, because you're making/thinking/commentating!

What drives you to keep publishing even when you are on holiday, for the promise of a new episode each week - for better audience engagement, or for the demands of the advertisers?

Consistency is key and king. If you publish regularly people start to (consciously or unconsciously) come to expect it. You can fit into their life when they know your show is every week, for example. Others “publish when they can” and that means their show has no heartbeat and can’t be counted on. Life is a marathon, not a sprint, and step one is showing up. I like to show up every week. When I took a few months off last year to stay in South Africa, I had 12 shows already recorded and scheduled before I left.

You introduce the guest on their behalf. Why not let guests do it themselves?

Because most people aren’t good at introducing themselves, advocating for themselves, or talking about themselves. I like to take a moment, be consistent and talk them up. It starts the show well because it reminds them they are awesome!

You keep the episode length within 30 mins. Guests are different, some keep talking and some are succinct. How do you achieve this goal?

A typical show has 6 bullet points, 5 minutes each, as I plan the content. I'll do a lot of research (think 50 tabs open, etc) and then I work out the story arc (where do we want to take the audience) with the guest ahead of time, and I optimize the show and conversation for that process.

We bounce bullet points back and forth over email for a while or have a preliminary Skype/Facetime.

Would you mind sharing your content producing procedures after recording? I'd love to learn what steps you take from editing to publishing, and tips to be more efficient.

I store everything in a workflow of folders in Dropbox. I have an “input raw shows” folder and an “output produced shows” folder. I use zencastr to record, and the result is a WAV file for each speaker. Then my paid producer Mandy will level the audio, edit and merge them in Audacity, then add the music, produce the MP3, add the ID3tags, and put the result in the output folder. Then she uploads it to Simplecast and schedules the show for Thursday. My custom-built podcast site then pulls the show from the Simplecast REST API and it shows up at http://hanselminutes.com.

In addition to your perseverance, what other recommendations do you have to new tech podcast hosts, like me?

Perseverance is key. No one listened to my first hundred shows. Do this for yourself first, and the audience later. 

Also, audio quality is everything. If it’s low or bad or hard to hear you’ll lose audiences. One other tip, as you get better as an interviewer the less you’ll have too edit, which will save you time. If you mess up, stop. Clap, then start again. The clap makes it easy to see the mistake (it'll be a spike on the audio waveform) and then you can do a "pull up" and just elide that portion.

What do you mean by "I optimize the show and conversation for that process"

The point of a story is the story arc. You can't just randomly chat with folks, you need to have a plan and a direction. Where are you taking the listener? How will you get them there? Are you being empathic and putting yourself in the shoes of the listener? What do they know, what do they not know?

How much should you talk?

Less. It's not about me or you, it's about the guest. I play a role. I play the foil. What is a foil?

foil - a person or thing that contrasts with and so emphasizes and enhances the qualities of another.

Here is a real show. I'm in green. I'm there to ask YOUR questions (as you're not there!) and advocate for the listener. Whether or not I know the answer or not isn't important. I'm there to expand acronyms, provide context, and guide the journey.

Talk less, listen more

Do you have a podcast? Leave a link below and share YOUR process!


Sponsor: Like C#? We do too! That’s why we've developed a fast, smart, cross-platform .NET IDE which gives you even more coding power. Clever code analysis, rich code completion, instant search and navigation, an advanced debugger... With JetBrains Rider, everything you need is at your fingertips. Code C# at the speed of thought on Linux, Mac, or Windows. Try JetBrains Rider 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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Updating my ASP.NET podcast site to System.Text.Json from Newtonsoft.Json

January 10, 2020 Comment on this post [12] Posted in DotNetCore
Sponsored By

JSON LogoNow that .NET Core 3.1 is LTS (Long Term Support) and will be supported for 3 years, it's the right time for me to update all my .NET Core 2.x sites to 3.1. It hasn't take long at all and the piece of mind is worth it. It's nice to get all these sites (in the Hanselman ecosystem LOL) onto the .NET Core 3.1 mainline.

While most of my sites working and running just fine - the upgrade was easy - there was an opportunity with the podcast site to move off the venerable Newtonsoft.Json library and move (upgrade?) to System.Text.Json. It's blessed by (and worked on by) James Newton-King so I don't feel bad. It's only a good thing. Json.NET has a lot of history and existed before .NET Standard, Span<T>, and existed in a world where .NET thought more about XML than JSON.

Now that JSON is essential, it was time that JSON be built into .NET itself and System.Text.Json also allows ASP.NET Core to existed without any compatibility issues given its historical dependency on Json.NET. (Although for back-compat reasons you can add Json.NET back with one like using AddJsonOptions if you like).

Everyone's usage of JSON is different so your mileage will depend on how much of Json.NET you used, how much custom code you wrote, and how deep your solution goes. My podcast site uses it to access a number of JSON files I have stored in Azure Storage, as well as to access 3rd party RESTful APIs that return JSON. My podcast site's "in memory database" is effectively a de-serialized JSON file.

I start by bringing in two namespaces, and removing Json.NET's reference and seeing if it compiles! Just rip that Band-Aid off fast and see if it hurts.

using System.Text.Json;
using System.Text.Json.Serialization;

I use Json Serialization in Newtonsoft.Json and have talked before about how much I like C# Type Aliases. Since I used J as an alias for all my Attributes, that made this code easy to convert, and easy to read. Fortunately things like JsonIgnore didn't have their names changed so the namespace was all that was needed there.

NOTE: The commented out part in these snippets is the Newtonsoft bit so you can see Before and After

//using J = Newtonsoft.Json.JsonPropertyAttribute;
using J = System.Text.Json.Serialization.JsonPropertyNameAttribute;

/* SNIP */

public partial class Sponsor
{
[J("id")]
public int Id { get; set; }

[J("name")]
public string Name { get; set; }

[J("url")]
public Uri Url { get; set; }

[J("image")]
public Uri Image { get; set; }
}

I was using Newtonsoft's JsonConvert, so I changed that DeserializeObject call like this:

//public static v2ShowsAPIResult FromJson(string json) => JsonConvert.DeserializeObject<v2ShowsAPIResult>(json, Converter.Settings);
public static v2ShowsAPIResult FromJson(string json) => JsonSerializer.Deserialize<v2ShowsAPIResult>(json);

In other classes some of the changes weren't stylistically the way I'd like them (as an SDK designer) but these things are all arguable either way.

For example, ReadAsAsync<T> is a super useful extension method that has hung off of HttpContent for many years, and it's gone in .NET 3.x. It was an extension that came along for the write inside Microsoft.AspNet.WebApi.Client, but it would bring Newtonsoft.Json back along for the ride.

In short, this Before becomes this After which isn't super pretty.

return await JsonSerializer.DeserializeAsync<List<Sponsor>>(await res.Content.ReadAsStreamAsync());
//return await res.Content.ReadAsAsync<List<Sponsor>>();

But one way to fix this (if this kind of use of ReadAsAsync is spread all over your app) is to make your own extension class:

public static class HttpContentExtensions
{
public static async Task<T> ReadAsAsync<T>(this HttpContent content) =>
await JsonSerializer.DeserializeAsync<T>(await content.ReadAsStreamAsync());
}

My calls to JsonConvert.Serialize turned into JsonSerializer.Serialize:

//public static string ToJson(this List<Sponsor> self) => JsonConvert.SerializeObject(self);
public static string ToJson(this List<Sponsor> self) => JsonSerializer.Serialize(self);

And the reverse of course with JsonSerializer.Deserialize:

//public static Dictionary<string, Shows2Sponsor> FromJson(string json) => JsonConvert.DeserializeObject<Dictionary<string, Shows2Sponsor>>(json);
public static Dictionary<string, Shows2Sponsor> FromJson(string json) => JsonSerializer.Deserialize<Dictionary<string, Shows2Sponsor>>(json);

All in all, far easier than I thought. How have YOU found System.Text.Json to work in your apps?


Sponsor: When DevOps teams focus on fixing new flaws first, they can add to mounting security debt. Veracode’s 2019 SOSS X report spotlights how developers can reduce fix rate times by 72% with frequent scans.

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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET 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.