Scott Hanselman

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

September 15, 2017 Comment on this post [8] Posted in DotNetCore | Open Source
Sponsored By

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!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

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

September 10, 2017 Comment on this post [8] Posted in DotNetCore | Open Source
Sponsored By

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!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

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

September 07, 2017 Comment on this post [10] Posted in ASP.NET MVC | Open Source
Sponsored By

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

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

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

T4MVC lets you write

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

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

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

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

you can write

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

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

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

Adding R4Mvc.Tools in NuGet

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

Generate-R4MVC

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

Links.css

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

return View(Views.About)

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

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

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

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


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

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

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

September 02, 2017 Comment on this post [35] Posted in Open Source
Sponsored By

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

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

First I was shocked. SHOCKED I SAY.

via GIPHY

Then I was offended

via GIPHY

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

via GIPHY

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

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

Here's what CsvHelper can do for you:

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

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

public sealed class PersonMap : CsvClassMap<Person>
{
public PersonMap()
{
Map( m => m.Id );
Map( m => m.Name );
References<AddressMap>( m => m.Address );
}
}

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

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

var csv = new CsvWriter( textWriter );
csv.WriteRecords( records );

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

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

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


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

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

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

August 29, 2017 Comment on this post [13] Posted in DotNetCore
Sponsored By

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!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.