Giter Site home page Giter Site logo

nbarbettini / little-aspnetcore-book Goto Github PK

View Code? Open in Web Editor NEW
700.0 66.0 191.0 1.88 MB

The Little ASP.NET Core Book, a friendly introduction to web programming and ASP.NET Core 2.0

Home Page: http://littleasp.net/book

License: Creative Commons Attribution 4.0 International

asp-net-core csharp web-application book

little-aspnetcore-book's Introduction

The Little ASP.NET Core Book

by Nate Barbettini

Copyright © 2018. All rights reserved.

ISBN: 978-1-387-75615-5

Released under the Creative Commons Attribution 4.0 license. You are free to share, copy, and redistribute this book in any format, or remix and transform it for any purpose (even commercially). You must give appropriate credit and provide a link to the license.

For more information, visit https://creativecommons.org/licenses/by/4.0/

Introduction

Thanks for picking up The Little ASP.NET Core Book! I wrote this short book to help developers and people interested in web programming learn about ASP.NET Core 2.0, a framework for building web applications and APIs.

The Little ASP.NET Core Book is structured as a tutorial. You'll build an application from start to finish and learn:

  • The basics of the MVC (Model-View-Controller) pattern
  • How front-end code (HTML, CSS, JavaScript) works together with back-end code
  • What dependency injection is and why it's useful
  • How to read and write data to a database
  • How to add log-in, registration, and security
  • How to deploy the application to the web

Don't worry, you don't need to know anything about ASP.NET Core (or any of the above) to get started.

Before you begin

The code for the finished version of the application you'll build is available on GitHub:

https://www.github.com/nbarbettini/little-aspnetcore-todo

Feel free to download it if you want to see the finished product, or compare as you write your own code.

The book itself is updated frequently with bug fixes and new content. If you're reading a PDF, e-book, or print version, check the official website (littleasp.net/book) to see if there's an updated version available. The very last page of the book contains version information and a changelog.

Reading in your own language

Thanks to some fantastic multilingual contributors, the Little ASP.NET Core Book has been translated into other languages:

Who this book is for

If you're new to programming, this book will introduce you to the patterns and concepts used to build modern web applications. You'll learn how to build a web app (and how the big pieces fit together) by building something from scratch! While this little book won't be able to cover absolutely everything you need to know about programming, it'll give you a starting point so you can learn more advanced topics.

If you already code in a backend language like Node, Python, Ruby, Go, or Java, you'll notice a lot of familiar ideas like MVC, view templates, and dependency injection. The code will be in C#, but it won't look too different from what you already know.

If you're an ASP.NET MVC developer, you'll feel right at home! ASP.NET Core adds some new tools and reuses (and simplifies) the things you already know. I'll point out some of the differences below.

No matter what your previous experience with web programming, this book will teach you everything you need to create a simple and useful web application in ASP.NET Core. You'll learn how to build functionality using backend and frontend code, how to interact with a database, and how to deploy the app to the world.

What is ASP.NET Core?

ASP.NET Core is a web framework created by Microsoft for building web applications, APIs, and microservices. It uses common patterns like MVC (Model-View-Controller), dependency injection, and a request pipeline comprised of middleware. It's open-source under the Apache 2.0 license, which means the source code is freely available, and the community is encouraged to contribute bug fixes and new features.

ASP.NET Core runs on top of Microsoft's .NET runtime, similar to the Java Virtual Machine (JVM) or the Ruby interpreter. You can write ASP.NET Core applications in a number of languages (C#, Visual Basic, F#). C# is the most popular choice, and it's what I'll use in this book. You can build and run ASP.NET Core applications on Windows, Mac, and Linux.

Why do we need another web framework?

