Quantcast
Channel: Scott Hanselman's Blog
Viewing all 1148 articles
Browse latest View live

dotnet sdk list and dotnet sdk latest

$
0
0

dotnet sdk listCan someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes!

Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constantly go into c:\Program Files\dotnet in order to get a list of the currently installed SDKs. I proposed that Microsoft make a "dotnet sdk list" command and the ability to pin down versions like "dotnet sdk 1.0.4" and even maybe install new ones with "dotnet sdk install 2.1.0" or something.

Fanie did all this for us except the installation part, and his implementation is clean and simple. It's so simple that I just dropped his commands into my Dropbox's Utils folder that I have in my PATH on all my machines. Now every machine I dev on has this extension.

Note that if I type "dotnet foo" the dotnet.exe driver will look in the path for an executable command called dotnet-foo.* and run it.

C:\Users\scott\Desktop>dotnet foo

No executable found matching command "dotnet-foo"

C:\Users\scott\Desktop>dotnet sdk
No executable found matching command "dotnet-sdk"

He created a dotnet-sdk.cmd you can get on his GitHub. Download his repo and put his command somewhere in your path. Now I can do this:

C:\Users\scott\Desktop>dotnet sdk list

The installed .NET Core SDKs are:
1.0.0
1.0.0-preview2-003131
1.0.0-rc3-004530
1.0.2
1.0.4

Which is lovely, but the real use case is this:

C:\Users\scott\Desktop\fancypants>dotnet --version

1.0.4

C:\Users\scott\Desktop\fancypants>dotnet sdk 1.0.0
Switching .NET Core SDK version to 1.0.0

C:\Users\scott\Desktop\fancypants>dotnet --version
1.0.0

C:\Users\scott\Desktop\fancypants>dir
Volume in drive C is Windows
Directory of C:\Users\scott\Desktop\fancypants

07/26/2017 04:53 PM 47 global.json
1 File(s) 47 bytes

Then if I go "dotnet sdk latest" it just deletes the global.json. Perhaps in a perfect world it should just remove the sdk JSON node in case global.json has been modified, but for now it's great. Without the global.json the dotnet.exe will just use your latest installed SDK.

This works with .NET Core 2.0 as well. This should be built-in, but for now it's a very nice example of a clean extension to dotnet.exe.

Oh, and by the way, he also made a ".net.cmd" so you can do this with all your dotnet.exe commands.

.NET run

Give these commands a try!


Sponsor: Check out JetBrains Rider: a new cross-platform .NET IDE. Edit, refactor, test and debug ASP.NET, .NET Framework, .NET Core, Xamarin or Unity applications. Learn more and download a 30-day trial!



© 2017 Scott Hanselman. All rights reserved.
     

Peachpie - Open Source PHP Compiler to .NET and WordPress under ASP.NET Core

$
0
0

The Peachpie PHP compiler project joined the .NET Foundation this week and I'm trying to get my head around it. PHP in .NET? PHP on .NET? Under .NET? What compiles to what? Why would I want this? How does it work? Does it feel awesome or does it feel gross?

image

Just drink this in.

C:\Users\scott\Desktop\peachcon> type program.php

<?php

function main()
{
echo "Hello .NET World!";
}

main();

C:\Users\scott\Desktop\peachcon> dotnet run
Hello .NET World!

Just like that. Starting from a .NET SDK (They say 1.1, although I used a 2.0 preview) you just add their templates

dotnet new -i Peachpie.Templates::*

Then dotnet new now shows a bunch of php options.

C:\Users\scott\Desktop\peachcon> dotnet new | find /i "php"

Peachpie console application peachpie-console PHP Console
Peachpie Class library peachpie-classlibrary PHP Library
Peachpie web application peachpie-web PHP Web/Empty

dotnet new peachpie-console for example, then dotnet restore and dotnet run. Boom.

NOTE: I did have to comment out his one line "<Import Project="$(CSharpDesignTimeTargetsPath)" />" in their project file that doesn't work at the command line. It's some hack they did to make things work in Visual Studio but I'm using VS Code. I'm sure it's an alpha-point-in-time thing.

It's really compiling PHP into .NET Intermediate Language!

PHP to .NET

You can see my string here:

Hello .NET World inside a PHP app inside the CLR

But...why? Here's what they say, and much of it makes sense to me.

  1. Performance: compiled code is fast and also optimized by the .NET Just-in-Time Compiler for your actual system. Additionally, the .NET performance profiler may be used to resolve bottlenecks.
  2. C# Extensibility: plugin functionality can be implemented in a separate C# project and/or PHP plugins may use .NET libraries.
  3. Sourceless distribution: after the compilation, most of the source files are not needed.
  4. Power of .NET: Peachpie allows the compiled WordPress clone to run in a .NET JIT'ted, secure and manageable environment, updated through windows update.
  5. No need to install PHP: Peachpie is a modern compiler platform and runtime distributed as a dependency to your .NET project. It is downloaded automatically on demand as a NuGet package or it can be even deployed standalone together with the compiled application as its library dependency.

PHP does have other VMs/Runtimes that are used (beyond just PHP.exe) but the idea that I could reuse code between PHP and C# is attractive, not to mention the "PHP as dependency" part. Imagine if I have an existing .NET shop or project and now I want to integrate something like WordPress?

PHP under ASP.NET Core

Their Web Sample is even MORE interesting, as they've implemented PHP as ASP.NET Middleware. Check this out. See where they pass in the PHP app as an assembly they compiled?

using Peachpie.Web;


namespace peachweb.Server
{
class Program
{
static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls("http://*:5004/")
.UseStartup<Startup>()
.Build();

host.Run();
}
}

class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();

services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.CookieHttpOnly = true;
});
}

public void Configure(IApplicationBuilder app)
{
app.UseSession();

app.UsePhp(new PhpRequestOptions(scriptAssemblyName: "peachweb"));
app.UseDefaultFiles();
app.UseStaticFiles();
}
}
}

Interesting, but it's still Hello World. Let's run WordPress under PeachPie (and hence, under .NET). I'll run MySQL in a local Docker container for simplicity:

docker run -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=wordpress -p 3306:3306 -d mysql

