Scott Hanselman

How to make a WinForms app with .NET 5 entirely from the command line and publish as one self-contained file

November 19, 2020 Comment on this post [14] Posted in DotNetCore | Open Source | Windows Client
Sponsored By

I got a lovely email from a reader named Steven who has been doing .NET for many years and is excited about .NET 5. He has an interesting perspective:

I really like the .NET library.

During 2020, I've taught myself enough Windows Forms to write my own JPG photo viewer.  Sorry but I'm not a fan of XAML, so I just write and compile raw Windows forms in C#.

Now before we start, I would offer that XAML is how you express your UI in WPF, and there is a WinForms designer for .NET Core in the latest version of Visual Studio so if you do want to mix and match using a designer and also writing your WinForms straight you can do that these days.

Steven asks:

I wonder if you could help me with a good recipe for command line compile on C#9 / .NET 5 to make a .exe?

More specifically he adds:

I want to be able to:
- from a command line
- without Visual Studio
- create a standalone .exe file for Windows
- from csharp myprog.cs
- where I don't mind if installing the Windows .NET runtime is a prerequisite
- Using C# 9 and .NET 5

Cool, I can help with that. Using only the .NET 5 SDK which you can install from http://www.dot.net, you can make a single EXE that will run on any Windows Machine in two commands, assuming you are already in a new empty folder.

~\Desktop\forsteven>
dotnet new winforms
The template "Windows Forms App" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on C:\Users\scott\Desktop\forsteven\forsteven.csproj...
Determining projects to restore...
Restored C:\Users\scott\Desktop\forsteven\forsteven.csproj (in 56 ms).
Restore succeeded.

~\Desktop\forsteven>
dotnet publish -r win-x64 /p:PublishSingleFile=true /p:IncludeNativeLibrariesForSelfExtract=true
Microsoft (R) Build Engine version 16.8.0+126527ff1 for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

Determining projects to restore...
Restored C:\Users\scott\Desktop\forsteven\forsteven.csproj (in 94 ms).
forsteven -> C:\Users\scott\Desktop\forsteven\bin\Debug\net5.0-windows\win-x64\forsteven.dll
forsteven -> C:\Users\scott\Desktop\forsteven\bin\Debug\net5.0-windows\win-x64\publish\

First I say dotnet new winforms which is the command line equivalent for "File | New Project in Visual Studio.

Next I dotnet publish -r win-x64 /p:PublishSingleFile=true /p:IncludeNativeLibrariesForSelfExtract=true which is a little extra with that last bit, but look at the design for the single file feature you'll see that if you want all the native libraries linked in you have suck in more.

Personally, I think that the last two in the list should just be one. It's not obvious but it turns out it's quite hard as you move into things like WinForms that require some native libraries. Those native libraries don't like being run while embedded in an EXE. To solve this, you can either use IncludeAllContentForselfExtract or IncludeNativeLibrariesForSelfExtract.

Self-Contained Publish

  • Normal publish: dotnet publish -r win-x64
    • Published files: HelloWorld.exe, HelloWorld.pdb, and 224 more files
  • Single-file publish Linux: dotnet publish -r linux-x64 /p:PublishSingleFile=true
    • Published files: HelloWorld, HelloWorld.pdb
  • Single-file publish Windows: dotnet publish -r win-x64 /p:PublishSingleFile=true
    • Published files: HelloWorld.exe, HelloWorld.pdb, coreclr.dll, clrjit.dll, clrcompression.dll, mscordaccore.dll
  • Single-file publish Windows with Extraction: dotnet publish -r win-x64 /p:PublishSingleFile=true /p:IncludeNativeLibrariesForSelfExtract=true
    • Published files: HelloWorld.exe, HelloWorld.pdb

So that "WithExtraction" means things get unzipped and run, while the other Single File isn't really single file (because some native bits are outside) but it avoids the temporary directory and just unfolds into memory. So it's more "Single small folder."

The resulting app is one 145 meg EXE that can be run anywhere without installing .NET 5 because we included it all in the EXE.

You can also add /p:PublishTrimmed=true and it's just 83 megs, again, just one EXE.

image

Hope this helps!


Sponsor: Need a multi-cluster load balancer and API gateway? Try VoltMesh: built for modern and distributed apps that require automation, performance and visibility. Start for free 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
Hosting By
Hosted in an Azure App Service

Spectre.Console lets you make beautiful console apps with .NET Core

November 18, 2020 Comment on this post [1] Posted in DotNetCore | Open Source
Sponsored By