There are a lot of great web frameworks to choose from already: Node/Express, Spring, Ruby on Rails, Django, Laravel, and many more. What advantages does ASP.NET Core have?

  • Speed. ASP.NET Core is fast. Because .NET code is compiled, it executes much faster than code in interpreted languages like JavaScript or Ruby. ASP.NET Core is also optimized for multithreading and asynchronous tasks. It's common to see a 5-10x speed improvement over code written in Node.js.

  • Ecosystem. ASP.NET Core may be new, but .NET has been around for a long time. There are thousands of packages available on NuGet (the .NET package manager; think npm, Ruby gems, or Maven). There are already packages available for JSON deserialization, database connectors, PDF generation, or almost anything else you can think of.

  • Security. The team at Microsoft takes security seriously, and ASP.NET Core is built to be secure from the ground up. It handles things like sanitizing input data and preventing cross-site request forgery (CSRF) attacks, so you don't have to. You also get the benefit of static typing with the .NET compiler, which is like having a very paranoid linter turned on at all times. This makes it harder to do something you didn't intend with a variable or chunk of data.

.NET Core and .NET Standard

Throughout this book, you'll be learning about ASP.NET Core (the web framework). I'll occasionally mention the .NET runtime, the supporting library that runs .NET code. If this already sounds like Greek to you, just skip to the next chapter!

You may also hear about .NET Core and .NET Standard. The naming gets confusing, so here's a simple explanation:

.NET Standard is a platform-agnostic interface that defines features and APIs. It's important to note that .NET Standard doesn't represent any actual code or functionality, just the API definition. There are different "versions" or levels of .NET Standard that reflect how many APIs are available (or how wide the API surface area is). For example, .NET Standard 2.0 has more APIs available than .NET Standard 1.5, which has more APIs than .NET Standard 1.0.

.NET Core is the .NET runtime that can be installed on Windows, Mac, or Linux. It implements the APIs defined in the .NET Standard interface with the appropriate platform-specific code on each operating system. This is what you'll install on your own machine to build and run ASP.NET Core applications.

And just for good measure, .NET Framework is a different implementation of .NET Standard that is Windows-only. This was the only .NET runtime until .NET Core came along and brought .NET to Mac and Linux. ASP.NET Core can also run on Windows-only .NET Framework, but I won't touch on this too much.

If you're confused by all this naming, no worries! We'll get to some real code in a bit.

A note to ASP.NET 4 developers

If you haven't used a previous version of ASP.NET, skip ahead to the next chapter.

ASP.NET Core is a complete ground-up rewrite of ASP.NET, with a focus on modernizing the framework and finally decoupling it from System.Web, IIS, and Windows. If you remember all the OWIN/Katana stuff from ASP.NET 4, you're already halfway there: the Katana project became ASP.NET 5 which was ultimately renamed to ASP.NET Core.

Because of the Katana legacy, the Startup class is front and center, and there's no more Application_Start or Global.asax. The entire pipeline is driven by middleware, and there's no longer a split between MVC and Web API: controllers can simply return views, status codes, or data. Dependency injection comes baked in, so you don't need to install and configure a container like StructureMap or Ninject if you don't want to. And the entire framework has been optimized for speed and runtime efficiency.

Alright, enough introduction. Let's dive in to ASP.NET Core!

little-aspnetcore-book's People

Contributors

nbarbettini avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

little-aspnetcore-book's Issues

More detailed social login instructions

  • Add social login instructions back in (Google)
  • Only after setting up HTTPS
  • Research a more elegant way to handle secrets (for deployment and testing)
  • Add test users or change settings to allow any Facebook user to log in
  • After deployment, go back into Facebook settings and update to published URI

Port may be different in redirect URI

When adding Facebook authentication, the Valid OAuth redirect URIs is not always localhost:5000. If you're using IIS Express it may be a different port. This can be confusing so it should be noted.

Why don't we use secret.json when creating an admin account?

Putting the following data

"Administrator" : {
     "UserName" : "[email protected]",
     "Email" : "[email protected]",
     "Password" : "NotSecure123!!"
}

in secret.json and loading them via IConfiguration con should be safer as well as it promotes a better practice.

private static async Task EnsureTestAdminAsync(UserManager<ApplicationUser> userManager, IConfiguration con)
{
    // ........

    testAdmin = new ApplicationUser { UserName = con["Administrator:UserName"], Email = con["Administrator:Email"] };
    await userManager.CreateAsync(testAdmin, con["Administrator:Password"]);
    await userManager.AddToRoleAsync(testAdmin, Constants.AdministratorRole);
}

