Subscribe: Scott Hanselman's Computer Zen
Added By: Feedage Forager Feedage Grade A rated
Language: English
app  core  csv  dotnet new  dotnet  framework  giraffe  library  mvc  net core  net standard  net  new  project  var 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Scott Hanselman's Computer Zen

Scott Hanselman's Blog

Scott Hanselman on Programming, User Experience, The Zen of Computers and Life in General


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

Mon, 18 Sep 2017 06:25:45 GMT

I 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 Even better, it uses the "dotnet new" templating system so you can check it out and get started in seconds.c:> md \mygiraffeeapp & cd \mygiraffeeappc:\mygiraffeeapp> dotnet new -i "giraffe-template::*"c:\mygiraffeeapp> dotnet new giraffeThe template "Giraffe Web App" was created successfully.c:\mygiraffeeapp> dotnet runHosting environment: ProductionContent root path: C:\mygiraffeappNow listening on: http://localhost:5000Application 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 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.HttpHandlersopen Giraffe.Middlewarelet 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.HttpHandlerslet model = { WelcomeText = "Hello World" }let app = choose [ // Assuming there is a view called "Index.cshtml" route "/" >=> razorHtmlView "Index" model ] There are samples at 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, a[...]

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

Thu, 14 Sep 2017 21:58:29 GMT

The 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 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 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\> dotnet new -i C:\BlogTemplate -o C:\myblogC:\> cd \myblog\BlogTemplateC:\myblog\BlogTemplate> dotnet runC:\myblog\BlogTemplate (master) > dotnet runUsing launch settings from C:\myblog\BlogTemplate\Properties\launchSettings.json...Hosting environment: DevelopmentContent root path: C:\myblog\BlogTemplateNow listening on: http://localhost:59938Application started. Press Ctrl+C to shut down. And here's my nice local new blog. It's got admin, login, comments, the basics. 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 prev[...]

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

Sun, 10 Sep 2017 06:44:59 GMT

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, ""); 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, ""); 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, ""); 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, 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.       [...]

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

Thu, 07 Sep 2017 19:05:30 GMT

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'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:Dinner Details you can writeDinner Details It's generating the URL for that 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." I'll run "Generate-R4MVC" in the Package Manager Console. 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. When returning a view, rather than return View("About") I can do return View(Views.About): The R4MVC project also has Tag Helpers so their mvc-action attribute gives you strong typing like this: This R4MVC project is just getting started, but I'm sure they'd appreciate your support! Head over to 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.       [...]

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

Sat, 02 Sep 2017 02:20:00 GMT

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. class="giphy-embed" style="position: absolute" height="100%" src="" frameborder="0" width="100%" allowfullscreen> via GIPHY Then I was offended class="giphy-embed" style="position: absolute" height="100%" src="" frameborder="0" width="100%" allowfullscreen> via GIPHY But finally I was hey...that's a good idea. class="giphy-embed" style="position: absolute" height="100%" src="" frameborder="0" width="100%" allowfullscreen> 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(); 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{ public PersonMap() { Map( m => m.Id ); Map( m => m.Name ); References( m => m.Address ); }}public sealed class AddressMap : CsvClassMap
{ 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.       [...]

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

Tue, 29 Aug 2017 19:55:27 GMT

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. 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=falseMicrosoft (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 linkedMicrosoft (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: 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.Exte[...]

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

Mon, 21 Aug 2017 23:46:49 GMT

I 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 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 loadCould not load file or assembly 'Microsoft.EntityFrameworkCore, Version=, 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 like this to change the restore style: PackageReference 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. Hope this helps.© 2017 Scott Hanselman. All rights reserved.       [...]

Draft - .NET Glossary Diagram

Thu, 17 Aug 2017 20:52:48 GMT

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.


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.