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

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…

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.
     

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

.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 bun…

.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.
         

    The Book of the Runtime – The internals of the .NET Runtime that you won’t find in the documentation

    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.
         

    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.
         

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

    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.
         

    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.
         

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

    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.
         

    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.
         

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

    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.
         

    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.
         

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

    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.
         

    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.
         

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

    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.
         

    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.
         

    Draft – .NET Glossary Diagram

    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.
         

    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.
         

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

    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.
         

    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.