GithubHelp home page GithubHelp logo

markjprice / cs10dotnet6 Goto Github PK

View Code? Open in Web Editor NEW
832.0 50.0 374.0 47.57 MB

Repository for the Packt Publishing book titled "C# 10 and .NET 6 - Modern Cross-Platform Development" by Mark J. Price

C# 81.73% HTML 14.62% CSS 2.51% JavaScript 1.14%

cs10dotnet6's Introduction

Improvements & Errata - list of corrections

Join me on Discord

C# 10 and .NET 6 - Modern Cross-Platform Development, Sixth Edition

.NET 6 will reach its end-of-life on Tuesday, November 12, 2024. I recommend upgrading to .NET 8 as soon as possible.

Published on Tuesday, November 9, 2021. Order today from Packt, Amazon.com, Amazon.co.uk, Amazon.com.au, and all good book stores. My author page on Amazon: https://www.amazon.com/Mark-J-Price/e/B071DW3QGN/

All of my books on Packt's website: https://subscription.packtpub.com/search?query=mark+j.+price

Code solutions for Visual Studio 2022 and Visual Studio Code

If you have Visual Studio 2022 for Windows and Visual Studio Code and its C# extension installed on the same computer, the build process can sometimes conflict. This is because Visual Studio has its own non-standard build server that is different from the standard build server used by .NET SDK. Visual Studio 2022 and Visual Studio Code also use different file types to group projects. So I have duplicated and separated solution code for each product:

  • /vs4win: Visual Studio 2022 for Windows solution files and projects for each chapter
  • /vscode: Visual Studio Code workspace files and projects for each chapter

Three chapters and the appendix available to download as a PDF file: 9781801077361_Bonus_Content.pdf.

  • Chapter 18, Building and Consuming Specialized Services
  • Chapter 19, Building Mobile and Desktop Apps Using .NET MAUI (also available as an updated online document)
  • Chapter 20, Protecting Your Data and Applications
  • Appendix A, Answers to the Test Your Knowledge Questions (click the PDF file above, download, and the Appendix starts on page 137.)

Supplementary print book materials available to download:

  • Color images of the screenshots/diagrams used in this book

Important

Corrections for typos and other mistakes and improvements like refactoring code. Useful links to other related material.

Join me on Discord

Join me on Discord using this invite: https://packt.link/csharp10dotnet6

Discord channel for the C# 10 and .NET 6 book

Microsoft Certifications

Announcing the New Foundational C# Certification with freeCodeCamp: https://devblogs.microsoft.com/dotnet/announcing-foundational-csharp-certification/

Microsoft used to have professional exams and certifications for developers that covered skills like C# and ASP.NET. Sadly, they have retired them all. These days, the only developer-adjacent exams and certifications are for Azure or Power Platform, as you can see from the certification poster: https://aka.ms/traincertposter

Microsoft .NET community support

Interviews with me

Podcast interviews with me:

Written interviews with me:

Book cover

C# 10 and .NET 6 by Packt Publishing

cs10dotnet6's People

Contributors

cr0rc avatar knoxyz avatar markjprice 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

cs10dotnet6's Issues

Encoding strings as byte arrays

The code on page 391 - "WorkingWithEncodings" always uses UTF-8 regardless of the number entered. I also checked the Chapter09 solution from the downloaded code and get the same result.

Not significant, but there is a warning that UTF-7 is obsolete and insecure.

Example Issue - Chapter 2 target-typed new

In Chapter 2: Using target-typed new to instantiate objects there is a code example:

class Person
{
  public DateTime BirthDate;
}
Person kim = new();
kim.BirthDate = new(1967, 12, 26); // instead of: new DateTime(1967, 12, 26)

However, running it in /Variables/Program.cs doesn't compile. Fails with error CS8803: Top-level statements must precede namespace and type declarations.

I had to change it to this to get it to build:

Person kim = new();
kim.BirthDate = new(1967, 12, 26); // instead of: new DateTime(1967, 12, 26)

class Person
{
  public DateTime BirthDate;
}

Unable to documenting functions with XML comments

Hello,
Page 140-141. Took me some time to realise that for using the XML comments ( tooltip
with only basic information was popping out), functions should be outside the Main method. It would be nice to have some note about it in the errata.

