Essentials Flashcards

1
Q

Which versions of the .NET SDK are currently installed in my computer?

A

You can see which versions of the .NET SDK are currently installed with a terminal. Open a terminal and run the following command.

dotnet –list-sdks

You get an output similar to:

3.1.424 [C:\program files\dotnet\sdk]
5.0.100 [C:\program files\dotnet\sdk]
6.0.402 [C:\program files\dotnet\sdk]
7.0.100 [C:\program files\dotnet\sdk]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which versions of the .NET runtime are currently installed in my computer?

A

Run:
dotnet –list-runtimes

You get an output similar to:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Create a new project using command line instructions.

Step #1 Create a folder and a global.json file for the new project

A

PS C:\dev> dotnet new globaljson –sdk-version 7.0.401 –output FirstProject

The template “global.json file” was created successfully.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is wrong with this command instruction?

PS C:\dev> dotnet new mvc –no-https –output FirstProject –framework net6.0.22

A

Error: Invalid option(s):
–framework net6.0.22

‘net6.0.22’ is not a valid value for –framework. The possible values are:
net6.0 - Target net6.0
net7.0 - Target net7.0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Create a new project using command line instructions.

Step #2 Create a new ASP.NET Core project using the MVC Framework

A

PS C:\dev> dotnet new mvc –no-https –output FirstProject –framework net6.0

The template “ASP.NET Core Web App (Model-View-Controller)” was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/aspnetcore/6.0-third-party-notices for details.

Processing post-creation actions…
Restoring C:\dev\FirstProject\FirstProject.csproj:
Determining projects to restore…
Restored C:\dev\FirstProject\FirstProject.csproj (in 87 ms).
Restore succeeded.

Https is not required.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Create a new project using command line instructions.

Step #3 Create a solution file for your new project

A

PS C:\dev> dotnet new sln -o FirstProject

The template “Solution File” was created successfully.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Create a new project using command line instructions.

Step #4 Add your new project to the solution

A

PS C:\dev> dotnet sln FirstProject add FirstProject

Project FirstProject.csproj added to the solution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Create a new project using command line instructions.

PS C:\dev> dotnet new globaljson –sdk-version 7.0.401 –output FirstProject
PS C:\dev> dotnet new mvc –no-https –output FirstProject –framework net6.0
PS C:\dev> dotnet new sln -o FirstProject
PS C:\dev> dotnet sln FirstProject add FirstProject

What would be the layout of folders and files created for this new project?

A

A new solution file (.sln), a new project file (.csproj), a global file (global.json) and folders and a program file (.cs) created by choosing the MVC Framework template

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Create a new project using command line instructions.

PS C:\dev> dotnet new globaljson –sdk-version 7.0.401 –output FirstProject
PS C:\dev> dotnet new mvc –no-https –output FirstProject –framework net6.0
PS C:\dev> dotnet new sln -o FirstProject
PS C:\dev> dotnet sln FirstProject add FirstProject

What would opening this solution look in VS 2022 Solution Explorer?

A

The project FirsProject is included as a C# project within the solution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Which file determines which HTTP port ASP.NET Core will use to listen for HTTP requests?

A