Note: secret.json will not be uploaded to github repository.

Discuss [Key] attribute

Suggestion:

When you mention the Id property, it may be useful to mention the [Key] attribute as well.

Page 93: for technical reasons you cannot use await in Program.cs

or on the top of page 90 of the old version of the book.
Is it an idea to have a short explanation there? Or a reference? About why you can't await in program.cs I am just curious and this "for technical reasons" is a trigger for me to google it. But can't find a good/clear explanation.

Translation into Russian?

I was wondering if anyone has already picked up work to translate the book into Russian. I would gladly do that, just to make the good content available for a wider audience.

How are different translations managed? Is it just an isolated fork? Any centralized management in this repo?

Console.log in site.js doesn't work

I can't seen to be able to test that the javascript is working at all. I can't log anything, there's not evidence that the jquery is working when I click the add button. I'm at the add new to-do items stage.

Javascript approach to add TodoItem is overkill

If we want to keep the book as simple as possible and keeping the quality high enough for the beginners, I think the Javascript approach to add TodoItem as explained in
this page should be removed.

Using a form with method=post should be enough.

Mention change in Razor syntax

From Duke Wang:

One small suggestion, since .NET Core razor tags have had a jumping change, from @html.()... to HTML 5 standard 'asp-*', etc., I think it is worth to mention it for ASP.NET 4 developers.

Taking a project that allows registered users to do CRUD on authorized parts of their own and others

Most of us probably know stackoverlow.com and its variants. A user allows to submit questions, answers and comments to their own and others.

The current project developed in this book does not teach us how to allow registered users to do such CRUD mentioned above. Taking a stackoverflow.com-like project as a tutorial seems to be more interesting as it covers the missing important parts about integrating Question, Answer, Comment entity model with the identity model.

Reuse TodoItem class

Is the NewTodoItem POCO an unnecessary duplication of TodoItem?

My initial thought was keeping everything super clean and separate, but that might be a little too much.

Spanish Translation

Hi! First of all thanks so much for your work, the book is just amazing and really helpful!

I would like to help with the Spanish translation if it's ok to you and no one is currently working on it.

Best Regards,
Pedro.

Facebook login

Hi, it's probably because stuff changed on the side of FB, but the screenshot on page 72 is not accurate anymore, and when clicking on the login button I get this (dutch, sorry) message:

fb-login

roughly translated it says: cannot load url, the domain of this url is not added to the domains of this app. add all domains and subdomains of the app in the field appdomains of the settings of your app to be able to load this url.

my app runs on port 5001 instead of the default 5000. Don't know why, but it's how it is. So I configured it like this:

fb-settings

it's probably just a wrong field because of the FB Dev page change. So it could use new screenshots in the book :)

Coordinating translation updates

I'm really excited that folks are interested in translating this book to more languages. Since I plan to update the book occasionally (with both small and large changes), I think we should discuss how to keep the translated versions in sync with the original.

Here's my suggestion for translation forks:

  • Maintain a master branch on your profile that doesn't contain any changes, but just serves as a diff against nbarbettini:master.
  • Keep the translation in another fork, like zh-cn or de-DE.
  • When the original book is updated, nbarbettini:master will move ahead of your master. This will make it really obvious what needs to be updated in the translation. When the translation fork has been updated, translator:master can be fast-forwarded to catch up with nbarbettini:master.

@windsting took this approach in his Chinese translation: https://github.com/windsting/little-aspnetcore-book

Open to any better suggestions!

cc:
@xleon
@duke1102
@sahinyanlik
@windsting
@atsvetkov
(Apologies if I missed anyone!)

Rewrite More Features structure

Currently the Add more features chapter tells you to use jQuery to make AJAX calls to some pseudo-API controllers. It would be better to stay fully inside the MVC fold and then contrast with a SPA architecture, instead of mixing metaphors.

Tl;dr - more MVC, less jQuery.

Why don't we use the simplest type for method parameters in ITodoItemService?

The current definition of ITodoItemService is as follows.

public interface ITodoItemService
{
    Task<IEnumerable<TodoItem>> GetIncompleteItemsAsync(ApplicationUser user);
    Task<bool> AddItemAsync(NewTodoItem newItem, ApplicationUser user);
    Task<bool> MarkDoneAsync(Guid id, ApplicationUser user);
}