I've long said, as a fan of the console and text mode, that the command line is underloved. You can do accelerated 3D VR, sure, but impress me with a nice ASCII progress bar or spinner and oh my! *Chef's kiss*

Enter yet another lovely Console library in the form of Spectre.Console. You may know Patrik Svensson as the creator of the wonderful Cake build system. He is also enhancing our consoles with Spectre.Console. It even has support for Figlet! What's FIGlet you say?!? Well, it's giant fonts with ASCII, of course!

 _____ ___ ____ _      _   
| ___|_ _/ ___| | ___| |_
| |_ | | | _| |/ _ \ __|
| _| | | |_| | | __/ |_
|_| |___\____|_|\___|\__|

Not very accessible, to be sure, but super impactful for the sighted. I encourage you to make apps that include everyone.

How cool is to bring such madness to C# and .NET!

var font = FigletFont.Load("starwars.flf");

AnsiConsole.Render(
new FigletText(font, "Hello")
.LeftAligned()
.Color(Color.Red));

That's just the start! Who ever said ASCII/ANSI style tables needed to be hard and ugly? Spectre says nay nay!

Nice Spectre.Console Animated Gif

You don't need to be fancy if you don't want to. You can just do some ANSI which is supported by nearly every console out there. Just bring in dotnet add package Spectre.Console and

using Spectre.Console

public static class Program
{
public static void Main(string[] args)
{
AnsiConsole.Markup("[underline red]Hello[/] World!");
}
}

You can render calendars!

var calendar = new Calendar(2020,10);
AnsiConsole.Render(calendar);

Giving you

         2020 October
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│ Sun │ Mon │ Tue │ Wed │ Thu │ Fri │ Sat │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│ │ │ │ │ 1 │ 2 │ 3 │
│ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ 10 │
│ 11 │ 12 │ 13 │ 14 │ 15 │ 16 │ 17 │
│ 18 │ 19 │ 20 │ 21 │ 22 │ 23 │ 24 │
│ 25 │ 26 │ 27 │ 28 │ 29 │ 30 │ 31 │
│ │ │ │ │ │ │ │
└─────┴─────┴─────┴─────┴─────┴─────┴─────┘

But tables are where Spectre.Console really shines!

There is so much good stuff in there. I wish the .NET command line would use the AnsiConsole.WriteException method, just to make my failures that much prettier!

Pretty exceptions

Regardless, get over to https://github.com/spectresystems/spectre.console and give this team a Star or two. And go make your utilities, your console apps, those little apps that are just gray and sad...go make them awesome!


Sponsor: Need a multi-cluster load balancer and API gateway? Try VoltMesh: built for modern and distributed apps that require automation, performance and visibility. Start for free 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
Hosting By
Hosted in an Azure App Service

Your dotnet outdated is outdated! Update and help keep your .NET projects up to date

November 12, 2020 Comment on this post [9] Posted in DotNetCore | Open Source
Sponsored By

I've talked about the dotnet-outdated tool before but now it's, ahem, outdated. It's moved to new owners so head over to your command line and update "dotnet-outdated" like this:

dotnet tool uninstall --global dotnet-outdated
dotnet tool install --global dotnet-outdated-tool

Just copy paste those and you'll be updated. Yes, it's changed it's moniker but the tool is the same and you still invoke it with "dotnet outdated." You can learn more about the wonderful dotnet outdated tool on their GitHub! Take a moment, Dear Reader, and give them a GitHub Star!

Now, here's the output of dotnet outdated on my own podcast's website

dotnet outdated finds older NuGet packages

I enjoy the use of color with this command line tool. Note that it's calling out that there may be some real Breaking Changes with some of these version number moves. Updating to a major version could be scary, so I'll take extra care there.

If I was feeling super lucky, I could do a dotnet outdated -u and have it automatically upgrade all my references and then test the resulting project. I could also update just a few, or do them one at a time. If you combine dotnet outdated with Github bots like Dependabot you can really get a handle all libraries updates once and for all.

dotnet outdated
No outdated dependencies were detected

Woohoo!


Sponsor: Have you tried developing in Rider yet? This fast and feature-rich cross-platform IDE improves your code for .NET, ASP.NET, .NET Core, Xamarin, and Unity applications on Windows, Mac, and Linux.

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

How to change the background of your Windows Terminal settings

November 10, 2020 Comment on this post [4] Posted in Win10
Sponsored By