net6 before

net6 after

Chapter 4 Factorial method issue

Hi Mark J Price,
First of all , thank you for amazing book.
Page 137 (Chapter 4) In the Calculating factorials with recursion heading, 0 is returned for 0 in the Factorial method. But 0 factorial equals 1.

Mention property explicitly

In section "Setting options with arguments" on page 88 of the print book, it is much clearer if you mention that ForegroundColor, BackgroundColor and CursorSize are properties of Console. When I first read this, I thought why you used Pascal case to name a variable, instead of camel case and why you did not specify the type of the variables.

OmniSharp: Select Project bug

In Chapter 01 pg 28 step 6 of the "Adding a second project using Visual Studio Code" section the attempt to launch OmniSharp: Select Project results in an error.

This bug has been raised as an issue ( #4914) on the OmniSharp Git project. It appears that the fix has been proposed to the master branch and is currently in release 1.23.18-beta2.

Based on the comments on pg 28 and pg 41 of Chapter 01, it appears that the use of this command is required in order to have multiple projects in the same workspace.

The current stable that I've installed is 1.23.17. Is it possible to update the OmniSharp extension in Visual Studio Code to 1.23.18-beta2 so that I can complete these steps? Or is it better to just wait for the stable release of 1.23.18 and come back to this later?

BTW - Great book so far. Appreciate your efforts.

Minor error

Inside the box for Good Practice on page 187 of the print book:

If you use are writing should be If you are writing.

Exercise 3.1, Answer 6 Clarification

The Bonus Content mentions for exercise 3.1, answer 6

The condition expression is required to evaluate to true or false, but the other two are optional

This could be misleading, as the condition expression is optional too.

The same applies for answer 8.

P28 Tip - Unable to select active project in VS Code - Extension 'ms-dotnettools.csharp' CANNOT use API proposal

If you receive the following error when trying to follow the advice on page 28, be aware that there is a bug in the C# for Visual Studio Code extension (version 1.23.17 released on 12/3/2021). To get around this, you have to either rollback the C# extension to a prior version or manually download / install the v1.24.0-beta1 version found here (expand the collapsed assets section by clicking on the chevron): C# extension v1.24.0-beta1.

Formal error text:
Extension 'ms-dotnettools.csharp' CANNOT use API proposal: quickPickSeparators. Its package.json#enabledApiProposals-property declares: [] but NOT quickPickSeparators. The missing proposal MUST be added and you must start in extension development mode or use the following command line switch: --enable-proposed-api ms-dotnettools.csharp

Good Practice tip:
To enable debugging and other useful features, like code formatting and Go to Definition, you must tell OmniSharp which project you are actively working on in Visual Studio Code. You can quickly toggle active projects by clicking the project/folder to the right of the flame icon on the left side of the status bar.

ilspy-vscode

Windows 10 pro 64bit
HP Intel(R) Core(TM) i5-2520M CPU @ 2.50GHz 2.50 GHz RAM 8gb

VS Code Version: 1.64.2
Node.js: 14.16.0
OS: Windows_NT x64 10.0.19044

I had installed ilspy-vscode and this errors has appeared:

image
image

How can i solve it to use ilsy ?

Bonus_Content.pdf p. 149, Ch.4 #3 Answer?

In the file cs10dotnet6-main/9781801077361_Bonus_Content.pdf
on p. 149 (Ch.4 Question 3 Answer) it reads:
Answer: F5 saves, compiles, runs, and attaches the debugger; Ctrl or Cmd + F5 saves, compiles, and runs the application with the debugger attached;
which sounds like F5 and Ctrl+F5 do the same thing. However I think Ctrl+F5 runs without the debugger.

Getting Git

I did not quite follow your intent about getting Git. On page 38 you use the command git clone https://github.com/markprice/cs10dotnet6.git. The command does not work without the Git App. I located the app at [https://git-scm.com/downloads] for windows (and possibly unix et al). I installed it and it did perform the clone operation. Did you want to suggest any configuration advice for the git install?

Formatting a string

On page 83 of the print book, the formatting string is not necessary when outputting the header since arg1 is a string:

Console.WriteLine(
    format: "{0,-10} {1,6}",
    arg0: "Name",
    arg1: "Count"
);

Building and Consuming Web Services - HttpLogging needs a tweak to appsettings.development.json

Just a quick one - on (or around) page 699 - 'Enabling HTTP logging' - I followed the steps in the book to add HttpLogging, but then didn't see any log messages when calling the localhost:5001/api/customers web service

I solved this by opening up the appsettings.Development.json file and changing

"Microsoft.AspNetCore": "Warning"
to
"Microsoft.AspNetCore": "Information"

The logging then appeared on next run.

Wording should be changed

P 171 #4. "Delete the ex" = ????. How about Change "Throw ex;", to "throw". OR, Remove the 'ex' from the 'Throw ex;' statement.

OmniSharp.MSBuild.ProjectManager - Attempted to update project that is not loaded

Getting Below Error after installing C# extension:-

Loading project: /Users/umesh/C#10/Code/Chapter02-vscode/Vocabulary/Vocabulary.csproj
It was not possible to find any installed .NET SDKs.
Install a .NET SDK from:
https://aka.ms/dotnet-download
[fail]: OmniSharp.MSBuild.ProjectManager
Failed to load project file '{projectFilePath}'.
Microsoft.Build.Exceptions.InvalidProjectFileException: The SDK 'Microsoft.NET.Sdk' specified could not be found.

umesh@Umeshs-MacBook-Air Vocabulary % dotnet --info
.NET SDK (reflecting any global.json):
Version: 6.0.100
Commit: 9e8b04bbff

Runtime Environment:
OS Name: Mac OS X
OS Version: 12.0
OS Platform: Darwin
RID: osx-x64
Base Path: /usr/local/share/dotnet/x64/sdk/6.0.100/

Host (useful for support):
Version: 6.0.0
Commit: 4822e3c3aa

.NET SDKs installed:
5.0.403 [/usr/local/share/dotnet/x64/sdk]
6.0.100 [/usr/local/share/dotnet/x64/sdk]

.NET runtimes installed:
Microsoft.AspNetCore.App 5.0.12 [/usr/local/share/dotnet/x64/shared/Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 6.0.0 [/usr/local/share/dotnet/x64/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 5.0.12 [/usr/local/share/dotnet/x64/shared/Microsoft.NETCore.App]
Microsoft.NETCore.App 6.0.0 [/usr/local/share/dotnet/x64/shared/Microsoft.NETCore.App]

To install additional .NET runtimes or SDKs:
https://aka.ms/dotnet-download

Missing $ on interpolated string.

Not sure of page# but towards the end of Chapter 2.
With C# 10, interpolated strings can now be used, as shown in the following code:

private const string fullname = "{firstname} {lastname}";

Without the $, the string is literal and not interpolated.

After installing VS 2022 where .NET 6 SDK is also installed, dotnet cli on my computer is not working

Hi Mark

I've just found that after installing VS 2022 and .NET 6 SDK. dotnet cli on my computer is not working.
For example, when I try to use dotnet new console or dotnet run. dotnet keep responding with this error:-

Missing or invalid manifest version
at Microsoft.NET.Sdk.WorkloadManifestReader.WorkloadManifestReader.ReadWorkloadManifest(String id, String informationalPath, LocalizationCatalog localizationCatalog, Utf8JsonStreamReader& reader)
at Microsoft.NET.Sdk.WorkloadManifestReader.WorkloadManifestReader.ReadWorkloadManifest(String manifestId, Stream manifestStream, Stream localizationStream, String informationalPath)
at Microsoft.NET.Sdk.WorkloadManifestReader.WorkloadResolver.LoadManifestsFromProvider(IWorkloadManifestProvider manifestProvider)
at Microsoft.NET.Sdk.WorkloadManifestReader.WorkloadResolver.Create(IWorkloadManifestProvider manifestProvider, String dotnetRootPath, String sdkVersion, String userProfileDir)
at Microsoft.DotNet.TemplateLocator.TemplateLocator.GetDotnetSdkTemplatePackages(String sdkVersion, String dotnetRootPath, String userProfileDir)
at Microsoft.DotNet.Tools.New.OptionalWorkloadProvider.GetAllTemplatePackagesAsync(CancellationToken cancellationToken)
at Microsoft.TemplateEngine.Edge.Settings.TemplatePackageManager.<>c__DisplayClass21_0.b__2()
at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.TemplateEngine.Edge.Settings.TemplatePackageManager.GetTemplatePackagesAsync(Boolean force, CancellationToken cancellationToken)
at Microsoft.TemplateEngine.Edge.Settings.TemplatePackageManager.UpdateTemplateCacheAsync(Boolean needsRebuild, CancellationToken cancellationToken)
at Microsoft.TemplateEngine.Edge.Settings.TemplatePackageManager.GetTemplatesAsync(CancellationToken cancellationToken)
at Microsoft.TemplateEngine.Cli.TemplateResolution.BaseTemplateResolver.GetTemplateGroupsAsync(CancellationToken cancellationToken)
at Microsoft.TemplateEngine.Cli.TemplateResolution.InstantiateTemplateResolver.ResolveTemplatesAsync(INewCommandInput commandInput, String defaultLanguage, CancellationToken cancellationToken)
at Microsoft.TemplateEngine.Cli.TemplateInvocationCoordinator.CoordinateInvocationAsync(INewCommandInput commandInput, CancellationToken cancellationToken)
at Microsoft.TemplateEngine.Cli.New3Command.EnterTemplateManipulationFlowAsync(INewCommandInput commandInput)
at Microsoft.TemplateEngine.Cli.New3Command.ExecuteAsync(INewCommandInput commandInput)
at Microsoft.TemplateEngine.Cli.New3Command.ActualRun(String commandName, ITemplateEngineHost host, ITelemetryLogger telemetryLogger, New3Callbacks callbacks, String[] args, String hivePath)

Hope you can help!
Regards,
Charnsit

Negative value result in Chapter 12

I'm trying your recorder.cs example on my Mac M1 with Rider of Jetbrains. I get the following output after several runs.

Processing. Please wait...
-1,867,776 physical bytes used.
14,041,088 virtual bytes used.
00:00:06.0042556 time span ellapsed.
6,004 total milliseconds ellapsed.

Can we say there exists a bug in .Net 6? When I'm running it on parallel desktop, it works as illustrated in your book.

-1,867,776 ??

Error in Chapter04/PrimeFactorsLib/Primes.cs

Dear,
Above Class snippet cannot work in this way because after having found the prime number you must "restart" the foreach, otherwise it continues with the next prime number divisor (try passing 50 and see result !!)
Enclosed the correct code snippet.
Ragards.
Cristiano
Primi.txt

DbContextFactory injection instead of DbContext in the Blazor Server

When I am injecting dbContext (page740) and I am trying to add or update Customers
I am getting an exception

Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type 'Xenbill.Shared.NorthwindContext'. System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913. at Microsoft.EntityFrameworkCore.Infrastructure.Internal.ConcurrencyDetector.EnterCriticalSection() at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.AsyncEnumerator.MoveNextAsync()

System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
at Microsoft.EntityFrameworkCore.Infrastructure.Internal.ConcurrencyDetector.EnterCriticalSection()
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.AsyncEnumerator.MoveNextAsync() Exception thrown: 'System.InvalidOperationException' in System.Private.CoreLib.dll Microsoft.AspNetCore.Components.Server.Circuits.RemoteRenderer: Warning: Unhandled exception rendering component: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.

After a little research I injected dbContextFactory instead of DbContext directly.
So I create new instances of dbContext every time I use NorthwindService ( which is Transient) .
I don't have exceptions when I am implementing this way.

Is this ok ?

btw Thx for this great book !!

Chapter 10 - 'Scaffolding models using an existing database' failed on M1 Mac with ARM dotnet

Just a quick report about an issue I had today with Chapter 10 (not specifically an issue with the book, but took a bit of searching to fix)

Hardware is an M1 Mac Mini, running Monterey, only version of .NET Sdk installed is Core 6(.0.201), ARM version.

Following the dotnet tool install --global dotnet-ef --version 6.0.0 and then adding it to the path appears to work fine at first glance, but running the subsequent steps to scaffold models using the existing database threw up an error...

running the dotnet ef dbcontext [...] resulted in

A fatal error occurred. The required library libhostfxr.dylib could not be found.
If this is a self-contained application, that library should exist in [/Users/[name]/.dotnet/tools/.store/dotnet-ef/6.0.0/dotnet-ef/6.0.0/tools/netcoreapp3.1/any/].
If this is a framework-dependent application, install the runtime in the global location [/usr/local/share/dotnet/x64] or use the DOTNET_ROOT environment variable to specify the runtime location or register the runtime location in [/etc/dotnet].

After a bit of Googling, seems like there's an issue with the tool installer which made it install the x86 version instead of the ARM version.

Uninstalling the x86 version using dotnet tool uninstall --global dotnet-ef and then following the instructions at dotnet/sdk#21187 (comment) to force the install of the ARM version using dotnet tool install --global dotnet-ef -a arm64 then allowed the dotnet ef dbcontext [...] step further on to work correctly.

Hope this helps someone!

Not Grasping: Visual Studio Code runs the console app in project folder?

Hello Mark,

I just finished the Chapter 4 sub-section "Logging during development and runtime". So far the book is great, and I'm learning about all the new features in .NET-land since I've been away from .NET for some years.

Using Visual Studio 2022 on Mac, I set the appsettings.json file to copy to output directory: Copy If Newer. And during execution, the debugger allows me to confirm reading from appsettings.json as seen in variable TraceSwitch ts. Success!

However using Visual Studio Code for Mac, I did not have the same success. Regarding appsettings.json location, you had written:

"This is necessary because unlike Visual Studio Code, which runs the console app in the project folder, Visual Studio runs the console app in Instrumenting\bin\Debug\net6.0 or Instrumenting\bin\Release\net6.0."

I'm confused by this quote, because all my attempts in Visual Studio Code to confirm the reading of appsettings.json with ts suggest that this JSON file is not being read, because it's not found. Also, here is my launch.json snippet:

        {
            "name": ".NET Core Launch (console) - Instrumenting",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            "program": "${workspaceFolder}/Instrumenting/bin/Debug/net6.0/Instrumenting.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            "stopAtEntry": false,
            "console": "internalConsole"
        },

Q1) From your quote, can you help me understand what you mean when you write that, Visual Studio Code runs the console app in the project folder? So far I cannot confirm that this is the case, rather the console app runs from /bin/*/* is what I observe.

Q2) In Visual Studio Code how do we also copy appsettings.json to output directory upon build?

Thanks!

Unable to create interactive C# books in Visual Studio Code

Hello,

I am unable to create interactive C# books in Visual Studio Code. I do the proper commands and then nothing appears. I have version 1.62.3 of Visual Studio Code. I also tried with Visual Studio Code - Insiders 1.63.0.0 and I have no problem creating interactive books. The problem occurs to me only with version 1.62.3.

Are there other people having the same issue with version 1.62.3 or I'm alone?

Information about my system:

  • Windows 10 Enterprise 64 bits version 20H2
  • Intel Core i7-6820HQ @ 2.7GHz

Typo in code snippet: Chapter_10

On page 427 - the code snippet adding the OnModelCreating method has a typo in the if statement. Specifically it reads

if (ProjectConstants.DatabaseProvider == "SQLite")

whereas it should say

if (ProjectConstants.DataBaseProvider == "SQLite")

Page 535 connectionString doesn't work

Hi, Mark:

Following the connection string specification on page 535 caused me to see "The certificate chain was issued by an authority that is not trusted." error when the code tries to open the connection.

Adding the following in the connectionString seems to solve the problem.

          "TrustServerCertificate=True;" +

Minor issue in errata.md - Page 28

The text for the errata states to install version v1.24.0-beta1 in the text. But the "download the VSIX" hypertext link points to the v1.23.18-beta2 VSIX file.

image

Note that the overriding bug in OmniSharp was resolved in v1.23.18-beta2 so installing either version will work.

Nested and child tasks wrong output

On page 522 the whole code looks like this

using static System.Console;

Task outerTask = Task.Factory.StartNew(OuterMethod);
outerTask.Wait();
WriteLine("Console app is stopping.");

static void OuterMethod()
{
    WriteLine("Outer method starting...");
    Task innerTask = Task.Factory.StartNew(InnerMethod);
    WriteLine("Outer method finished.");
}
static void InnerMethod()
{
    WriteLine("Inner method starting...");
    Thread.Sleep(2000);
    WriteLine("Inner method finished.");
}

But the output i get is always

Outer method starting...
Outer method finished.
Console app is stopping.

Inner method never gets called for some reason. Also later when you do attach to parent i get this

Outer method starting...
Outer method finished.
Inner method starting...
Inner method finished.
Console app is stopping.

Outer method always starts and finish before inner method starts.

Building a weather service using minimal APIs - ERROR: A path base can only be configured using IApplicationBuilder.UsePathBase().

Just came across the following issue on or around page 712 when building the minimal API web service.

Using VS Code, when following the instructions and then running the API I received the following error

Unhandled exception. System.InvalidOperationException: A path base can only be configured using IApplicationBuilder.UsePathBase(). at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.ParseAddress(String address, Boolean& https) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.BindAsync(AddressBindContext context, CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindAsync(IEnumerable listenOptions, AddressBindContext context, CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.BindAsync(CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.StartAsync[TContext](IHttpApplication application, CancellationToken cancellationToken) at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken) at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken) at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host) at Microsoft.AspNetCore.Builder.WebApplication.Run(String url)

Tweaking the launchSettings.json to

"applicationUrl": "https://localhost:5003/",
"launchUrl": "api/weather",

got around the issue and allowed the API to start up.

Carousel Not Working in Chapter 15

I was having issues getting the carousel to actually transition through each picture in the MVC project in Chapter 15. When loading the page, the first picture would load and that is it. The carousel was not transitioning to the second picture after the 3000ms interval.

Comparing the code to the example code in the Bootstrap 5 documents (Bootstrap Docs) I can see that there was a change to this code between Bootstrap 4 and Bootstrap 5. The code on pg 645 & 646 for the carousel needs to be updated to use "data-bs-" versus "data-".

For example this first line of code for the carousel:

<div id="categories" class="carousel slide" data-ride="carousel" data-interval="3000" data-keyboard="true">

should be for it to work with the Bootstrap 5 CSS file that was defaulted in the MVC template

<div id="categories" class="carousel slide" data-bs-ride="carousel" data-bs-interval="3000" data-keyboard="true">

Both date-ride & data-interval need to be changed to data-bs-ride and data-bs-interval. There are six locations in the code that need to be modified.

When I changed the code to the following, the carousel worked for me:

@if (Model is not null)
{
    <div id="categories" class="carousel slide" data-bs-ride="carousel" data-bs-interval="3000" data-keyboard="true">
        <ol class="carousel-indicators">
            @for (int c = 0; c < Model.Categories.Count; c++)
            {
                if (c == 0)
                {
                    currentItem = "active";
                }
                else
                {
                    currentItem = "";
                }
                <li data-bs-target="#categories" data-bs-slide-to="@c" class="@currentItem"></li>
            }
        </ol>
        <div class="carousel-inner">
            @for (int c = 0; c < Model.Categories.Count; c++)
            {
                if (c == 0)
                {
                    currentItem = "active";
                }
                else
                {
                    currentItem = "";
                }
                <div class="carousel-item @currentItem">
                    <img class="d-block w-100" src="~/images/category@(Model.Categories[c].CategoryId).jpeg"
                alt="@Model.Categories[c].CategoryName" >
                    <div class="carousel-caption d-none d-md-block">
                        <h2>@Model.Categories[c].CategoryName</h2>
                        <h3>@Model.Categories[c].Description</h3>
                        <p>
                            <a class="btn btn-primary" href="/category/@Model.Categories[c].CategoryId">Views</a>
                        </p>
                    </div>
                </div>
            }
        </div>
        <a class="carousel-control-prev" href="#categories" role="button" data-bs-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next" href="#categories" role="button" data-bs-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>
    </div>
}

Chap01 - Notebooks

Upon opening Command Palette and entering .net inter as directed I get nothing. No reference to .NET Interactive.
BTW, I am running the most recent updated version of VS Code on a Windows 10 OS.

Erratta.md

Reference to ## Page 179 - Understanding the call stack should be ## Page 169 ...

Improvement comment for Go To Definition

On pages 40 through 41 you explain the Go To Definition, which you may want to point out especially in Code the comments do not show up. and when I looked at the lines on my Visual Studio 2022 Community the lines were different. I like the fact you did not rehash your previous book and you added some additional resources. from your previous book. The image is from Visual Studio Community Preview Edition which as you can see varies
image
Thanks,
Bernard A. Bailey, Jr.

Converting numbers from cardinal to ordinal

Hi,

I noticed the provided code sample under this section in Chapter 04 would create a bug for 11, 12, 13 special cases for numbers greater than 100, i.e. 111, 112, 113. I added a fix, please check it out.

`static string CardinalToOrdinal(int number)
{
int lastTwoDigits = number % 100;

switch (lastTwoDigits)
{
    case 11: // special cases from 11th to 13th
    case 12:
    case 13:
        return $"{number}th";
    default:
        int lastDigit = number % 10;

        string suffix = lastDigit switch
        {
            1 => "st",
            2 => "nd",
            3 => "rd",
            _ => "th"
        };
        return $"{number}{suffix}";
}

}`

System.NotSupported Exception

When running Chapter09, "WorkingWithJson", I get a "System.NotSupported Exception saying "System.DateOnly instances are not supported. Exception message attached.

SystemNotSupportedException

Are there issues with using VS Code in a VM?

Windows 10, VirtualBox VM

P 151 / 153. Set a condition < or >, it always stops at that line.

Also, every once in a while, while editing code, instead of a '"' (quote), an '@' appears. I need to restart the VM, which fixes this, but then it can happen again.

Configuring HTTP Clients using HttpClientFactory - .NET 6.0 bug prevents WebHost.UseUrls from working

Just come across what appears to be a bug in .NET 6.0. I followed the instructions on (or around) page 701 to specify port 5002 for HTTPS however when running the WebApi project it still fired up using port 5001 (which then caused conflict when running the Mvc project).

A quick Google led me to an acknowledgement of the problem here - dotnet/aspnetcore#38185. Looks like it's intended to be fixed in 6.0.4

To get around the issue for now I simply tweaked the WebApi properties/launchsettings.json to specifically use port 5002 (for HTTPS, and tweaked HTTP to 5003 so it didn't conflict).

Hope this helps. :)

Ch12 - Unclear instructions in db setup

At the bottom of page 560 there is an instruction to "remove all Fluent API statement that call the ValueGeneratedNever method to configure primary key properties".

So do you remove only the .ValueGeneratedNever part, or the entire line, or the entire modelBuilder.Entity call?

The instruction doesn't make it very clear and the code example only shows how it looks before, with no view of after.

Chapter 1 typo

Page 32 says

  1. Hover your mouse above the code block and click + Markup to add a Markdown cell.

instead of +Markdown

If this is for code stuff only, sorry.

Bonus Content - I'm struggling getting the GraphQL builder to work

Just trying to work through the GraphQL section at the moment, and I'm having a massive headache with it. It looks as though GraphQL have made the implementation of .AddGraphQL you're using in the book obsolete with latest versions, and I'm struggling to tweak it to a correct implementation.

I've seen someone else mention the issue here - graphql-dotnet/graphql-dotnet#2856

I can get _so _ far by adding the GraphQL, GraphQL.MicrosoftDI and GraphQL.SystemTextJson packages, and tweaking the .AddGraphQL implementation to something like

builder.Services.AddGraphQL(b => b .AddSystemTextJson() .AddGraphTypes(typeof(NorthwindSchema).Assembly) //.AddDataLoader() );

But I can't find the right import for .AddDataLoader() and to be honest it feels like I'm taking random stabs in the dark. I'm not finding too much on the web for this either.

I don't suppose you've used it recently and have any suggestions I could try?

:NO on pages 64 and 70

The ":NO" on page 64 and page 70 prints "NO" instead of the expected result. If I remove the ":NO", then it prints the values as expected.

vscode extension id typo

Hello,

In Chapter 1, tintoy.msbuild-project-tools was mistyped as tinytoy.msbuild-project-tools

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.