As ITodoItemService is specifically intended to operate on

public class TodoItem
{
    public string OwnerId { get; set; }
    public Guid Id { get; set; }
    public bool IsDone { get; set; }
    public string Title { get; set; }
    public DateTimeOffset? DueAt { get; set; }
}

why don't we define ITodoItemService with the simplest types as follows?

public interface ITodoItemService
{
    Task<IEnumerable<TodoItem>> GetIncompleteItemsAsync(string ownerId);
    Task<bool> AddItemAsync(string title, string ownerId);
    Task<bool> MarkDoneAsync(Guid id, string ownerId);
}

The simplest types represent a type of TodoItem and/or types of properties defined in TodoItem class.

The advantage of my proposal above is that ITodoItemService depends only on TodoItem type and the built-in .NET types rather than ApplicationUser class or others.

Explain Docker secrets handling

Got cut from 1.0: the deployment chapter should explain how to handle secrets in a Docker environment. Right now, it tells you to disable Facebook login if you're on Docker (which isn't ideal).

Unit test error in AddItemAsync

Feedback:

When running Unit tests: there is an error in test execution, but the test project doesn’t say anything more than this generic error message. (I tried in both VS Code and VS 2017 15.4)
Message: System.NullReferenceException : Object reference not set to an instance of an object.

I tracked it down to the second parameter of the AddItemAsync method, which expects a user but is getting passed a null value from the test method.

Missing "using AspNetCoreTodo.Models;" in Controllers\TodoController.cs

I did not find anywhere instructing to add "using AspNetCoreTodo.Models;" into Controllers\TodoController.cs, otherwise build fails:-

Controllers\TodoController.cs(25,20): error CS0246: The type or namespace name 'TodoViewModel' could not be found (are you mi
ssing a using directive or an assembly reference?) [(..)\AspNetCoreTodo\AspNetCoreTodo.csproj]

I think this should be added to mvc-basics/finish-controller.

Add scoped Vs Add singleton for database when not using Entity Framework

I did not quite get when to use services.AddScoped or services.AddSingleton while using databases.

In the book it is mentioned that when using Entity Framework services.AddScoped is required because of the way Entity Framework handles requests. But is this the same case when using other databases also like MongoDB or CouchDB??

This Stackoverflow link describes the differences between them: https://stackoverflow.com/questions/38138100/what-is-the-difference-between-services-addtransient-service-addscope-and-servi

But the accepted way is not mentioned. Could you provide some better detail?

Building the application in forward order is better

The building process in this book seems to be in reverse order. For example, this section creates ManageUserController before creating ManageUsersViewModel. Furthermore, Constants class that is defined later is not used from the beginning; it will be better if we use [Authorize(Roles=Constants.Administrator)] rather than [Authorize(Roles="Administrator")], right?

Building in reverse order also prevents us from compiling the code gradually. I propose to adopt forward order in building the apps like building a house; we start building from the ground floor to the higher floors. Thank you!

More early help for first-time users

Suggestion:

Provide a little more detail when first encountering steps such as new file creation (e.g. add a new controller). This will obviously be different for VS2017, VS Code and CLI...

Optional OOP/C# language features explanation

@Welkie had a great suggestion here:

I think it would be a good idea have a section with an intro to OOP concepts, maybe with a disclaimer that it's an optional section that can be skipped if readers are already familiar with OOP.

It may also do double duty as a nice intro to C# language features too, which means there would be less need for comments about C# features in the rest of the book (for example, talking about the constructor, or a generic type), making the rest of the book flow nicer. In this case, the section would be best pitched as an "intro to OOP concepts in C#" so that both those new to OOP and new to C# would know to read it first before continuing.

Add navigation property on model

Is it necessary to add a navigation property on the TodoItem model pointing to the User model? I may have forgotten about this. (Reminder to investigate)

Uncaught exception when using Humanizer