I've often asked for my Windows Terminal's settings.json (formerly profiles.json) so I keep it up on GitHub. The thing is, all my machines are different. I mix it up, I change it.

Remember that the Windows Terminal is approaching version 1.5 today! Make sure you upgrade and read about the new features! This version includes clickable hyperlinks! UPGRADE NOW.

Get Windows Terminal free from the Store. You can also get it from GitHub's releases but I recommend the store because it'll stay up to date automatically.

Here's what my Terminal looks like today! I've added transparent PNGs in the lower right corners of each shell so I can keep track, but it's also nice for teaching folks how to use the Command Line.

Here's the settings block for PowerShell, for example. Note the backgroundImage* items:

{
"guid": "{574e775e-4f2a-5b96-ac1e-a2962a402336}",
"hidden": false,
"name": "PowerShell",
"source": "Windows.Terminal.PowershellCore",
"backgroundImage": "D:\\Dropbox\\utils\\TerminalBackgrounds\\powershell-2-400x225.png",
"backgroundImageStretchMode": "none",
"backgroundImageAlignment": "bottomRight",
"colorScheme": "Campbell Powershell"
},

I keep my background images in DropBox or OneDrive so they can be referred to from any of my computers. You can make stretch wallpaper-like images, or you can make subtle (or less subtle, like mine) logo watermarks.

Lovely backgrounds for your Windows Terminal

Here's the PNG backgrounds for these images. I also put this images at https://github.com/shanselman/PrettyWindowsTerminalThings and you're welcome to put nice ones and your own tips up there as well!

dos

powershell-2-400x225

ubuntu_white-orange_hex_su

Thanks to https://www.powershellmagazine.com/ for the use of their PowerShell Logo! Also check out How to make a pretty prompt in Windows Terminal with Powerline, Nerd Fonts, Cascadia Code, WSL, and oh-my-posh.


Sponsor: Have you tried developing in Rider yet? This fast and feature-rich cross-platform IDE improves your code for .NET, ASP.NET, .NET Core, Xamarin, and Unity applications on Windows, Mac, and Linux.

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

Creating a question friendly environment

November 05, 2020 Comment on this post [0] Posted in Musings
Sponsored By

christina-wocintechchat-com-MkxWUzCuYkE-unsplashA few years back I had a lovely podcast conversation with technical leader Keavy McMinn.

Sometimes I wonder if anyone listens to the show. Then a nice comment will come in when someone listen to an episode years ago and is still thinking about particular quote or line.

Last week I got an email asking about a blog post or podcast that I might have written, and the person wanted me to dig up the quote on a specific topic. It turns out it was from that podcast episode with Keavy. Keavy talks a lot about technical leadership on her blog and you should check it out.

I recently added Transcripts to all 400 HOURS of the podcast and you can search the entire 15 year episode archive in one place at Podscribe!

One of the topics around leadership I've been thinking about a lot lately is how to make work a "question friendly environment." You may hear the term "safe space" to refer to this kind of thing.

"We are missing out on valuable opportunities to connect and grow in our understanding of people if we aren’t giving one another permission to ask each other ignorant questions" - from Viewpoint

Some people come up at your later in career might say, "you should just ask your question don't be a wimp." However, when we do this I think we forget what it was like to be just a few years out of school. You know you don't know anything, but you really don't know how much you don't know.

In my opinion, the number one thing that we can do make more senior engineers, is to give the junior engineers a really good place to ask lots of dumb questions. That means replying to them with patience, providing them with resources to learn and explore, not scoffing or rolling our eyes. You too were once early in career, Dear Reader. Being given a place and permission to ask questions without judgment is a huge gift!

Permission to ask

As a manager, we need to explicitly offer the permission to ask. Talk about permission to ask questions up front, and model that behavior so that others know it's OK. Make sure that folks know you're not going to "flip the bozo bit" just because someone asked a question about DNS.

From Scott Ginsberg, If you want to build this type of environment, there are four key tasks ahead:

1. List the reasons why employees might (not) ask questions.
2. Maintain a question-friendly attitude.
3. Affirm your employees when they ask questions.
4. Reinforce a question-friendly environment.

Make it so that questions can also be asked anonymously. Take their technical questions and consider them from their perspective. They may be missing historical context but they add a new diverse point of view or a fresh technical spin.

What are you doing in your technical teams and at your company to make sure that folks feel they can ask technical questions without judgment?


Sponsor: Suffering from a lack of clarity around software bugs? Give your customers the experience they deserve and expect with error monitoring from Raygun.com. Installs in minutes, try it 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
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.