I downloaded WordPress from here (note they have the "app" bootstrapper" that hosts .NET and then runs WordPress) restore and run.

WordPress under .NET Core

It's early and it's alpha - so set your expectations appropriately - but it's surprisingly useful and appears to be under active development.

What do you think?

Be sure to explore their resources at http://www.peachpie.io/resources and watch their video of WordPress running on .NET. It's all Open Source, in the .NET Foundation, and the code is up at https://github.com/iolevel/ and you can get started here: http://www.peachpie.io/getstarted


Sponsor: Check out JetBrains Rider: a new cross-platform .NET IDE. Edit, refactor, test and debug ASP.NET, .NET Framework, .NET Core, Xamarin or Unity applications. Learn more and download a 30-day trial!


© 2017 Scott Hanselman. All rights reserved.
     

A proper terminal for Visual Studio

$
0
0

Whack Whack Terminal is an experimental free plugin for Visual Studio 2017 that aims to bring a full terminal inside of Visual Studio. Those of you who use Visual Studio Code have long enjoyed the integrated xtermjs terminal. Justin Clareburt worked with Daniel Griffen on hacking together this solution as an experiment. There is no plans for it to be more than an experiment, I'm told BUT I always say vote with your feet. I figure a few tens of thousands of installs and someone will decide to build it in. I have long used Mads Kristensen's Quake Mode that lets me launch a command prompt from VS, but ever since the NuGet Package manager showed up in VS many years ago, I've always wanted a real FULL terminal in VS.

Today, the code is alpha quality, so expect it will actively improve, and don't be mean in the GitHub Issues. They've versioned it at 0.2, and is aiming for parity with the features in the terminal in VSCode for version 1.0.

Still, go install WhackWhack in VS2017 NOW! Nothing ventured, nothing gained!

Hey it's a real terminal inside of Visual Studio

I'm sure they will update it with lots of great features like changing the fonts and colors, but if you want to hack away (as of the date of this blog post) you can mess around in C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\sjogt3hc.qcl\daytona with ZERO WARRENTY EXPRESS OR IMPLIED. I went into there and edited the default.css file by removing all the comments and changing the background-color to black, the text to white, and adding a font-family choosing Consolas. If you do that, you'll likely need to uninstall/reinstall at some point when REAL customizations come. Again, alpha. But awesome.

"Whack" is a shorthand word for a slash (forward or otherwise) and the default hotkey is Ctrl+\, Ctrl+\. That's twice. so Ctrl WHACK WHACK. When you use the hotkey it will open the folder in the same folder as the currently selected project in the Solution Explorer.

If you want to change the hotkey to something else (like a more sensible Ctrl+~) you can do it in Tools | Options | Keyboard like this.

Changing the hotkey for the terminal

Then assign a new one by clicking in Press Shortcut Keys and typing "Ctrl+`" (which to me, is Ctrl ~ on my keyboard, without the shift)

Changing the hotkey for the terminal

By default the shell is PowerShell, but there's also places to support bash/Ubuntu, etc. For now, if you want bash, you can type C:\windows\sysnative\bash.exe in the terminal.

And just to freak you out, here's top running inside Visual Studio.

And just to freak you out, here's top running inside Visual Studio.

Enjoy! Install "WhackWhackTerminal" from here.



© 2017 Scott Hanselman. All rights reserved.
     

.NET and WebAssembly - Is this the future of the front-end?

$
0
0

6 years ago Erik Meijer and I were talking about how JavaScript is/was an assembly language. It turned into an interesting discussion/argument (some people really didn't buy it) but it still kept happening. Currently WebAssembly world is marching forward and is supported in Chrome, Firefox, and in Development in Edge, Opera, and Safari.

"The avalanche has begun, it's too late for the pebbles to vote." - Ambassador Kosh

Today in 2017, WebAssembly is absolutely a thing and you can learn about it at http://webassembly.org. I even did a podcast on WebAssembly with Mozilla Fellow David Bryant (you really should check out my podcast, I'm very proud of it. It's good.)

The classic JavaScript TODO app, written with C# and .NET and Blazor

The image above is from Steve Sanderson's NDC presentation. He's writing the classic client-side JavaScript ToDo application...except he's writing the code in C#.

What is WebAssembly?

"WebAssembly or wasm is a low-level bytecode format for in-browser client-side scripting, evolved from JavaScript." You can easily compile to WebAssembly from C and C++ today...and more languages are jumping in to include WebAssembly as a target every day.

Since I work in open source .NET and since .NET Core 2.0 is cross-platform with an imminent release, it's worth exploring where WebAssembly fits into a .NET world.

Here's some projects I have identified that help bridge the .NET world and the WebAssembly world. I think that this is going to be THE hot space in the next 18 months.

WebAssembly for .NET

Despite its overarching name, this OSS project is meant to consume WASM binary files and execute them from within .NET assemblies. To be clear, this isn't compiling .NET languages' (C#, VB.NET, F#) into WebAssembly, this is for using WebAssembly as if it's any other piece of resuable compiled code. Got an existing WASM file you REALLY want to call from .NET? This is for that.

Interestingly, this project doesn't spin up a V8 or Chakra JavaScript engine to run WASM, instead it reads in the bytecode and converts them to .NET via System.Reflection.Emit. Interesting stuff!

Mono and WebAssembly

One of the great things happening in the larger .NET Ecosystem is that there is more than one ".NET" today. In the past, .NET was a thing that you installed on Windows and generally feared. Today, there's .NET 4.x+ on basically every Windows machine out there, there's .NET Core that runs in Docker, on Mac, Windows, and a dozen Linuxes...even Raspberry Pi, and Mono is another instance of .NET that allows you to run code in dozens of other platforms. There's multiple "instances of .NET" out there in active development.

The Mono Project has two prototypes using Mono and WebAssembly.

The first one uses the traditional full static compilation mode of Mono, this compiled both the Mono C runtime and the Mono class libraries along with the user code into WebAssembly code. It produces one large statically compiled application. You can try this fully statically compiled Hello World here. The full static compilation currently lives here.

So that's a totally statically compiled Hello World...it's all of Mono and your app into Web Assembly. They have another prototype with a difference perspective:

The second prototype compiles the Mono C runtime into web assembly, and then uses Mono’s IL interpreter to run managed code. This one is a smaller download, but comes at the expense of performance. The mixed mode execution prototype currently lives here.

Here they've got much of Mono running in Web Assembly, but your IL code is interpreted. One of the wonderful things about Computer Science - There is more than one way to do something, and they are often each awesome in their own way!

"Blazor" - Experimental UI Framework running .NET in the browser

With a similar idea as the Mono Project's second prototype, Steve Sanderson took yet another "instance of .NET," the six year old open source DotNetAnywhere (DNA) project and compiled it into Web Assembly. DNA was an interpreted .NET runtime written in portable C. It takes standard IL or CIL (Common Intermediate Language) and runs it "on resource-constrained devices where it is not possible to run a full .NET runtime (e.g. Mono)." Clever, huh? What "resource-constrained device do we have here six years later?" Why, it's the little virtual machine that could - the JavaScript VM that your browser already has, now powered by a standard bytecode format called WebAssembly.

To prove the concept, Steve compiles DotNetAnywhere to WASM but then takes it further. He's combined standard programming models that we see on the web with things like Angular, Knockoutjs, or Ember, except rather than writing your web applications' UI in JavaScript, you write in C# - a .NET language.

Here in the middle of some Razor (basically HTML with C# inline) pages, he does what looks like a call to a backend. This is C# code, but it'll run as WASM on the client side within a Blazor app.

@functions {

WeatherForecast[] forecasts;

override protected async Task InitAsync()
{
using (var client = new HttpClient())
{
var json = await client.GetStringAsync(AbsoluteUrl("/api/SampleData/WeatherForecasts"));
forecasts = JsonUtil.Deserialize<WeatherForecast[]>(json);
}
}
}

This would allow a .NET programmer to use the same data models on the client and the server - much like well-factored JavaScript should today - as well as using other .NET libraries they might be familiar or comfortable with.

Why do this insane thing? "To see how well such a framework might work, and how much anyone would care." How far could/should this go? David Fowler already has debugging working (again this is ALL prototypes) in Visual Studio Code. Don't take my word for it, watch the video as Steve presents the concept at the NDC Conference.

Blazor as a prototype has a number of people excited, and there was a Blazor Hackthon recently that produced some interesting samples including a full-blown app.

Other possibilities?

There's lots of other projects that are compiling or transpiling things to JavaScript. Could they be modified to support WebAssembly? You can take F# and compile it to JavaScript with F#'s Fable project, and some folks have asked about WebAssembly.

At this point it's clear that everyone is prototyping and hacking and enjoying themselves.

What do YOU think about WebAssembly?



© 2017 Scott Hanselman. All rights reserved.
     

Exploring refit, an automatic type-safe REST library for .NET Standard

$
0
0

I dig everything that Paul Betts does. He's a lovely person and a prolific coder. One of his recent joints is called Refit. It's a REST library for .NET that is inspired by Square's Retrofit library. It turns your REST API into a live interface:

public interface IGitHubApi

{
[Get("/users/{user}")]
Task<User> GetUser(string user);
}

That's an interface that describes a REST API that's elsewhere. Then later you just make a RestService.For<YourInterface> and you go to town.

var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");


var octocat = await gitHubApi.GetUser("octocat");

imageThat's lovely! It is a .NET Standard 1.4 library which means you can use it darn near everywhere. Remember that .NET Standard isn't a runtime, it's a version interface - a list of methods you can use under many different ".NETs." You can use Refit on UWP, Xamarin.*, .NET "full" Frameowrk, and .NET Core, which runs basically everywhere.

Sure, you can make your own HttpClient calls, but that's a little low level and somewhat irritating. Sure, you can look for a .NET SDK for your favorite REST interface but what if it doesn't have one? It strikes a nice balance between the low-level and the high-level.

I'll give an example and use it as a tiny exercise for Refit. I have a service that hosts a realtime feed of my blood sugar, as I'm a Type 1 Diabetic. Since I have a Continuous Glucose Meter that is attached to me and sending my sugar details to a web service called Nightscout running in Azure, I figured it'd be cool to use Refit to pull my sugar info back down with .NET.

The REST API for Nightscout is simple, but doe have a lot of options, query strings, and multiple endpoints. I can start by making a simple interface for the little bits I want now, and perhaps expand the interface later to get more.

For example, if I want my sugars, I would go

https://MYWEBSITE/api/v1/entries.json?count=10

And get back some JSON data like this:

[

{
_id: "5993c4aa8d60c09b63ba1c",
sgv: 162,
date: 1502856279000,
dateString: "2017-08-16T04:04:39.000Z",
trend: 4,
direction: "Flat",
device: "share2",
type: "sgv"
},
{
_id: "5993c37d8d60c09b93ba0b",
sgv: 162,
date: 1502855979000,
dateString: "2017-08-16T03:59:39.000Z",
trend: 4,
direction: "Flat",
device: "share2",
type: "sgv"
}
]

Where "sgv" is serum glucose value, or blood sugar.

Starting with .NET Core 2.0 and the SDK that I installed from http://dot.net, I'll first make a console app from the command line and add refit like this:

C:\users\scott\desktop\refitsugars> dotnet new console

C:\users\scott\desktop\refitsugars> dotnet add package refit

Here's my little bit of code.

  • I made an object shaped like each recorded. Added aliases for weirdly named stuff like "sgv"
  • COOL SIDE NOTE: I added <LangVersion>7.1</LangVersion> to my project so I could have my public static Main entry point be async. That's new as many folks have wanted to have a "public static async void Main()" equivalent.

After that it's REALLY lovely and super easy to make a quick strongly-typed REST Client in C# for pretty much anything. I could see myself easily extending this to include the whole NightScout diabetes management API without a lot of effort.

using Newtonsoft.Json;

using Refit;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace refitsugars
{
public interface INightScoutApi
{
[Get("/api/v1/entries.json?count={count}")]
Task<List<Sugar>> GetSugars(int count);
}

public class Sugar
{
[JsonProperty(PropertyName = "_id")]
public string id { get; set; }

[JsonProperty(PropertyName = "sgv")]
public int glucose { get; set; }

[JsonProperty(PropertyName = "dateString")]
public DateTime itemDate { get; set; }
public int trend { get; set; }
}

class Program
{
public static async Task Main(string[] args)
{
var nsAPI = RestService.For<INightScoutApi>("https://MYURL.azurewebsites.net");
var sugars = await nsAPI.GetSugars(3);
sugars.ForEach(x => { Console.WriteLine($"{x.itemDate.ToLocalTime()} {x.glucose} mg/dl"); });
}
}
}

And here's the result of the run.

PS C:\Users\scott\Desktop\refitsugars> dotnet run

8/15/2017 10:29:39 PM 110 mg/dl
8/15/2017 10:24:39 PM 108 mg/dl
8/15/2017 10:19:40 PM 109 mg/dl

You should definitely check out Refit. It's very easy and quite fun. The fact that it targets .NET Standard 1.4 means you can use it in nearly all your .NET projects, and it already has creative people thinking of cool ideas.


Sponsor: Check out JetBrains Rider: a new cross-platform .NET IDE. Edit, refactor, test and debug ASP.NET, .NET Framework, .NET Core, Xamarin or Unity applications. Learn more and download a 30-day trial!


© 2017 Scott Hanselman. All rights reserved.
     

Draft - .NET Glossary Diagram

$
0
0

I'm working on this slide as support for this excellent .NET Glossary. It's not done yet, but I'm curious for your thoughts. Every system has terms and concepts that are initially unfamiliar but make sense once you grok them.

image

Here are these concepts used in an example sentence, for context:

  • Application Framework - “Are you using the ASP.NET Core web framework for that microservice?”
  • Metapackage - “I want to install the ASP.NET Core framework; it’s a package of packages”
  • Package/NuGet - “I know there’s a NuGet package for decoding JSON.”
  • Library/Assembly - “Now, you’ll compile your source into an assembly”
  • .NET Standard – “Which version of the .NET Standard specification does your assembly target?"
    • "My Apple Watch supports .NET Standard 1.6 but my Windows 10 laptop supports 2.0 with more APIs.”
  • C#, F#, VB, etc – “Which language did you use?”
  • .NET SDK - “Did you get the developer tools?”
  • CLR/CoreCLR – “Which runtime is your app using?”
  • An implementation of .NET is a runtime along with libraries that implement a version of the .NET Standard
    • “Are you using .NET Core, .NET Framework, or Mono for this project?”
  • Platform - An operating system and some hardware (ARM, x64, etc.)
    • “Is that an ASP.NET Core app running in Docker on a Raspberry Pi?”

Constructive feedback, please. This is a draft.


Sponsor: Check out JetBrains Rider: a new cross-platform .NET IDE. Edit, refactor, test and debug ASP.NET, .NET Framework, .NET Core, Xamarin or Unity applications. Learn more and download a 30-day trial!



© 2017 Scott Hanselman. All rights reserved.
     

Referencing .NET Standard Assemblies from both .NET Core and .NET Framework

$
0
0

Lots of .NET Projects sharing a .NET Standard LibraryI like getting great questions in email but I LOVE getting great questions in email with a complete and clear code repro (reproduction) that's in a git somewhere. Then I can just clone, build (many many bonus points for a clean build) and check out the bug.

I got a great .NET Core question and repro here https://github.com/ScarlettCode/Example. I forked it, fixed it, and submitted a PR. Here's the question and issue and today's fix.

The project has a C# library project (an assembly) that is written to the .NET Standard 2.0. You'll recall that the .NET Standard isn't a runtime or a library in itself, but rather an interface. They are saying that this library will work anywhere that the .NET Standard is supported, like Linux, Mac, and Windows.

Here's that main .NET Standard Library called "Example.Data" written in C#.

Then he had:

  • Windows Forms (WinForms) application in VB.NET using .NET "full" Framework 4.6
  • Console Application also using .NET Framework 4.6
  • Console Application using .NET Core 2.0

Each of these apps is referring to the Example.Data library. The Example.Data library then pulls in a database access library in the form of Microsoft.EntityFrameworkCore.InMemory via NuGet.

WinForms app -> Data Access library -> Some other library. A->B->C where B and C are packages from NuGet.

The .NET Core console builds and runs great. However, when the other projects are run you get this error:

Can't load

Could not load file or assembly
'Microsoft.EntityFrameworkCore, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=adb9793829ddae60'
or one of its dependencies. The system cannot find
the file specified.

Pretty low level error, right? First thing is to check the bin folder (the results of the compile) for a project that doesn't run. Looks like there's no Microsoft.EntityFrameworkCore there. Why not? It's assembly "C" downstream of "A" and "B". EntityFramework's assembly is referred to by the Example.Data assembly...but why didn't it get copied in?

The "full" Framework projects are using the older .csproj format and by default, they use package.config to manage dependencies. The newer projects can reference Packages as first-class references. So we need to tell ALL projects in this solution to manage and restore their packages as "PackageReferences."

I can open up the .csproj file for the Framework projects and add this line within the first <PropertyGroup> like this to change the restore style:

 <RestoreProjectStyle>PackageReference</RestoreProjectStyle>

As Oren wisely says:

"Using .NET Standard requires you to use PackageReference to eliminate the pain of “lots of packages” as well as properly handle transitive dependencies. While you may be able to use .NET Standard without PackageReference, I wouldn’t recommend it."

I can also change the default within VS's Package Management options here in this dialog.

 <RestoreProjectStyle>PackageReference</RestoreProjectStyle> Default Package management format

Hope this helps.



© 2017 Scott Hanselman. All rights reserved.
     

Experimental: Reducing the size of .NET Core applications with Mono's Linker

$
0
0

The .NET team has built a linker to reduce the size of .NET Core applications. It is built on top of the excellent and battle-tested mono linker. The Xamarin tools also use this linker so it makes sense to try it out and perhaps use it everywhere!

"In trivial cases, the linker can reduce the size of applications by 50%. The size wins may be more favorable or more moderate for larger applications. The linker removes code in your application and dependent libraries that are not reached by any code paths. It is effectively an application-specific dead code analysis." - Using the .NET IL Linker

I recently updated a 15 year old .NET 1.1 application to cross-platform .NET Core 2.0 so I thought I'd try this experimental linker on it and see the results.

The linker is a tool one can use to only ship the minimal possible IL code and metadata that a set of programs might require to run as opposed to the full libraries. It is used by the various Xamarin products to extract only the bits of code that are needed to run an application on Android, iOS and other platforms.

I'll add this line to a nuget.config in my project's folder. Note that NuGet will inherit global settings and ADD this line.

<?xml version="1.0" encoding="utf-8"?>

<configuration>
<packageSources>
<add key="dotnet-core" value="https://dotnet.myget.org/F/dotnet-core/api/v3/index.json" />
</packageSources>
</configuration>

Then I'll add the IL Linker's NuGet package to my project with this command line command (or from Visual Studio):

dotnet add package ILLink.Tasks -v 0.1.4-preview-906439

The assemblies will automatically be "trimmed" when they are published (not built) so I'll build it twice, disabling it with a switch:

D:\github\TinyOS\OS Project>dotnet publish -c release -r win-x64 -o notlinked /p:LinkDuringPublish=false

Microsoft (R) Build Engine version 15.3 for .NET Core

TinyOSCore -> D:\github\TinyOS\OS Project\bin\Release\netcoreapp2.0\win-x64\TinyOSCore.dll
TinyOSCore -> D:\github\TinyOS\OS Project\notlinked\

D:\github\TinyOS\OS Project>dotnet publish -c release -r win-x64 -o linked
Microsoft (R) Build Engine version 15.3 for .NET Core

TinyOSCore -> D:\github\TinyOS\OS Project\bin\Release\netcoreapp2.0\win-x64\TinyOSCore.dll
TinyOSCore -> D:\github\TinyOS\OS Project\linked\

And here's the results:

image

You can also run it with  /p:ShowLinkerSizeComparison=true and get a nice table. I've trimmed the table as it's super long.

  TinyOSCore -> D:\github\TinyOS\OS Project\bin\Release\netcoreapp2.0\win-x64\TinyOSCore.dll

Before linking (B) After linking (B) Size decrease
----------- ----------- ----------- -----------
Total size of assemblies 48,025,824 16,740,056 65.14%
----------- ----------- ----------- -----------
TinyOSCore.dll 36,352 36,352 0.00%
Microsoft.Extensions.Configuration.dll 24,584 24,584 0.00%
Microsoft.Extensions.Configuration.Abstractions.dll 20,480 20,480 0.00%
Microsoft.Extensions.Configuration.Binder.dll 24,064 24,064 0.00%
Microsoft.Extensions.Configuration.FileExtensions.dll 22,528 22,528 0.00%
Microsoft.Extensions.Configuration.Json.dll 24,072 24,072 0.00%
Microsoft.Extensions.DependencyInjection.dll 46,600 46,600 0.00%
Microsoft.Extensions.DependencyInjection.Abstractions.dll 35,336 35,336 0.00%
Microsoft.Extensions.FileProviders.Abstractions.dll 17,920 17,920 0.00%
Microsoft.Extensions.FileProviders.Physical.dll 31,240 31,240 0.00%
Microsoft.Extensions.FileSystemGlobbing.dll 39,432 39,432 0.00%
Microsoft.Extensions.Options.dll 26,120 26,120 0.00%
Microsoft.Extensions.Options.ConfigurationExtensions.dll 16,904 16,904 0.00%
Microsoft.Extensions.Primitives.dll 33,800 33,800 0.00%
Newtonsoft.Json.dll 639,488 639,488 0.00%
Microsoft.CSharp.dll 1,092,096 392,192 64.09%
Microsoft.VisualBasic.dll 465,416 0 100.00%
Microsoft.Win32.Primitives.dll 18,968 4,608 75.71%
Microsoft.Win32.Registry.dll 85,008 0 100.00%
SOS.NETCore.dll 54,264 0 100.00%
System.AppContext.dll 14,336 2,560 82.14%
System.Buffers.dll 14,336 2,560 82.14%
System.Collections.Concurrent.dll 206,360 31,744 84.62%
System.Collections.Immutable.dll 2,378,264 0 100.00%
System.Collections.NonGeneric.dll 96,792 24,576 74.61%
System.Collections.Specialized.dll 88,608 15,360 82.67%
System.Collections.dll 326,664 52,224 84.01%

TinyOSCore -> D:\github\TinyOS\OS Project\bin\Release\netcoreapp2.0\win-x64\publish\

You can see in some places where there's no size decrease. That's because I'm using those assemblies completely. Some see a 100% decrease - they've been removed entirely - because I'm not using the Registry, for example. And some see a fractional decrease because I'm using some methods but not others.

You can check out the full instructions and try this yourself at https://github.com/dotnet/core/blob/master/samples/linker-instructions.md. Again, it's a work in progress.


Sponsor: Check out JetBrains Rider: a new cross-platform .NET IDE. Edit, refactor, test and debug ASP.NET, .NET Framework, .NET Core, Xamarin or Unity applications. Learn more and download a 30-day trial!



© 2017 Scott Hanselman. All rights reserved.
     

Cloud Database? NoSQL? Nah, just use CSVs and CsvHelper

$
0
0

KISS - Keep it Simple, Stupid. While I don't like calling people stupid, I do like to Keep it Super Simple!

I was talking to Jeff Fritz on my team about a new system we're architecting. I suggested CosmosDB or perhaps Azure Table Storage. Then we considered the amount of data we were storing (less than 100 megs) and Jeff said...let's just use CSV files and CsvHelper.

First I was shocked. SHOCKED I SAY.

via GIPHY

Then I was offended

via GIPHY

But finally I was hey...that's a good idea.

via GIPHY

A fine idea in fact. Why use more moving parts than needed? Sure we could use XML or JSON, but for our project we decided rather than even bother with an admin site that we'd use Excel for administration! It edits CSV files nicely thank you very much.

Can you parse CSV files yourself? Sure, but it'll start getting complex as you move between data types, think about quotes, deal with headers, whitespace, encoding, dates, etc. CSV files can be MUCH more complex and subtle than you'd think. Really.

Here's what CsvHelper can do for you:

var csv = new CsvReader( textReader );

var records = csv.GetRecords<MyClass>();

Here you just get an array of some class - if your class's structure maps 1:1 with your CSV file. If not, you can map your class with a projection of the types in the CSV file.

public sealed class PersonMap : CsvClassMap<Person>

{
public PersonMap()
{
Map( m => m.Id );
Map( m => m.Name );
References<AddressMap>( m => m.Address );
}
}

public sealed class AddressMap : CsvClassMap<Address>
{
public AddressMap()
{
Map( m => m.Street );
Map( m => m.City );
Map( m => m.State );
Map( m => m.Zip );
}
}

And finally, just want to export a CSV from an Enumerable that mirrors what you want? Boom.

var csv = new CsvWriter( textWriter );

csv.WriteRecords( records );

Or do it manually if you like (hardcode some, pull from multiple sources, whatever):

var csv = new CsvWriter( textWriter );

foreach( var item in list )
{
csv.WriteField( "a" );
csv.WriteField( 2 );
csv.WriteField( true );
csv.NextRecord();
}

It won't replace SQL Server but it may just replace one-table SQLite's and "using a JSON file as a database" for some of your smaller projects. Check out CsvHelper's site and excellent docs here along with the CsvHelper GitHub here.


Sponsor: Check out JetBrains Rider: a new cross-platform .NET IDE. Edit, refactor, test and debug ASP.NET, .NET Framework, .NET Core, Xamarin or Unity applications. Learn more and download a 30-day trial!



© 2017 Scott Hanselman. All rights reserved.
     

T4MVC and R4MVC - Roslyn code generators for ASP.NET Core tag helpers

$
0
0

I've always loved the T4 text generator within Visual Studio. If you are looking for T4 within Visual Studio 2017 you need to install the "Visual Studio extension development" option within the installer to access it. However, T4 development seems stalled/done and if you want to utilize some of it.

There's a nice open source project called T4MVC that you can use with Visual Studio 2015 and ASP.NET MVC to create strongly typed helpers that eliminate the use of literal strings in many places. That means instead of:

@Html.ActionLink("Dinner Details", "Details", "Dinners", new { id = Model.DinnerID }, null)

T4MVC lets you write

@Html.ActionLink("Dinner Details", MVC.Dinners.Details(Model.DinnerID))

Fast forward to 2017 and that team is working on a new project called R4MVC...it's a code generator that's based on Roslyn, the .NET Compiler Platform (hence the R).

It also lets you update your @Html.ActionLinks to be strongly typed, but more importantly it lets you extend that to strongly typed taghelpers, so instead of:

<a asp-action="Details" asp-controller="Dinners" asp-route-id="@Model.DinnerID">Dinner Details</a>

you can write

<a mvc-action="MVC.Dinners.Details(Model.DinnerID)">Dinner Details</a>

It's generating the URL for that <a> tag using the method and parameter.

Using an ASP.NET Core 1.1 app (2.0 is coming soon they say) I'll add the NuGet packages R4Mvc.Tools and R4Mvc, making sure to "include prerelease."

Adding R4Mvc.Tools in NuGet

I'll run "Generate-R4MVC" in the Package Manager Console.

Generate-R4MVC

There is a new R4Mvc.generated.cs file that gets created, and inside it is a whole bunch of classes based on the files on disk. For example I can type @Links.css, or @Links.lib and start getting intellisense for all my files on disk like JavaScript or CSS.

Links.css

When returning a view, rather than return View("About") I can do return View(Views.About):

return View(Views.About)

The R4MVC project also has Tag Helpers so their mvc-action attribute gives you strong typing like this:

<a mvc-action="MVC.Home.Index()">

This R4MVC project is just getting started, but I'm sure they'd appreciate your support! Head over to https://github.com/T4MVC/R4MVC/issues and learn about what they are planning and perhaps help out!

What do you think? Do you think there's value in smarter or strongly-typed URL generation with ASP.NET?


Sponsor: Raygun provides real time .NET error monitoring and supports all other major programming languages and frameworks too! Forget logs and support tickets. Reproduce software bugs in minutes with Raygun's error tracking software!



© 2017 Scott Hanselman. All rights reserved.
     

Experiments in Open Source: Exploring vcr-sharp for Http record and playback

$
0
0

I've always said that reading source code is as important as write it - especially as part of the learning process. You learn a ton about how other coders think and solve problems, plus you learn about lots of new libraries and methods you may not be familiar with.

Last week I noticed this tweet from Brendan Forster about an experiment he's working on. He is interesting in your feedback on his experiment and if you would use it.

He's created a new library for .NET called vcr-sharp that is inspired by the vcr Ruby gem and the scotch .NET library.

Again, he's made it clear he's just experimenting but I think this has some interesting potential.

Vcr-sharp lets you record and playback HTTP requests! In this example, WithCassette is an extension method on HttpClientFactory. That extension method sets up a DelgatingHandler to a ReplayingHandler. That ReplayingHandler "loads the cassette" and returns it as a cached response.

using (var httpClient = HttpClientFactory.WithCassette("my-test-scenario"))

{
var request = new HttpRequestMessage(HttpMethod.Get, "http://www.iana.org/domains/reserved");
var response = await httpClient.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
body.ShouldContain("Example domains");
}

Also worth noting is that within the VCR-Sharp library Brendan uses an assertion library for .NET called "Shouldly." Shouldly has some interesting extension methods that let you express how you Assert within your Tests.

They say - this is the old Assert way:

Assert.That(contestant.Points, Is.EqualTo(1337));

For your troubles, you get this message, when it fails:

Expected 1337 but was 0

They say - this is how it Should be:

contestant.Points.ShouldBe(1337);

Which is just syntax, so far, but check out the message when it fails:

contestant.Points should be 1337 but was 0

Another example:

Assert.That(map.IndexOfValue("boo"), Is.EqualTo(2));    // -> Expected 2 but was 1
map.IndexOfValue("boo").ShouldBe(2);                    // -> map.IndexOfValue("boo") should be 2 but was 1

It makes tests very easy to read. A nice bit of syntactic sugar:

[Fact]

public async Task AppendsNewRequestToCache()
{
Environment.SetEnvironmentVariable("VCR_MODE", "Cache");
var session = "append-second-request";

using (var httpClient = HttpClientFactory.WithCassette(session))
{
var request = new HttpRequestMessage(HttpMethod.Get, "https://www.iana.org/performance/ietf-statistics");
var response = await httpClient.SendAsync(request);
}

var cassette = await ReadCassetteFile(session);
cassette.http_interactions.Length.ShouldBe(2);
}

It also uses BenchmarkDotNet, which you may be familiar with. It allows you to mark methods as [Benchmark] methods and you'll get smart warming up, running, teardowns and statistics like this;

[Benchmark]

public async Task ReadFromCache()
{

using (var httpClient = HttpClientFactory.WithCassette("example-test"))
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://www.iana.org/domains/reserved");
var response = await httpClient.SendAsync(request);
}
} Output:
        Method |     Mean |    Error |   StdDev |

-------------- |---------:|---------:|---------:|
ReadFromCache | 684.1 us | 3.154 us | 2.796 us |

I'd encourage you to check vcr-sharp out over at https://github.com/shiftkey/vcr-sharp, read the source code, and think about how you'd use it. I am sure Brendan would appreciate your thoughts and feedback in the GitHub Issues! Also check out how he uses Tests, Shouldly, and BenchmarkDotNet in his project and consider how you'd use them in yours!


Sponsor: Raygun provides real time .NET error monitoring and supports all other major programming languages and frameworks too! Forget logs and support tickets. Reproduce software bugs in minutes with Raygun's error tracking software!



© 2017 Scott Hanselman. All rights reserved.
     

The ASP.NET Interns ship their project - A basic blog template for .NET Core

$
0
0

The internsThe Visual Studio Tools team had some great interns this summer. Juliet Daniel, Lucas Isaza, and Uma Lakshminarayan have been working all summer and one of their projects was to make something significant with ASP.NET Core and .NET Core. They decided to write a blog template. This is interesting as none of them had written C# or .NET before. Python, C, JavaScript, but not C#. This was a good exercise for them to not only learn C#/.NET but also give the team real feedback on the entire process. The ASP.NET Community Standup had the interns on the show to give us a walkthrough of their process and what they thought of VS.

They did their work over at https://github.com/VenusInterns/BlogTemplate so I'd encourage you to star their repository...and maybe get involved! This is a great starter application to explore ASP.NET and possibly do a pull request (make sure to give them a heads up in an issue before refactoring/changing everything ;) ) and contribute.

The interns used ASP.NET Core's new Razor Pages as well. Razor Pages sits on (is just) MVC so while it might initially look unfamiliar, remember that it's all still using the ASP.NET Core "MVC" pattern under the hood.

When you install the  .NET Core SDK you'll get a bunch of standard templates so you can:

  • dotnet new console
  • dotnet new mvc
  • dotnet new console --language F#
  • etc

There are lots of 3rd party and community templates and the beginnings of a website to search them. I expect this to be more formal and move into docs.microsoft.com in time.

The interns made "dotnet new blog" where blog is the short name of their template. They haven't yet released their template into NuGet for folks to easily install "dotnet new -I blogtemplate.whatever," For now you'll need to clone their repo as if you were developing a template yourself. It's actually a decent way for you to learn how to make templates.

Try this, using the .NET Core 2.0 SDK.

C:\> git clone https://github.com/VenusInterns/BlogTemplate.git

C:\> dotnet new -i C:\BlogTemplate -o C:\myblog
C:\> cd \myblog\BlogTemplate
C:\myblog\BlogTemplate> dotnet run
C:\myblog\BlogTemplate (master) > dotnet run
Using launch settings from C:\myblog\BlogTemplate\Properties\launchSettings.json...
Hosting environment: Development
Content root path: C:\myblog\BlogTemplate
Now listening on: http://localhost:59938
Application started. Press Ctrl+C to shut down.

And here's my nice local new blog. It's got admin, login, comments, the basics.

image

At this point you're running a blog. You'll see there is a Solution in there and a project, and because it's a template rather than a packaged project, you can open it up in Visual Studio Code and start making changes. This is an important point. This is an "instance" that you've created. At this point you're on your own. You can expand it, update it, because it's yours. Perhaps that's a good idea, perhaps not. Depends on your goals, but the intern's goal was to better understand the "dotnet new" functionality while making something real.

Here's some of the features the interns used, in their words.

  • Entity Framework provides an environment that makes it easy to work with relational data. In our scenario, that data comes in the form of blog posts and comments for each post.
  • The usage of LINQ (Language Integrated Query) enables the developer to store (query) items from the blog into a variety of targets like databases, xml documents (currently in use), and in-memory objects without having to redesign how things are queried, but rather where they are stored.
  • The blog is built on Razor Pages from ASP.NET Core. Because of this, developers with some knowledge of ASP.NET Core can learn about the pros and cons of building with Razor Pages as opposed to the previously established MVC schema.
  • The template includes a user authentication feature, done by implementing the new ASP.NET Identity Library for Razor Pages. This was a simple tool to add that consisted of installing the NuGet package and creating a new project with the package and then transferring the previous project files into this new project with Identity. Although a hassle, moving the files from one project to the other was quite simple because both projects were built with Razor Pages.
  • Customizing the theme is fast and flexible with the use of Bootstrap. Simply download a Bootstrap theme.min.css file and add it to the CSS folder in your project (wwwroot > css). You can find free or paid Bootstrap themes at websites such as bootswatch.com. You can delete our default theme file, journal-bootstrap.min.css, to remove the default theming. Run your project, and you'll see that the style of your blog has changed instantly.

I wouldn't say it's perfect or even production ready, but it's a great 0.1 start for the interns and an interesting codebase to read and improve!

Here's some ideas if you want a learning exercise!

  • Make the serializers swappable. Can you change XML to JSON or Markdown?
  • Make an RSS endpoint!
  • Add Captcha/reCaptcha
  • Add social buttons and sharing
  • Add Google AMP support (or don't because AMP sucks)
  • Add Twitter card support

You can also just play with their running instance here. Be nice. https://venusblog.azurewebsites.net/ (Username: webinterns@microsoft.com, Password: Password.1)


Sponsor: A third of teams don’t version control their database. Connect your database to your version control system with SQL Source Control and find out who made changes, what they did, and why. Learn more!



© 2017 Scott Hanselman. All rights reserved.
     

A Functional Web with ASP.NET Core and F#'s Giraffe

$
0
0

728331198_7c1854e363_bI was watching Ody Mbegbu's YouTube Channel - it's filled with .NET Core and ASP.NET Tutorial Videos - and was checking out one in particular, "Getting Started with ASP.NET Core Giraffe." Dane Vinson pointed me to it.

There is such a great open source renaissance happening right now with new framework's and libraries popping up in the .NET Core space. I hope you check them out AND support the creators by getting involved, writing docs, filing (kind) issues, and even doing pull requests and fixing bugs or writing tests.

Ody's video was about Dustin Morris' "Giraffe" web framework. Dustin's description is "A native functional ASP.NET Core web framework for F# developers." You can check it out over at https://github.com/dustinmoris/Giraffe.

Even better, it uses the "dotnet new" templating system so you can check it out and get started in seconds.

c:> md \mygiraffeeapp & cd \mygiraffeeapp

c:\mygiraffeeapp> dotnet new -i "giraffe-template::*"
c:\mygiraffeeapp> dotnet new giraffe
The template "Giraffe Web App" was created successfully.
c:\mygiraffeeapp> dotnet run
Hosting environment: Production
Content root path: C:\mygiraffeapp
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

Boom. Now I'm checking out Giraffe's "Hello World."

Because ASP.NET Core is very modular and built on "middleware" pipelines, that means that other frameworks like Giraffe can use the bits they want and remove the bits they down. Remembering that this is F#, not C#, here you can see Giraffe adding itself to the pipeline while still using the StaticFileMiddleware.

let configureApp (app : IApplicationBuilder) =

app.UseGiraffeErrorHandler errorHandler
app.UseStaticFiles() |> ignore
app.UseGiraffe webApp

The initial readme.md for Giraffe is the docs for now, and frankly, they are excellent and easy to read. The author says:

It is not designed to be a competing web product which can be run standalone like NancyFx or Suave, but rather a lean micro framework which aims to complement ASP.NET Core where it comes short for functional developers. The fundamental idea is to build on top of the strong foundation of ASP.NET Core and re-use existing ASP.NET Core building blocks so F# developers can benefit from both worlds.

Here is a smaller Hello World. Note the use of choose and the clear and terse nature of F#:

open Giraffe.HttpHandlers

open Giraffe.Middleware

let webApp =
choose [
route "/ping" >=> text "pong"
route "/" >=> htmlFile "/pages/index.html" ]

type Startup() =
member __.Configure (app : IApplicationBuilder)
(env : IHostingEnvironment)
(loggerFactory : ILoggerFactory) =

app.UseGiraffe webApp

Is terse an insult? Absolutely not, it's a feature! Check out this single line exampe...and the fish >=> operator! Some people don't like it but I think it's clever.

let app = route "/" >=> setStatusCode 200 >=> text "Hello World"

Making more complex:

let app =

choose [
GET >=> route "/foo" >=> text "GET Foo"
POST >=> route "/foo" >=> text "POST Foo"
route "/bar" >=> text "Always Bar"
]

Or requiring certain headers:

let app =

mustAccept [ "text/plain"; "application/json" ] >=>
choose [
route "/foo" >=> text "Foo"
route "/bar" >=> json "Bar"
]

And you can continue to use Razor views as you like, passing in models written in F#

open Giraffe.Razor.HttpHandlers


let model = { WelcomeText = "Hello World" }

let app =
choose [
// Assuming there is a view called "Index.cshtml"
route "/" >=> razorHtmlView "Index" model
]

There are samples at https://github.com/dustinmoris/Giraffe/tree/master/samples you can check out as well

* Giraffe photo by Kurt Thomas Hunt, used under CC


Sponsor: A third of teams don’t version control their database. Connect your database to your version control system with SQL Source Control and find out who made changes, what they did, and why. Learn more!



© 2017 Scott Hanselman. All rights reserved.
     

What would a cross-platform .NET UI Framework look like? Exploring Avalonia

$
0
0

Many years ago before WPF was the "Windows Presentation Foundation" and introduced XAML as a UI markup language for .NET, Windows, and more, there was a project codenamed "Avalon." Avalon was WPF's codename. XAML is everywhere now, and the XAML Standard is a vocabulary specification.

Avalonia is an open source project that clearly takes its inspiration from Avalon and has an unapologetic love for XAML. Steven Kirk (GitHubber by day) and a team of nearly 50 contributors are asking what would a cross-platform .NET UI Framework look like. WPF without the W, if you will.

Avalonia (formerly known as Perspex) is a multi-platform .NET UI framework. It can run on Windows, Linux, Mac OS X, iOS and Android.

YOU can try out the latest build of Avalonia available for download here:https://ci.appveyor.com/project/AvaloniaUI/Avalonia/branch/master/artifacts and probably get the "ControlCatalog.Desktop" zip file at the bottom. It includes a complete running sample app that will let you explore the available controls.

Avalonia is cross-platform XAML ZOMG

It's important note that while Avalonia may smell like WPF, it's not WPF. It's not cross-platform WPF - it's Avalonia. Make sense? Avalonia does styles differently than WPF, and actually has a lot of subtle but significant syntax improvements.

Avalonia is a multi-platform windowing toolkit - somewhat like WPF - that is intended to be multi- platform. It supports XAML, lookless controls and a flexible styling system, and runs on Windows using Direct2D and other operating systems using Gtk & Cairo.

It's in an alpha state but there's an active community excited about it and there's even a Visual Studio Extension (VSIX) to help you get File | New Project support and create an app fast. You can check out the source for the sample apps here https://github.com/AvaloniaUI/Avalonia/tree/master/samples.

Just in the last few weeks you can see commits as they explore what a Linux-based .NET Core UI app would look like.

You can get an idea of what can be done with a framework like this by taking a look at how someone forked the MSBuildStructuredLog utility and ported it to Avalonia - making it cross-platform - in just hours. You can see a video of the port in action on Twitter. There is also a cross-platform REST client you can use to call your HTTP Web APIs at https://github.com/x2bool/restofus written with Avalonia.

The project is active but also short on documentation. I'm SURE that they'd love to hear from you on Twitter or in the issues on GitHub. Perhaps you could start contributing to open source and help Avalonia out!

What do you think?


Sponsor: Get the latest JetBrains Rider preview for .NET Core 2.0 support, Value Tracking and Call Tracking, MSTest runner, new code inspections and refactorings, and the Parallel Stacks view in debugger.



© 2017 Scott Hanselman. All rights reserved.
     

Spend less time CD'ing around directories with the PowerShell Z shortcut

$
0
0

Everyone has a trick for moving around their computer faster. It might be a favorite shell, a series of aliases or shortcuts. I like using popd and pushd to quickly go deep into a directory structure and return exactly where I was.

Another fantastic utility is simply called "Z." There is a shell script for Z at https://github.com/rupa/z that's for *nix, and there's a PowerShell Z command (a fork of the original) at https://github.com/vincpa/z.

As you move around your machine at the command line, Z is adding the directories you usually visit to a file, then using that file to give you instant autocomplete so you can get back there FAST.

If you have Windows 10, you can install Z in seconds like this:

C:\> Install-Module z -AllowClobber

Then just add "Import-Module z" to the end of your Profile, usually at $env:USERPROFILE\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

Even better, Z works with pushd, cd, or just "z c:\users\scott" if you like. All those directory changes and moves will be recorded it the Z datafile that is stored in ~\.cdHistory.

What do you think? Do you have a favorite way to move around your file system at the command line?


Sponsor: Get the latest JetBrains Rider preview for .NET Core 2.0 support, Value Tracking and Call Tracking, MSTest runner, new code inspections and refactorings, and the Parallel Stacks view in debugger.


© 2017 Scott Hanselman. All rights reserved.
     

The Book of the Runtime - The internals of the .NET Runtime that you won't find in the documentation

$
0
0

The Microsoft Docs at https://docs.microsoft.com are really fantastic lately. All the .NET Docs are on GitHub https://github.com/dotnet/docs/ and you can contribute to them. However, in the world of software engineering (here some a bad, mixed metaphor) there's instructions on how to use a faucet and there's instructions on how to build and design plumbing from scratch.

RyuJIT High level overview

There's additional DEEP docs that don't really belong on the docs site. It's the Book of the Runtime and for now it's on GitHub. Here's the BotR FAQ.

If you're interested in the internals of a system like the .NET Runtime, these docs are a gold mine for you.

The Book of the Runtime is a set of documents that describe components in the CLR and BCL. They are intended to focus more on architecture and invariants and not an annotated description of the codebase.

It was originally created within Microsoft in ~ 2007, including this document. Developers were responsible to document their feature areas. This helped new devs joining the team and also helped share the product architecture across the team.

We realized that the BotR is even more valuable now, with CoreCLR being open source on GitHub. We are publishing BotR chapters to help a new set of CLR developers.

This book likely isn't for you if you're an app developer. Who is it for?

  • Developers who are working on bugs that impinge on an area and need a high level overview of the component.
  • Developers working on new features with dependencies on a component need to know enough about it to ensure the new feature will interact correctly with existing components.
  • New developers need this chapter to maintain a given component.

These aren't design documents, these are docs that were written after features are implemented in order to explain how they work in practice.

Recently Carol Eidt wrote an amazing walkthrough to .NET Core's JIT engine. Perhaps start at the JIT Overview and move to the deeper walkthrough. Both are HUGELY detailed and a fascinating read if you're interested in how .NET makes Dynamic Code Execution near-native speed with the RyuJIT - the next-gen Just in Time compiler.

Here's a few highlights I enjoyed but you should read the whole thing yourself. It covers the high level phases and then digs deeper into the responsibilities of each. You also get a sense of why the RyuJIT is NOT the same JITter from 15+ years ago - both the problem space and processors have changed.

This is the 10,000 foot view of RyuJIT. It takes in MSIL (aka CIL) in the form of byte codes, and the Importer phase transforms these to the intermediate representation used in the JIT. The IR operations are called “GenTrees”, as in “trees for code generation”. This format is preserved across the bulk of the JIT, with some changes in form and invariants along the way. Eventually, the code generator produces a low-level intermediate called InstrDescs, which simply capture the instruction encodings while the final mappings are done to produce the actual native code and associated tables.

ryujit-phase-diagram

This is just one single comprehensive doc in a collection of documents. As for the rest of the Book of the Runtime, here's the ToC as of today, but there may be new docs in the repository as it's a living book.

Check it out!


Sponsor: Check out JetBrains Rider: a new cross-platform .NET IDE. Edit, refactor, test and debug ASP.NET, .NET Framework, .NET Core, Xamarin or Unity applications. Learn more and download a 30-day trial!



© 2017 Scott Hanselman. All rights reserved.
     

Tabs vs Spaces - A peaceful resolution with EditorConfig in Visual Studio. Plus .NET Extensions!

$
0
0

The culture wars continue. The country is divided with no end in sight. Tabs or spaces? There's even an insane (IMHO) assertion that the spaces people make more money.

I'm going with Gina Trapani on this one. I choose working code.

Teams can fight but the problem of formatting code across teams is solved by EditorConfig. I'm surprised more people don't know about it and use it, so this blog post is my small way of getting the word out. TELL THE PEOPLE.

Take a project and make a new .editorconfig file and put this in it. I'll use a dotnet new console example hello world app.

[*.cs]

indent_style = tab
indent_size = tab
tab_size = 4

I've set mine in this example to just *.cs, but you could also say [*.{cs,js}] or just [*] if you like, as well as have multiple sections.

You'll check this file in WITH your project so that everyone on the team shares the team's values.

Here in Notepad2 we can see someone has used spaces for whitespace, like a savage. Whitespace appears as pale dots in this editor.

image

I'll open this project in Visual Studio 2017 which supports the EditorConfig file natively. Notice the warning at the bottom where VS lets me know that this project has conventions that are different than my own.

user preferences for this file type are overwidden by this project's coding conventions

VS Format Document commands will use tabs rather than spaces for this project. Here is the same doc reformatted in VS:

image

At this point I'm comforted that the spaces have been defeated and that cooler heads have prevailed - at least for this project.

.NET Extensions to EditorConfig

Even better, if your editor supports it, you can include "EditorConfig Extensions" for specific files or languages. This way your team can keep things consistent across projects. If you're familiar with FxCop and StyleCop, this is like those.

There's a ton of great .NET EditorConfig options you can set to ensure the team uses consistent Language Conventions, Naming Conventions, and Formatting Rules.

  • Language Conventions are rules pertaining to the C# or Visual Basic language, for example, var/explicit type, use expression-bodied member.
  • Formatting Rules are rules regarding the layout and structure of your code in order to make it easier to read, for example, Allman braces, spaces in control blocks.
  • Naming Conventions are rules respecting the way objects are named, for example, async methods must end in "Async".

You can also set the importance of these rules with things like "suggestion," or "warning," or even "error."

As an example, I'll set that my team wants predefined types for locals:

dotnet_style_predefined_type_for_locals_parameters_members = true:error

Visual Studio here puts up a lightbulb and the suggested fix because my team would rather I use "string" than the full "System.String.

Visual Studio respects EditorConfig

The excellent editorconfig for .NET docs have a LOT of great options you can use or ignore. Here's just a FEW (controversial) examples:

  • csharp_new_line_before_open_brace - Do we put open braces at the end of a line, or on their own new line?
  • csharp_new_line_before_members_in_object_initializers - Do we allow A = 3, B = 4, for insist on a new line for each?
  • csharp_indent_case_contents - Do we freakishly line up all our switch/case statements, or do we indent each case like the creator intended?
  • You can even decide on how you Want To Case Things And Oddly Do Sentence Case: pascal_case, camel_case, first_word_upper, all_upper, all_lower

If you're using Visual Studios 2010, 2012, 2013, or 2015, fear not. There's at least a basic EditorConfig free extension for you that enforces the basic rules. There is also an extension for Visual Studio Code to support EditorConfig files that takes just seconds to install although I don't see a C# one for now, just one for whitespace.


Sponsor: Check out JetBrains Rider: a new cross-platform .NET IDE. Edit, refactor, test and debug ASP.NET, .NET Framework, .NET Core, Xamarin or Unity applications. Learn more and download a 30-day trial!



© 2017 Scott Hanselman. All rights reserved.
     

Free .NET Training - The Videos from .NET Conf 2017 are now available

$
0
0

.NET Conf was worldwide this year.NET Conf 2017 is done and it was great. We had three days of sessions, and two of the days had two tracks, so there's more than 40 hours of great free videos and training for you to check out and share. Some of the content was from Microsoft but a bunch of the videos were from community and open source project members who Skyped into the studio! While I was in Redmond, Washington, Miguel de Icaza and Scott Hunter did a keynote from Devintersection in Stockholm.

There were also a number of local dotNetConf events! I hope you consider hosting one in your locale next year! While the virtual conference was filmed and broadcast LIVE, all the session videos are posted now at https://channel9.msdn.com/Events/dotnetConf/2017. There's 46 videos but here's a few of my favorites.

Containerized ASP.NET Core Apps with Kubernetes

Mete Atemal from Google joined us to talk about Containerized ASP.NET Core Apps with Kubernetes

image

Build Your Own Cortana Skill

Dorene Brown showed us how to wrote a Cortana skill in C# and .NET.

image

What's New in Visual Studio 2017

Kasey does a deep drive into a TON of the more advanced VS2017 features.

image

Diagnostics 101

The Legend himself, Jon Skeet, does a fantastic code-heavy talk on how to diagnose your app when things go wrong.

image

Go Serverless with Azure Functions and C#

Cecil Phillip breaks down the "serverless" buzzword and shows you how to use Azure Functions.

image

Get started with F# and .NET Core

Phillip Carter is geeked about F# and you should be too!

image

Full Stack F# with Fable

Once you've gotten started with F#, take a look at Fable and start writing Full Stack F# with F# on both the server and client!

image

Turning software into computer chips with Hastlayer

Zoltan explains to me how to use Hastlayer to transform .NET software into electronic circuits on FPGAs!

    image

    Getting Started with .NET

    And finally, last but not least, Kathleen Dollard and I did two hours (part 1 and part 2) on:

    image

    This is just a taste, there's a LOT of great videos so go explore!


    Sponsor: Do you know how many errors, crashes and performance issues your users are experiencing? Raygun installs in minutes. Discover problems you didn't even know about and replicate bugs with greater speed and accuracy. Learn more!



    © 2017 Scott Hanselman. All rights reserved.
         

    Learning about the F# SAFE stack - Suave.io, Azure, Fable, Elmish

    $
    0
    0

    Last month I looked at a Functional Web with ASP.NET Core and F#'s Giraffe. Giraffe is F# middleware that takes ASP.NET Core's pipeline in a new direction with a functional perspective. However, Giraffe isn't the only F# web stack to choose from! There's Freya, WebSharper, and there's also a very interesting and quite complete story with The SAFE Stack.

    The SAFE Stack

    The SAFE Stack is an open source stack, like LAMP, or WAMP, or other acronym stacks, except this one is all open source .NET with a functional perspective. From the announcement blog:

    • Suave model for server-side web programming
    • Azure for cloud-based systems
    • Fable for Javascript-enabled applications.
    • Elmish for an easy-to-understand UI programming mode

    To be clear, while this is a prescriptive stack, it's not a stack that forces you to do anything. You can swap bits out as you please.

    Fable is particularly interesting as it's an F# to JavaScript transpiler. Try Fable online here http://fable.io/repl and turn F# into JavaScript LIVE! Their Sudoku sample is particularly impressive.

    Here's two small - but interesting - examples where F# code ends up as JavaScript which ends up creating ReactJS components:

    let words size message =
        R.span [ Style [ !!("fontSize", size |> sprintf "%dpx") ] ] [ R.str message ]
    let buttonLink cssClass onClick elements = 
        R.a [ ClassName cssClass
              OnClick (fun _ -> onClick())
              OnTouchStart (fun _ -> onClick())
              Style [ !!("cursor", "pointer") ] ] elements

    Then later in a Menu.fs that also turns into JavaScript eventually, you can see where they conditionally render the Button for logout, or links for for other Views for the Home Page or Wishlist. You can read lots more about Fable over at the Compositional IT blog.

    let view (model:Model) dispatch =
        div [ centerStyle "row" ] [ 
              yield viewLink Home "Home"
              if model.User <> None then 
                  yield viewLink Page.WishList "Wishlist"
              if model.User = None then 
                  yield viewLink Login "Login" 
              else 
                  yield buttonLink "logout" (fun _ -> dispatch Logout) [ str "Logout" ]
            ]

    Elmish for F# takes the Model View Update (MVU) architecture and brings it to F# and the browser. There's a good breakdown of the value Elmish provides also at the Compositional IT blog.

    Suave is its own cross platform Web Server. Here's Hello World in Suave.

    open Suave
    

    startWebServer defaultConfig (Successful.OK "Hello World!")

    Suave has been around for while and gets better all the time. I blogged about it in 2015 and got it running on Azure. My blog post is not a best practice any more - it was a spike attempt by me - and fortunately they've moved on and improved things.

    Here's Suave getting set up within the sample app. Check out how they route HTTP Verbs and URL paths.

        let serverConfig =
            { defaultConfig with
                logger = Targets.create LogLevel.Debug [|"ServerCode"; "Server" |]
                homeFolder = Some clientPath
                bindings = [ HttpBinding.create HTTP (IPAddress.Parse "0.0.0.0") port] }
        let app =
            choose [
                GET >=> choose [
                    path "/" >=> Files.browseFileHome "index.html"
                    pathRegex @"/(public|js|css|Images)/(.*)\.(css|png|gif|jpg|js|map)" >=> Files.browseHome
                    path "/api/wishlist/" >=> WishList.getWishList loadFromDb ]
                POST >=> choose [
                    path "/api/users/login" >=> Auth.login
                    path "/api/wishlist/" >=> WishList.postWishList saveToDb
                ]
                NOT_FOUND "Page not found."
            ] >=> logWithLevelStructured Logging.Info logger logFormatStructured
        startWebServer serverConfig app

    Very interesting stuff! There are so many options in .NET open source. I'll be doing podcasts on this stack soon.

    Trying out the SAFE Stack

    If you're using Visual Studio Community 2017, make sure you've got F# support included. I double-checked under Individual components. You can run the VS2017 installer multiple time and add and remove stuff without breaking things, so don't worry. If you are using other versions of VS, check here http://fsharp.org/use/windows/ to get the right download for your machine. If you're using Visual Studio Code, you'll want the Ionide F# plugin for Code.

    Adding F# to Visual Studio Community 2017

    Once I had node and yarn installed, it was easy to try out the sample app and get it running locally with "build run." It uses DotNetWatcher, so you can just keep it running in the background and work on your code and it'll recompile and restart as you go.

    The SAFE stack running

    The complete "SAFE" stack demo website is LIVE here http://fable-suave.azurewebsites.net (login test/test/) and all the source code for the app is here: https://github.com/SAFE-Stack/SAFE-BookStore.


    Sponsor: Do you know how many errors, crashes and performance issues your users are experiencing? Raygun installs in minutes. Discover problems you didn't even know about and replicate bugs with greater speed and accuracy. Learn more!



    © 2017 Scott Hanselman. All rights reserved.
         

    Botwin offers an interesting alternative option for routing with ASP.NET Core

    $
    0
    0

    NancyFx is a great alternative to ASP.NET if you want to make elegant little web apis like this:

    public class SampleModule : Nancy.NancyModule
    
    {
    public SampleModule()
    {
    Get["/"] = _ => "Hello World!";
    }
    }

    However, it may be that you want a routing style - the way you define your routes - that is like NancyFx BUT you want to use ASP.NET. Botwin is a library that lets you do just that. They say:

    This is not a framework, it simply builds on top of Microsoft.AspNetCore.Routing allowing you to have more elegant routing rather than have attribute routing, convention routing, ASP.Net Controllers or IRouteBuilder extensions.

    You can plug Botwin into your existing ASP.NET Core application, or you can even add a basic started Botwin app to "dotnet new" like this:

    C:\botwinexample> dotnet new -i BotwinTemplate
    
    C:\botwinexample> dotnet new botwin -n MyBotwinApp
    C:\botwinexample> dir
    10/11/2017 10:14 PM 284 HomeModule.cs
    10/11/2017 10:14 PM 470 MyBotwinApp.csproj
    10/11/2017 10:14 PM 421 Program.cs
    10/11/2017 10:14 PM 408 Startup.cs
    4 File(s) 1,583 bytes

    You add Botwin as a service to your ASP.NET Core app:

    public class Startup
    
    { public void ConfigureServices(IServiceCollection services) { services.AddBotwin(); } public void Configure(IApplicationBuilder app) { app.UseBotwin(); }
    }

    And then add 'Modules' like this:

    namespace MyBotwinApp
    {
        using Botwin;
        using Microsoft.AspNetCore.Http;
        public class HomeModule : BotwinModule
        {
            public HomeModule()
            {
                Get("/", async(req, res, routeData) => await res.WriteAsync("Hello from Botwin!"));
            }
        }
    }
    

    That's a hello world. Let's try something more interesting. You can have Before and After hooks like this:

    public class HooksModule : BotwinModule
    
    {
    public HooksModule()
    {
    this.Before = async (ctx) =>
    {
    ctx.Response.StatusCode = 402;
    await ctx.Response.WriteAsync("Pay up you filthy animal");
    return false;
    };

    this.Get("/hooks", async (req, res, routeData) => await res.WriteAsync("Can't catch me here"));

    this.After = async (ctx) => await ctx.Response.WriteAsync("Don't forget you owe me big bucks!");
    }
    }

    Here's a more complex example. See how they do a BindAndValidate in the Post() where they check for a valid Actor before working with it.

    public class ActorsModule : BotwinModule
    
    {
    public ActorsModule(IActorProvider actorProvider)
    {
    this.Get("/actors", async (req, res, routeData) =>
    {
    var people = actorProvider.Get();
    await res.AsJson(people);
    });

    this.Get("/actors/{id:int}", async (req, res, routeData) =>
    {
    var person = actorProvider.Get(routeData.As<int>("id"));
    await res.Negotiate(person);
    });

    this.Put("/actors/{id:int}", async (req, res, routeData) =>
    {
    var result = req.BindAndValidate<Actor>();

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

    //Update the user in your database

    res.StatusCode = 204;
    });

    this.Post("/actors", async (req, res, routeData) =>
    {
    var result = req.BindAndValidate<Actor>();

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

    //Save the user in your database
    res.StatusCode = 201;
    await res.Negotiate(result.Data);
    });
    }

    What do you think about the choices you have with ASP.NET Core? Some people feel like the amount of plugability is overwhelming, but I find the flexibility heartening. Go check out Botwin and, hopefully, help out and contribute to open source!


    Sponsor: Get the latest JetBrains Rider preview for .NET Core 2.0 support, Value Tracking and Call Tracking, MSTest runner, new code inspections and refactorings, and the Parallel Stacks view in debugger.



    © 2017 Scott Hanselman. All rights reserved.
         
    Viewing all 1148 articles
    Browse latest View live


    <script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>