In Add external packages chapter, we start using Humanizer. I have encountered the following error:
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
An unhandled exception has occurred: The resource object with key 'DateHumanize_Mul tipleDaysFromNow' was not found
Parameter name: resourceKey
I think it may be caused by the fact that my Windows and Chrome are in Polish. After changing Humanizer.Core to Humanizer everything started working. It would be good to add a little note about this.

Publish to DigitalOcean with Docker

The Docker section in the deployment chapter shows you how to use docker compose and set up two containers (nginx and kestrel). It stops short of actually showing you how to deploy that multi-container application, though.

It should:

  • Point to existing DigitalOcean guide for setting up a Docker host
  • Describe how to push the built Docker image to Docker Hub
  • Explain how to spin up a multi-container app on the DigitalOcean VM (probably just docker compose up)

Identity exception

identity

I am running 2.1.300-preview2-008530 which might cause it. So I have some small differences between the version used in the book and mine. I have published what I have so far in this repo: https://github.com/jphellemons/LittleBook

for instance in program.cs BuildWebHost vs CreateWebHostBuilder
https://github.com/jphellemons/LittleBook/blob/fc5cbead616bed11dab832f72afa8638fe702869/LittleBook/Program.cs#L18

But I have missed something in the Startup.cs I think:

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.

But I have the applicationuser and identityuser service here:
https://github.com/jphellemons/LittleBook/blob/fc5cbead616bed11dab832f72afa8638fe702869/LittleBook/Startup.cs#L42

I have checked the book and can't find my error. Did I really miss something? If it's not because of a small missing part of the book. Then I am sorry and I should have posted it on StackOverflow instead of filing an issue. I just want to give some feedback on the book to try and add value. So that the book even gets better and might help more people :) and to learn stuff myself.

Portuguese (pt-br) Translation

Hi!
This seems to be a good hit in Brazil. There's no much content in Portuguese for ASP.NET Core. Since English is not so widespread there, I believe a bunch of devs can benefit from it. Even if they know English, a pt-br version would be optimal for some.

I could help translating it.. just let me know if you are interested.. and we could proceed from that.

Cheers.

Extend "Use a database" chapter with existing database info

Hey.

I think it would benefit the "Database" chapter a lot, if you talk about what to understand under the terms "Code First" and "Database First" and how to actually use EF to automatically create Models and DbContext from pre-existing database tables.
I'd assume that a bunch of people already have some sort of database structure set up which they would like to use later, even if it's not really needed for the tutorial project.

Mentioning the objective of the book in more details from the beginning

To synchronize expectation of readers with that of author, I think we need to mention from the beginning about the technology and what kind of web application we are going to build in more details.

For example, we are going to build a web application with

  • a cross platform Asp.net Core 2.0 MVC rather than Asp.net Core 2.0 Razor Pages

  • a cross platform Entity Framework Core 2.0 with SQLite

  • C# programming language

The web application uses a single database file with several tables provided by Asp.net Core Identity. As we will not discuss about master-detail relationship here, we add only a single extra table named TodoItem in which an authenticated user manages his/her Todo list. The list of todo items is not shared among other users who are either registered or unregistered.

The application also allows users to login with facebook account. Finally, the application will be deployed to Azure, Docker, etc after passing the unit test.

Some screenshots of the apps are also useful to illustrate the application. For example, the screenshot when

  • an authenticated user adds some todo items.
  • an authenticated user checks the checkbox for completed todo items.
  • etc

Rewrite Add more features chapter

  • Rebuild the Add New Item and Check to Complete features as MVC actions, not AJAX
  • Update readme, less mention of JS
  • Maybe a sidebar discussion about MVC, AJAX, JS?
  • Consider moving "Update the service layer" above "Update the database"

Add security headers

The security chapter should cover using NWebSec to return security headers like

  • Content-Security-Policy
  • Strict-Transport-Security
  • X-Frame-Options
  • X-Content-Type-Options

Add HTTPS

Didn't have time to finish this for 1.0. The security chapter should cover:

  • Require HTTPS for controllers (or the whole project)
  • Debugging HTTPS locally

Mention the dotnet secrets manager

The Facebook login instructions (which introduced and showed the secrets manager) were removed in 1.1. We should figure out how to talk about the secrets manager again, possibly in #21.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.