launchSettings.json
Look at profiles section, applicationUrl setting!

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:5000",
      "sslPort": 0
    }
  },
  "profiles": {
    "FirstProject": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

iisSettings shows the same applicationUrl is not required

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Run a project using the command line.

A

PS C:\dev\FirstProject> dotnet run

You can now browse the url for this project http://localhost:5000/

http://localhost:5000/ is defined in launchSettings.json profiles sectio

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the content of the HomeController.cs file when first created?

A

HomeController.cs is created when using the MVC template for creating a projecty. It is located in the Controllers folder within the project.

using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using FirstProject.Models;

namespace FirstProject.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

Note: using Microsoft.AspNetCore.Mvc;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is an endpoint?

A

An endpoint is an action written in C# and defined in a controller. In ASP.NET Core applications, incoming requests are handled by endpoints.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a route?

A

A route is rule that is used to define how a request is handled. When a project is first created, a default rule is also created to get started.

The ASP.NET Core routing system is responsible for selecting the endpoint that will handle an HTTP request.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Which component processes the contents of views and generates HTML that is sent to the browser?

A

Razor!
Razor is a view engine and the expressions in views are known as Razor expressions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the standard naming convention for view files that allows Razor to locate a view?

A

Put view files in a folder whose name matches the controller that contains the action method.

Example: Views/Home folder, since the action method is defined by the Home controller.

HomeController.cs
~~~
public class HomeController : Controller
{
public ViewResult Index() { return View(“MyView”); }
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you provide data to views?

A

Action methods provide data to views by passing arguments to the View method. The data provided to the view is known as the view model.

public class HomeController : Controller
{    
    public ViewResult Index() 
    {  
        int hour = DateTime.Now.Hour;
        string viewModel = hour < 12 ? "Good Morning!" : "Good Afternoon!";
        return View("MyView", viewModel);
				}    
}

Note: return View(“MyView”, viewModel);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the difference between expressions @model and @Model?

@model string
@{
    Layout = null;
}
<!DOCTYPE html>

<html>
    <head>
        <meta name="viewport" content="width=device-width"/>
        <title>Index</title>
    </head>
    <body>
        <div>
         @Model Hello World! (from the view)
        </div>

    </body>
</html>
A

@model expression specifies the type of the view model.

@model string

The view modelo value is included in the HTML output using the @Model expression.

@Model Hello World! (from the view)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What happens when you execute the dotnet watch command? >dotnet watch

A

The comand watch runs a project and when you can make changes to the project, your code is automatically recompiled and any change is automatically displayed in the browser.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What happens when you make a mistake when the dotnet watch is running?

A

The dotnet watch command indicates that it cannot automatically update the browser. You will have to restart your application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the convention to allocate the definitions of the data model classes?

A

The data model classes are defined by convention in a folder named Models which was automatically added by the project template when the project was first created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the convention when you need to define multiple action methods?

A

A single controller class can define multiple action methods, and the convention is to group related actions in the same controller.

23
Q

Which files will Razor will look for?

public class HomeController : Controller
{
    public IActionResult Index() 
    { 
        return View(); 
    }

    public ViewResult RsvpForm()
    {
        return View();
    }
A

As per convention, Razor will look for the Index.cshtml and the RsvpForm.cshtml within the Views/Home folder/

24
Q

what happens when this instruction is run within a view file?
<a asp-action="RsvpForm">RSVP Now!</a>

A

The asp-action attribute is a tag helper attribute, which is an instruction for Razor that will be performed when the view is rendered.
In this specific example, it creates a link to the RsvpForm.cshtml file

25
Q

What is specified by the @model expression?
~~~
@model PartyInvites.Models.GuestResponse
~~~

A

The @model expression specifies that the view expects to receive a GuestResponse object as its view model!

26
Q

what is the purpose of the contents of this form element?

<form asp-action="RsvpForm" method="post">
A

The asp-action attribute applied to the form element will use the URL routing configuration to the set the action to a specific URL like this:

<form method="post" action="/Home/RsvpForm">

You should always use the features provided by ASP.NET Core to generate URLs, rather than hard-code them into your views.

27
Q

What is implied by the HttpGet attribute in this method?

[HttpGet]
public ViewResult RsvpForm()
{
    return View();
}
A

The HttpGet attribute declares thta this method should be used only for GET requests.

28
Q

What is model binding?

    [HttpPost]
    public ViewResult RsvpForm(GuestResponse guestResponse)
    {
        if (ModelState.IsValid)
        {
            Repository.AddResponse(guestResponse);
            return View("Thanks", guestResponse);
        }
        else 
        {
            return View();
        }      
        
    }
A

Model binding is an important and useful feature os ASP.NET Core whereby incoming data is parsed and the key value pairs in the HTTP request are used to populate properties of domain model types.
It lets you work with C# objects rather than dealing with individual data values!

Note that GuestResponse is automatically populated with form data.

29
Q

What happens if the first line of code (@model) is ommitted?

@model IEnumerable<PartyInvites.Models.GuestResponse>
@{    Layout = null;}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="wodth=device=width" />
    <title>Responses</title>
</head>
<body>    <div class="text-center p-2">
        <h2 class="text-center">Here is the list of people attending the party</h2>
        <table class="table table-bordered table-striped table-sm">
            <thead> <tr>  <th>Name</th>    <th>eMail</th> <th>Phone</th>     </tr> </thead>
            <tbody>
                @foreach (PartyInvites.Models.GuestResponse r in Model!)
                {
                    <tr>   <td>@r.Name</td>    <td>@r.eMail</td><td>@r.Phone</td>    </tr>
                }
            </tbody> </table>  </div></body></html>

Consider that GuestResponse does not contain a GetEnumerator method!

A

Compiler Error CS1579

*foreach statement cannot operate on variables of type ‘GuestResponse’ because ‘GuestResponse’ does not contain a public definition for ‘GetEnumerator’
*

@model implements IEnumerable for the PartyInvites.Models.GuestResponse in order to support the @foreach.

30
Q

What are the two conditions that must be met in order to iterate through a collection using @foreach?

Consider what happens when a collection does not contain GetEnumerator()

A

To iterate through a collection using the foreach statement, the collection must meet the following requirements:

Its type must include a public parameterless GetEnumerator method whose return type is either class, struct, or interface type.

The return type of the GetEnumerator method must contain a public property named Current and a public parameterless method named MoveNext whose return type is Boolean.

Compiler Error CS1579

31
Q

How do you define validation rules in an ASP.NET Core application?

A

In an ASP.NET Core application, validation rules are defined by applying attributes to model classes, which means the same validation rules can be applied in any form that uses that class.

ASP.NET Core relies on attributes from the System.ComponentModel.DataAnnotations namespace.

using System.ComponentModel.DataAnnotations;

namespace PartyInvites.Models
{
    public class GuestResponse
    {
        [Required(ErrorMessage ="Please enter your name!")]
        public string? Name { get; set; }
        [Required(ErrorMessage = "Please enter your eMail!")]
        public string? eMail { get; set; }
        
        [Required(ErrorMessage = "Please enter your phone!")]
        public string? Phone { get; set; }

        [Required(ErrorMessage = "Please confirm your attendance to the party!")]
        public bool? WillAttend { get; set; }        
    }
}

Note the Required attribute for every property definition.

32
Q

What is the purpose of the property ModelState from a base Controller class?

    [HttpPost]
    public ViewResult RsvpForm(GuestResponse guestResponse)
    {
        if (ModelState.IsValid)
        {
            Repository.AddResponse(guestResponse);
            return View("Thanks", guestResponse);
        }
        else 
        {
            return View();
        }
    }****
A

The Controller base class provides a property called ModelState that provides details of the outcome of the model binding process.

33
Q

What does it mean when ModelState.IsValid returns false?

    [HttpPost]
    public ViewResult RsvpForm(GuestResponse guestResponse)
    {
        if (ModelState.IsValid)
        {
            Repository.AddResponse(guestResponse);
            return View("Thanks", guestResponse);
        }
        else 
        {
            return View();
        }
    }
A

If ModelState.IsValid == false, it means that we have a validation error during the model binding process.

34
Q

What is the purpose of the wwwroot folder in the default configuration for ASP.NET?

A

The default configuration for ASP.NET includes support for static content (images), CSS stylesheets and JavaScript files. It maps requests to the wwwroot folder automatically.

35
Q

What is Bootstrap?

A

Bootstrap is a CSS framework that is currentlyy a mainstay of web application development.

36
Q

How does basic Bootstrap features work?

A

The basic Bootstrap features work by applying classes to elements that correspond to CSS selectors defined in the files added to the wwwroot/lib/bootstrap folder.

 <form asp-action="RsvpForm" method="post" class="m-2">
     <div asp-validation-summary="All"></div>
     <div class="form-group">
            <label asp-for=Name class="form-label">Your name:</label>
            <input asp-for=Name class="form-control" />
     </div>
        <div>
            <label asp-for=eMail class="form-label">Your eMail:</label>
            <input asp-for=eMail class="form-control" />
        </div>
        <div>
            <label asp-for=Phone class="form-label">Your phone:</label>
            <input asp-for=Phone class="form-control" />
        </div>
        <div>
            <label asp-for=WillAttend class="form-label">Will you attend to the party?</label>
            <select asp-for=WillAttend class="form-control">
                <option value="">Choose an option</option>
                <option value="true">Yes, I'll be there</option>
                <option value="false">No, I can't come'</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary mt-3">Submit RSVP</button>
 </form>

Note the class attributes in html tags

37
Q

How do you add Bootstrap support in a View file?

A

To add Bootstrap support in a View file, you need to add a link element whose href attribute loads the bootstrap.css file from the wwwroot/lib folder.

<link href="/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
38
Q

When writing an XUnit test class, what is the meaning of the Fact attribute applied to a method?

using XUnit

A

The Fact attribute is applied to a method to indicate that is a fact that should be run by the test runner. It can also be extended to support a customized definition of a test method.

39
Q

Unit test follows a pattern referred to AAA. Describe such pattern.

[Fact]
public void CanChangeProductPrice()
{
    var p = new Product { Name = "Test", Price = 100M };
		
    p.Price = 200M; 
    
    Assert.Equal(100M, p.Price); 
}

This example uses xUnit.net

A

In Unit Testing, AAA pattern refers to arrange, act & assert!

Every unit test follows this pattern:
* arrange - set up the conditions for the test
* act - apply the test
* assert - verify the results of the test

Both Arrange & Act sections are C# code. Assert section is handled by Xunit.

40
Q

Why it must be a using statement for xUnit.net when declaring a testing class?

A

The Fact attribute and the Assert class are defined in the Xunit namespace, for whcih there must be a using statement in every test class.

using Xunit;

41
Q

Use the command line to test a project.

A

> dotnet test

42
Q

Use Visual Studio to test a project

A

Run Test Explorer from Test (menu)

Note that you have to build the solution to perform the test

43
Q

In Visual Studio, how do you run only the tests that failed in a given project?

A

In Visual Studio, Test Explorer shows a command button Run Failed Tests

44
Q

What is Moq?

A

Moq is the most popular and friendly mocking framework for .NET.
A mocking package makes easy to create fake (or mock) objects for testing.

45
Q

Using the command line, how do you add the Moq mocking package to a testing project?

A

> dotnet add MyProject.Test package Moq –version 4.16.1

Current Moq package version is 4.20.69

46
Q

Using the command line, list all available .NET templates

A

> dotnet new list

> dotnet new –list is deprecated

47
Q

Describe the web project template

A

The web project template creates a project that is set up with the minimum code and content required for ASP.NET Core development.

> dotnet new web --no-https --output MySln/MyProj --framework net6.0

48
Q

What is the purpose of the app.UseStaticFiles(); line statement?

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.UseStaticFiles();
app.Run();
}
A

This statement adds support for responding to HTTP requests with static content in the wwwroot folder, such as an HTML file, etc.

49
Q

Build a project using the command line

A
> dotnet build

This will build the project located in the current folder.

50
Q

Run and build a project using the command line

A
> dotnet run

You can build and run a project located in the current folder in a single step.

51
Q

What does this line statement do?
~~~
> dotnet watch
~~~

A

.NET has an integrated hot reload feature, which compiles and applies updates to applications on the fly.
Start an application with hot reload by running
~~~
> dotnet watch
~~~
watch will monitor the project for changes. When a change is detected, it automatically recompiles the project and reloads the browser.

Note that some code changes will require an app restart!

52
Q

Using the command line, give an example of adding a package to a project

A
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 6.0.0
53
Q

Which project file contains references to packages added?

A

References of added packages to a project are included in the project .csproj file.

Reference to Microsoft.EntityFrameworkCore.SqlServer package

54
Q

Give an example of how to remove a package from a project using the command line.

A
dotnet remove package Microsoft.EntityFrameworkCore.SqlServer

In this example EntityyFramework is removed from the current project.