From 816e13c81d3568fe9449445d10e44bd620589081 Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Thu, 6 Oct 2022 13:24:03 -0500 Subject: [PATCH 01/15] updated VS setup and install for both win and mac --- .../introduction-and-setup/mac-setup.rst | 78 ++++++++---- src/chapters/introduction-and-setup/setup.rst | 61 +++++---- .../introduction-and-setup/windows-setup.rst | 117 ++++++++++-------- src/conf.py | 2 +- 4 files changed, 153 insertions(+), 105 deletions(-) diff --git a/src/chapters/introduction-and-setup/mac-setup.rst b/src/chapters/introduction-and-setup/mac-setup.rst index e2c92bdd..9edbc2fd 100644 --- a/src/chapters/introduction-and-setup/mac-setup.rst +++ b/src/chapters/introduction-and-setup/mac-setup.rst @@ -1,42 +1,68 @@ Mac Users: Visual Studio for Mac ================================ -#. Check that you are using supported MacOS version `here `__. +Before you start the installation guide, read through each step below. +You will find the recommended features and functionality to install listed in each step. -#. Download `Visual Studio for Mac `__. You may be prompted for your - computer's password to complete the download and begin installation. +.. admonition:: Warning -#. The first choice you will need to make in the setup process are the development platforms you want to include in - the install with Visual Studio. Select **.NET Core** only. + Allow at least **an hour** for the installation process. - .. figure:: ./figures/vsmac-dotnetcore-install.png - :alt: Select Visual Studio .NET Core package to install. +Installation Steps +------------------ +Walk through the installation process by following Microsoft's `Install Visual Studio for Mac `_ guide. - Select .NET Core package to install. +**Prerequisites** + +Check out that you can install this on your computer. -#. Once installed, the IDE will open on it's own. If it does not, you may need to open it manually. You will next - see a window asking you to login to your Microsoft account. You do not need to sign-in in order to use the - IDE for this class and can select *I'll do this later* to continue setup. +**Install Visual Studio** - .. figure:: ./figures/vsmac-microsoft-account.png - :alt: Visual Studio Microsoft sign-in page. +#. Download the installer. - Visual Studio Microsoft sign-in page. - -#. Next you will be asked to choose which shortcut system to use. You may not have a preference yet and can always - change this later. If you are familiar with the text editor Visual Studio Code, this may be a good starting option - for you. +#. Install using the *.dmg* file. - .. figure:: ./figures/vsmac-shortcut-selection.png - :alt: Visual Studio keyboard shortcut selection. +#. Open the application. - Visual Studio keyboard shortcut selection. +#. Continue if you agree with the privacy statements and license terms. -#. Finally, you have made it to the project selection window. This will be the item you will see when you open - Visual Studio. You do not need to create or open a new project just yet. +#. The only component required for this course is **.NET**. + + You can modify this later as you gain more coding experience. - .. figure:: ./figures/vsmac-project-opener.png - :alt: Visual Studio opening project selection pane. +#. Select the **Install** button. - Visual Studio opening project selection pane. +#. Assist the installer as needed. + This may take a while, but stick around. + You may be asked to enter your password a few times. + +#. To personalize or not? This is up to you. + + Microsoft Account + Creating a Microsoft account is optional. + + Keyboard Shortcuts + The default is Visual Studio for Mac and that is a good starting option. + You can change this later. + +#. Launch Visual Studio and start developing + + +A Tour of Your New IDE +---------------------- + +Microsoft has created a `walkthrough `_ of the Visual Studio 2022 for Mac. +We recommend you read through this to learn the location of key components within your new IDE. + + +Troubleshooting +--------------- + +Already have Visual Studio on Your Computer? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +If you don’t have this most recent version of Visual Studio installed, you will need to updated it. +The `Update Visual Studio for Mac Guide `_ can help you update your old version of VS to the latest. +At the time of this writing, the current version for the course is 2022. + +Updating can also help you keep any of your workloads, extensions, or other installed packages up to date. \ No newline at end of file diff --git a/src/chapters/introduction-and-setup/setup.rst b/src/chapters/introduction-and-setup/setup.rst index a0bfb589..f7819c64 100644 --- a/src/chapters/introduction-and-setup/setup.rst +++ b/src/chapters/introduction-and-setup/setup.rst @@ -7,51 +7,66 @@ For the entirety of this course, we will be coding in C# with the help of Visual .. _install-visual-studio: -Visual Studio -------------- +The Integrated Development Environment +-------------------------------------- -Visual Studio is an **integrated development environment (IDE)**. An IDE is like a text -editor on steroids. We can write and edit code *and* make use of additional features that -enhance our coding experience. Visual Studio offers -code completion hints, debugging, and even it's own compiler. We'll be using it throughout -this course, so it's time to get familiar with some of the basics. +Visual Studio (VS) is an **integrated development environment (IDE)**. +An IDE is like a text editor on steroids. +We can write and edit code *and* make use of additional features that enhance our coding experience. +VS offers code completion hints, debugging, and even it's own compiler. + +We'll be using it throughout this course, so it's time to get familiar with some of the basics. .. admonition:: Note - Visual Studio IDE is not the same application as the text editor called Visual Studio Code. - If you already have VS Code installed on your machine, you will still need to - install and configure Visual Studio. + Visual Studio IDE is *not* the same application as the source-code editor called Visual Studio Code (VS Code). + If you already have VS Code installed on your machine, you will still need to install and configure VS. .. _dotnet-intro: -.. index:: ! .NET Core, ! Software Development Kit, ! SDK +.. index:: ! .NET, ! Software Development Kit, ! SDK + +Development Frameworks +---------------------- -.NET Core ---------- +.NET +^^^^ -**.NET Core** is a set of tools for developing software in a number of different programming languages, including C#. +**.NET** is a set of tools for developing software in a number of different programming languages, including C#. The tools together make what is known as a **software development kit**, or **SDK**. -Unlike it's predecessor, just called .NET or .NET Framework, .NET Core is open-source and available on several -operating systems. The SDK provides the runtime environment and the virtual machine for compiling -and running C# programs. -Starting with .NET 5, in November of 2020, the terms *Core and Framework* have been deprecated. There is now just one -version of .NET that is based on .NET Core. +Some of its featuers: + +* Open-source and available on several operating systems. +* The SDK provides the runtime environment and the virtual machine for compiling and running C# programs. +* Contains the **base class libraries** which include the built-in code that takes care of common programming items, such as object types. +* Able to be extended using additional frameworks such as ASP.NET. + +You can learn more about .NET `here `_. -.NET Core also notably contains the base class libraries. This is the built-in code that takes care of common programming items, -such as object types. +ASP.NET Core +^^^^^^^^^^^^ + +As we progress through this portion of the course, we will start creating web projects. +.NET will compile C#, but does not contain any libraries for web development. +ASP.NET Core is an open source collection of libraries specifically for web development and creating dynamic web applications. + +We will use ASP.NET Core midway through this course; however, you can to learn more about this framework at `this `_ site. .. _compiling-csharp: -A summary of the relationship between the code you write in C# and tools provided by .NET Core: +C# and the Frameworks +--------------------- + +A summary of the relationship between the code you write in C# and tools provided by .NET: #. We write code in C#. #. The source code is compiled (like translating) into another intermediate language. #. The intermediate code is read by a runtime program included in the .NET SDK. #. The runtime environment translates the intermediate code into machine-readable language. -Fortunately for us, .NET Core can be installed along with Visual Studio IDE. +Fortunately for us, .NET can be installed along with Visual Studio IDE. Windows Users vs. Mac Users --------------------------- diff --git a/src/chapters/introduction-and-setup/windows-setup.rst b/src/chapters/introduction-and-setup/windows-setup.rst index 4c5ecfd2..e2e12a66 100644 --- a/src/chapters/introduction-and-setup/windows-setup.rst +++ b/src/chapters/introduction-and-setup/windows-setup.rst @@ -1,90 +1,97 @@ Windows Users: Visual Studio Community Edition ============================================== -#. Download the Community version of Visual Studio from `this page `__. +Before you start the installation guide, read through each step below. +You will find the recommended features and functionality to install listed in each step. - .. admonition:: Note - - Users can select from multiple options for software downloads, such as Visual Studio Code and - Visual Studio for Mac, on this page. Do NOT select either of these options! - - Allow at least an hour for the installation process. - -#. Run the installer, and select the following packages from the *Workloads* pane: +.. admonition:: Warning - - ASP.NET and web development - - Azure development - - Data storage and processing - - .NET core cross-platform development + Allow at least **an hour** for the installation process. - Your selections will look like these screens: +Installation Steps +------------------ +Walk through the installation process by following Microsoft's `Install Visual Studio `_ guide. - .. figure:: figures/vs-packages.png - :alt: VS install ASP.NET and web development, Azure development, and data storage and processing packages. +#. Verify that your computer can run Visual Studio 2022. - VS install ASP.NET and web development, Azure development, and data storage and processing packages. +#. Download the **Community** version of **Visual Studio 2022**. - .. figure:: figures/vs-packages-2.png - :alt: VS install .NET core cross-platform development package. + .. admonition:: Note + Make sure you select **Visual Studio 2022**. - VS install .NET core cross-platform development package. + You will see multiple options for software downloads, such as Visual Studio Code and + Visual Studio for Mac, on this page. Do NOT select either of these options! -#. When the install finishes running, Visual Studio will open by default. -#. Sign in to an existing Microsoft account or create a new one to take advantage of the Community Edition. +#. Install the Visual Studio Installer - .. figure:: figures/vs-windows-welcome.png - :alt: VS welcome modal for windows. +#. Chose your **Workloads:** + + Select the following packages from the *Workloads* pane: - Visual Studio welcome window. + - ASP.NET and web development + - Azure development + - Data storage and processing + - .NET core cross-platform development -#. The launcher window will prompt you with some choices via a window - similar to what you see below. Select the displayed options. (If you - don’t see the box about applying customizations, don’t worry about it, - just proceed.) + You may need to scroll down to find all of the recommended workloads. - .. figure:: figures/launch-options.png - :scale: 40% - :alt: Visual Studio Launch Options, Visual C# selected + .. admonition:: Note - Launch Options, , Visual C# selected + Steps 5 - 7 are for customizing your Visual Studio. + They are optional, and will use the default setting if applicable. + This is perfectly acceptable and will work well for this course. -.. _vs-windows-project-opener: + If you do NOT want to customize your installation process skip to Step 8. -#. Finally, you have made it to the project selection window. - This will be the item you will see when you open Visual Studio. - You do not need to create or open a new project just yet. +#. *Optional*. Choose individual components - .. figure:: figures/vs-windows-installed.png - :scale: 70% - :alt: VS Windows Project Opener + .. admonition:: Note - VS Windows Project Opener + If you are customizing your **Individual components**, make sure that you are installing .NET 6.0 Runtime. + This is a default setting. Do not uncheck the box. + +#. *Optional*. Install language packs -.. admonition:: Note +#. *Optional*. Select installation location + +#. Start developing - If you fail to install one or more of the required packages, you can do - so by closing Visual Studio and running the installer again. Select - *Modify* in the Visual Studio section of the window, and then - select the additional package(s) to install. -.. admonition:: Warning +A Tour of Your New IDE +---------------------- - If you don’t have this most recent version of Visual Studio - installed, you will need to install it via the instructions above. +Microsoft has created a `walkthrough `_ of the Visual Studio 2022. +We recommend you read through this to learn the location of key components within your new IDE. - If you have a pre-existing Visual Studio install, you may need to - install the .NET Core Tools package. To do so, follow the `instructions - provided by - Microsoft `__. +Visual Studio Extensions +------------------------ +Extensions can help make your workflow smoother. +These are usually add-ons that you can add or remove from your IDE as you grow in your coding skills. Connect to GitHub for Windows Users ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Visit this page to download and install the `GitHub Extension for Visual -Studio `__. +In this course, we will continue to use GitHub and GitHub Classroom for code storage. +Visual Studio has an extension for making it easier to connect with GitHub. +Visit this page to download and install the `GitHub Extension for Visual Studio `_. + +Troubleshooting Your Install +---------------------------- + +Missing or Wrong Components? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +If you realize (or worry) that you did not install Visual Studio correctly, +the `Modify Visual Studio Guide `_ +can help you make any needed modifications. This includes changing your workloads or individual components. +Already have Visual Studio on Your Computer? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +If you don’t have this most recent version of Visual Studio installed, you will need to updated it. +The `Update Visual Studio Guide `_ can help you update your old version of VS to the latest. +At the time of this writing, the current version for the course is 2022. +Updating can also help you keep any of your workloads, extensions, or other installed packages up to date. \ No newline at end of file diff --git a/src/conf.py b/src/conf.py index b892fe36..80216bd3 100644 --- a/src/conf.py +++ b/src/conf.py @@ -68,7 +68,7 @@ # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. -language = None +language = 'en' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. From 634c16097f7aa9965556e09c551ec8c25b06603a Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Fri, 7 Oct 2022 12:17:22 -0500 Subject: [PATCH 02/15] updated chapter wording and cyu --- src/chapters/introduction-and-setup/setup.rst | 9 +++++---- src/chapters/introduction-and-setup/why-csharp.rst | 5 +++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/chapters/introduction-and-setup/setup.rst b/src/chapters/introduction-and-setup/setup.rst index f7819c64..054a9e3a 100644 --- a/src/chapters/introduction-and-setup/setup.rst +++ b/src/chapters/introduction-and-setup/setup.rst @@ -88,17 +88,18 @@ Check Your Understanding ------------------------ .. admonition:: Question - - True/False: .NET Core is the MacOS version of .NET Framework + + Visual Studio is a framework. #. True #. False -.. ans: False, while .NET Core can operate in MacOS, it is not specific to that operating system +.. ans: False, Visual Studio is an IDE. The .NET and ASP.NET Core are frameworks that we use inside Visual Studio. .. admonition:: Question - .NET Core contains: + .NET contains: + (Select all that apply) #. A C# compiler #. A virtual machine diff --git a/src/chapters/introduction-and-setup/why-csharp.rst b/src/chapters/introduction-and-setup/why-csharp.rst index 1c3bd107..6fa4c7f3 100644 --- a/src/chapters/introduction-and-setup/why-csharp.rst +++ b/src/chapters/introduction-and-setup/why-csharp.rst @@ -5,10 +5,11 @@ Why Learn C#? This course is an introduction to **C#** and the .NET framework. C# is a programming language developed by Microsoft and used in almost all of its products. + This course is designed for learners who are already familiar with at least one programming language. Thus, we'll move quickly through the syntax rules and procedural basics of the language (ie, how does one write a ``for`` loop in C#? a -conditional statement?). +conditional statement? Etc.). As you've likely heard before, once you grasp the fundamentals of programming in one language, learning another becomes much easier. Professional software @@ -20,6 +21,6 @@ it's wise to start learning new ones early on in your career. Beyond the basics of programming in C#, you'll learn some key *object oriented* concepts to enhance the capabilities of your programs. You'll also download a program called **Visual Studio IDE** to get familiar with the tools of the C# developer. -In the final lessons of this course, you will use a C# framework called **.NET Core MVC**. +In the final lessons of this course, you will use a C# framework called **ASP.NET Core MVC**. This framework gives us the scaffolding necessary to create *MVC* programs (another concept we'll cover) effectively and efficiently. From b484ca1763062029dc679a78238fea4fdf79551e Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Fri, 7 Oct 2022 13:54:47 -0500 Subject: [PATCH 03/15] mvc project creation updated --- .../controllers-simple.rst | 8 +- src/chapters/aspdotnet-intro/initialize.rst | 85 +++++++++---------- src/conf.py | 2 +- 3 files changed, 50 insertions(+), 45 deletions(-) diff --git a/src/chapters/aspdotnet-controllers-and-routes/controllers-simple.rst b/src/chapters/aspdotnet-controllers-and-routes/controllers-simple.rst index 94a2274c..7f5195f5 100644 --- a/src/chapters/aspdotnet-controllers-and-routes/controllers-simple.rst +++ b/src/chapters/aspdotnet-controllers-and-routes/controllers-simple.rst @@ -31,9 +31,15 @@ Controllers and Static Responses - Video .. admonition:: Note - If you ever want to verify what code you started this video with, the `starter code `__ for this video is on the ``master`` branch. + If you ever want to verify what code you started this video with, the `starter code `__ for this video is on the ``main`` branch. If you ever want to verify what code you end this video with, the `final code `__ for this video is on the ``static-responses`` branch. + If you are exploring the starter code and are not able to build a website by using the "Run" button in Visual Studio, + try the following in your terminal: + + * Using the terminal, navigate into your project + * Enter the command: ``dotnet run`` and follow the instructions + .. admonition:: Tip **Windows Users**: You might need to change some solution settings if you pull down this demo repository and run it on your computer. diff --git a/src/chapters/aspdotnet-intro/initialize.rst b/src/chapters/aspdotnet-intro/initialize.rst index 1e94c2a1..734c4a89 100644 --- a/src/chapters/aspdotnet-intro/initialize.rst +++ b/src/chapters/aspdotnet-intro/initialize.rst @@ -2,7 +2,8 @@ Create a New ASP.NET Project ============================ ASP.NET is a framework in the .NET Core family that is used to build web applications. -While `ASP.NET `_ can be used to build a wide variety of web applications, we will be focusing on using it to build MVC web applications. +While `ASP.NET `_ can be used to build a wide variety of web applications, +we will be focusing on using it to build MVC web applications. .. _initialize-aspdotnet-project: @@ -11,72 +12,71 @@ Getting Started To create a new ASP.NET MVC project, start a new project in Visual Studio. -**Windows Users:** +Windows Users +^^^^^^^^^^^^^ #. Use the **Get started** Menu to **Create a new project**. - - .. figure:: figures/WindowsNewProjectPage0.png - :alt: User selects "Create a new project". - - User selects "Create a new project". - - #. When selecting the type of project, select **ASP.NET Core Web App (Model-View-Controller)**. There are 2 ways to find this easily: - A. Select "Web" from the dropdown menu. - B. Use the search bar. + A. Use the search bar. + B. Select "Web" from the dropdown menu. Once you have your project type, click *Next*. +#. Name your project ``HelloASPDotNET`` and put it in the appropriate directory for all of your classwork. + Hit Next. +#. Select the Framework. We are going to use *.NET Core 6.0*. + You do not need to adjust any other options at this point. Select Create! +#. Visual Studio creates a fully-functional web application for you. - .. figure:: figures/WindowsNewProjectPage1.png - :alt: User selects "ASP.NET Core Web App (Model-View-Controller)" by using option A's dropdown menu. - - User selects "ASP.NET Core Web App (Model-View-Controller)" by using option A's dropdown menu. - -#. Name your project ``HelloASPDotNET`` and put it in the appropriate directory for all of your classwork. Hit Next. - - .. figure:: figures/WindowsNewProjectPage2.png - :alt: User names project and selects location for repo. +Troubleshooting + This `tutorial for Windows `_ + can help you if you are stuck. - User names project and selects location for repo. +Mac Users +^^^^^^^^^ -#. Select the Framework. We are going to use *.NET Core 3.1 (Long-term support)*. - We are using this version because it is stable for creating the projects in this textbook. - You do not need to adjust any other options at this point. Select Create! +#. Open Visual Studio for Mac and select a **New** +#. The type of project is a **Web Application (Model-View-Controller)**. + In the left-side menu, select **App** from under the **Web and Console** list. + Continue on to the next screen. +#. Target Framework will be ``.NET 6.0``. You don't need to adjust any other settings at this time. +#. Name your project ``HelloASPDotNET`` and put it in the appropriate directory for all of your classwork. + Hit Next. +#. Visual Studio creates a fully-functional web application for you. - .. figure:: figures/WindowsNewProjectPage3.png - :alt: User selects ".NET Core 3.1 (Long-term support)". +Troubleshooting + Microsoft created a tutorial for creating an MVC in Visual Studio, but for the Mac version they recommend the following `guide `_. +.. admonition:: Note + + The guide is working with ``.NET 5.0`` which is no longer supported. Make you that you are using ``.NET 6.0``. -**All Users:** +All Users +^^^^^^^^^ -#. Visual Studio creates a fully-functional web application for you. #. Now launch the application! - a. **Mac Users**: Click *Run*. + a. **Mac Users**: Click *Run*. It is a button that looks like a triangle pointing to the right. b. **Windows Users**: Try clicking *IIS Express* first. If this results in an ``HTTP Error 500.0``, use the dropdown arrow next to *IIS Express*. Select ``HelloAspDotNet`` (or whatever you named your project) and try launching the application again. - .. figure:: figures/iis-alternative.png - :alt: Arrow points to HelloAspDotNet in a dropdown menu. - - Select ``HelloAspDotNet`` as an alternative. +#. Eventually, your browser will open and display your application. + Take note of the port number in the address bar. -#. Eventually, your browser will open and display your application. Take note of - the port number in the address bar. - - .. figure:: figures/portnumber.png - :alt: Arrow points to URL indicating port number is 5001. - - Taking note of the port number used by the server +Troubleshooting + Refer to the guides mentioned above .. admonition:: Note The home page of your application already contains a link to a tutorial from Microsoft on how to use ASP.NET MVC. - If you want extra study materials, check out that `tutorial `_ from the home page Microsoft designed! + If you want extra study materials, check out + that `tutorial `_ from the home page Microsoft designed! + +Explore the Code +---------------- In the ``Controllers`` directory, check out ``HomeController.cs``. Microsoft provided the code in ``HomeController`` and that is why our application ran immediately after we created it and was full of content. @@ -87,7 +87,7 @@ As we work on our new application, we will be adding a new controller, ``HelloCo As you code along with the videos, you will be working on your own project. However, should you want to review a step or double-check your code, fork LaunchCode's ``HelloASPDotNETDemo`` repository to see what the code looked like at each stage. The repository is up on `Github `_. - The ``master`` branch contains the code after creation and also shows the starting point for the next chapter. + The ``main`` branch contains the code after creation and also shows the starting point for the next chapter. Check Your Understanding ------------------------ @@ -97,7 +97,6 @@ Check Your Understanding True/False: You should take note of the port number the server is using to run your application. a. True - b. False .. ans: True! It may not run at 5001 diff --git a/src/conf.py b/src/conf.py index b892fe36..80216bd3 100644 --- a/src/conf.py +++ b/src/conf.py @@ -68,7 +68,7 @@ # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. -language = None +language = 'en' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. From 0fb6c180ee8644953aa7b17a59b8942c1b3c3004 Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Fri, 7 Oct 2022 15:53:56 -0500 Subject: [PATCH 04/15] notes for dotnet 6.0 added --- .../controllers-simple.rst | 51 +++++++++++++------ 1 file changed, 36 insertions(+), 15 deletions(-) diff --git a/src/chapters/aspdotnet-controllers-and-routes/controllers-simple.rst b/src/chapters/aspdotnet-controllers-and-routes/controllers-simple.rst index 7f5195f5..2b5b75d2 100644 --- a/src/chapters/aspdotnet-controllers-and-routes/controllers-simple.rst +++ b/src/chapters/aspdotnet-controllers-and-routes/controllers-simple.rst @@ -3,6 +3,13 @@ Simple Controllers ================== +.. admonition:: Warning + + Many changes have happened in the world of Visual Studio and ASP.NET since the writing of this book. + We reviewed the videos and instructions in the latest environment and framework and made notes to help you through any discrepancies. + If you get stuck following along with a video, we suggest comparing the written instructions for the problematic area. + Notes have been added to the reading that will help you locate or code what is needed to complete each chapter project. + The first of the MVC elements we'll work on implementing are the controllers. Recall that controllers are like the traffic cops of our application. They handle the requests made from users interacting with the application's view and update model data accordingly. Conversely, changes to model data are sent to the view @@ -37,8 +44,8 @@ Controllers and Static Responses - Video If you are exploring the starter code and are not able to build a website by using the "Run" button in Visual Studio, try the following in your terminal: - * Using the terminal, navigate into your project - * Enter the command: ``dotnet run`` and follow the instructions + #. Using the terminal, navigate into your project + #. Enter the command: ``dotnet run`` and follow the prompts in your terminal .. admonition:: Tip @@ -58,7 +65,8 @@ Some tools may depend on us following the convention of the MVC design pattern, If you want to change something about the provided structure, be sure to double check the documentation to make sure a tool does not depend on you following it! To designate a given class as a controller within the ASP.NET framework, we extend the ``Controller`` class. -The `Controller class `__ provides us with the necessary members and methods to manage traffic between the three components in our MVC application. +The `Controller class `_ +provides us with the necessary members and methods to manage traffic between the three components in our MVC application. .. sourcecode:: csharp @@ -79,10 +87,22 @@ ASP.NET MVC has two different ways to map these routes: conventional routing and **Conventional routing** establishes the routes as endpoints in one of the application's configuration files. **Attribute routing** establishes the routes using :ref:`C# attributes ` that are placed in the controller file. -Routes in conventional routing are setup via endpoints in a configuration file called ``Startup.cs``. +Routes in conventional routing are setup via endpoints in a configuration file called ``Program.cs``. When an HTTP request comes in, routing matches the request with an endpoint. **Endpoints** designate the controller action that executes when the appropriate HTTP request comes into the application. +.. admonition:: Note on the Startup.cs file + + ASP.NET 6.0 combines the ``Program.cs`` and ``Startup.cs`` files. + If you are following along with Sally's video, you will see the files are separated. She is using ASP.NET 3.1 in her video. + This discrepancy between ASP.NET frameworks should not affect this project. + + If you started your project on your own in .NET 6.0, we recommend exploring `Sally's repo `_ + and see if you can identify where and how these two files were combined. + + This `documentation `_ + illustrates some of the changes between .NET 5.0 and .NET 6.0. + When we created a new ASP.NET application, without adding any code, we were immediately able to run it. This is because the MVC application we start out with already has the routing and endpoints set up. When we open the application, we see in the ``Controllers`` directory that Microsoft has a preconfigured ``HomeController``. @@ -101,12 +121,15 @@ If we added a new method, ``Hello()``, to the ``HomeController``, we would see t .. admonition:: Note Throughout this book, we will be using attribute routing to break the pattern established by conventional routing. - However, if you want to investigate further on how to use an endpoint for a rule-breaking route in conventional routing, Microsoft has a great `article `_ on the subject. - For example, endpoints preconfigured in ``Startup.cs`` is how we can navigate to ``localhost:5001`` and ``localhost:5001/Home/Index`` to see the same page. + However, if you want to investigate further on how to use an endpoint for a rule-breaking route in conventional routing, + Microsoft has a great `article `_ on the subject. + For example, endpoints preconfigured in ``Program.cs`` is how we can navigate to ``localhost:5001`` and ``localhost:5001/Home/Index`` to see the same page. + + **Remember:** ``Program.cs`` contain the endpoints in an ASP.NET 6.0 application. -When adding a new controller, such as ``HelloController``, we need to make sure that routing is properly configured whether we use conventional routing or attribute routing. -We want to start by adding a new action method to ``HelloController``. -**Action methods** are the public methods in a controller class. +When adding a new controller, such as ``HelloController``, we need to make sure that routing is properly configured whether +we use conventional routing or attribute routing. +We want to start by adding a new action method to ``HelloController``. **Action methods** are the public methods in a controller class. Action methods respond at a specific route and that response can be an update to a view, sending new data to a model, returning some simple HTML, and so on. When we are creating a new action method, we want to think about what route the method needs to respond at, what request type the action method should respond to, and what that response entails. Let's start by adding the following ``Index()`` method: @@ -136,12 +159,10 @@ We also want to make use of attribute routing in our new ``HelloController``. To do so, we can add attributes to our ``Index()`` method. As you may recall from the :ref:`chapter ` on unit testing, attributes in C# lie somewhere between code and comments. While an attribute cannot change the code inside the method or class, an attribute in attribute routing does supply critical information about routes and request types. -Attribute routing is powerful because it does not depend on any endpoint mapping info in ``Startup.cs``, can defy the pattern established by conventional routing, and specify one request type for a method to respond to. - -.. admonition:: Note - - ASP.NET has many different attributes that we can use in our controllers. - For a more in-depth catalog of different attributes, check out the `documentation `__. +Attribute routing is powerful because it does not depend on any endpoint mapping info in ``Program.cs``, can defy the pattern established by conventional routing, and specify one request type for a method to respond to. + +ASP.NET has many different attributes that we can use in our controllers. +For a more in-depth catalog of different attributes, check out the `documentation `__. .. index:: ! [HttpGet], ! [HttpPost], ! [Route("path")] From 3c036168f9c9cdfa9c77365f8967131911866865 Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Thu, 13 Oct 2022 17:26:28 -0500 Subject: [PATCH 05/15] links to documentation and wording updated --- src/chapters/exceptions/common-exceptions.rst | 2 +- src/chapters/exceptions/exercises.rst | 4 +- src/chapters/vstools/debugger.rst | 29 ++++++------- src/chapters/vstools/msbuild.rst | 37 +++++++++------- src/chapters/vstools/nuget.rst | 43 +++++++++---------- 5 files changed, 57 insertions(+), 58 deletions(-) diff --git a/src/chapters/exceptions/common-exceptions.rst b/src/chapters/exceptions/common-exceptions.rst index 80244ff1..c94cfd54 100644 --- a/src/chapters/exceptions/common-exceptions.rst +++ b/src/chapters/exceptions/common-exceptions.rst @@ -12,7 +12,7 @@ extend the ``System.Exception`` class. `here `__. The examples in this table are excerpted from -`this page `__, +`this page `__, where you can find several other commonly used exception types. .. list-table:: Common Exception Types in C# diff --git a/src/chapters/exceptions/exercises.rst b/src/chapters/exceptions/exercises.rst index bb81cf50..0ae4e4ab 100644 --- a/src/chapters/exceptions/exercises.rst +++ b/src/chapters/exceptions/exercises.rst @@ -1,7 +1,9 @@ Exercises: Exceptions ===================== -To get started, fork and clone this `repo `_ from Github. +To get started, fork and clone this `repo `_ from Github. + +You will be working in the **ExceptionExercises** directory of the repository. Divide By Zero! --------------- diff --git a/src/chapters/vstools/debugger.rst b/src/chapters/vstools/debugger.rst index e56eb3f4..100ff15b 100644 --- a/src/chapters/vstools/debugger.rst +++ b/src/chapters/vstools/debugger.rst @@ -1,9 +1,8 @@ Debugger ======== - + Watch this video to learn the basics of the debugging tools available in Visual Studio. If you want -to follow along, Chris is debugging the :ref:`hello-methods` program back in the introduction to -data types. +to follow along, Chris is debugging the :ref:`hello-methods` program back in the introduction to data types. .. youtube:: :video_id: sACkw915kmg @@ -11,17 +10,17 @@ data types. A summary of Chris's debugger tips: -- Right click in the text editing window to add a breakpoint to your code. +- Right click in the text editing window to add a `breakpoint `_ to your code. - Start debug mode with the run button as you might normally run your program. - Debugger Panes: - - *Autos* pane shows the values of parameters and variables on the line that the debugger is + - `Autos `_ pane shows the values of parameters and variables on the line that the debugger is currently sitting on, as well as the line above. - - *Locals* pane shows the value of local variables and parameters within the program being debugged. - - Add variables, parameters, and expressions to the *Watch* pane to monitor their values while debugging. - - *Call Stack* pane displays the record of the methods that have been called in the program being debugged. + - `Locals `_ pane shows the value of local variables and parameters within the program being debugged. + - Add variables, parameters, and expressions to the `Watch `_ pane to monitor their values while debugging. + - `Call Stack `_ pane displays the record of the methods that have been called in the program being debugged. - View a list of breakpoints in the *Breakpoints* pane. You may also disable and enable breakpoints from here. -- Debugger Buttons: - - *Step over* button moves debugger to the next line to be executed within a method. +- Debugger `Code Stepping `_ Buttons: + - `Step over `_ button moves debugger to the next line to be executed within a method. - *Step out* button brings the debugger out of the execution of a method. - *Step into* button makes the debugger enter the method at which it is currently paused. Note that you can't step into ``System`` defined methods, only those defined by your program. @@ -40,6 +39,7 @@ A summary of Chris's debugger tips: - To add conditions to a breakpoint, right click on the breakpoint and select *Edit Breakpoint*. From menu that opens, use the *Advanced Conditions* section to set your conditions for when you want the breakpoint to be executed. + - For more information on using the Debugger in Visual Studio for Mac, check out this `guide `_. Check Your Understanding @@ -47,11 +47,9 @@ Check Your Understanding .. admonition:: Question - True/False: Breakpoints on ``Console.WriteLine()`` are helpful because - stepping into them reveals what is printed in the console. + Breakpoints on ``Console.WriteLine()`` are helpful because stepping into them reveals what is printed in the console. a. True - b. False .. ans: False, The Visual Studio debugger tool does not allow us to step into ``Console.WriteLine()`` methods or any method defined by ``System``. @@ -61,11 +59,8 @@ Check Your Understanding Define a *breakpoint*. a. A point in our code where the debugger will stop running and provide information about the current state. - - b. A point in our code that we anticipate will result in an exception or error. - + b. A point in our code that we anticipate will result in an exception or error. c. A point in our code where we include a print statement to see what's going on. - d. A point in our code where we want to throw the computer out of a window because nothing works. .. ans; a, A point in our code where the debugger will stop running and provide information about the current state. diff --git a/src/chapters/vstools/msbuild.rst b/src/chapters/vstools/msbuild.rst index c4a62ee3..e1f85076 100644 --- a/src/chapters/vstools/msbuild.rst +++ b/src/chapters/vstools/msbuild.rst @@ -8,8 +8,7 @@ file type. It contains instructions on how to build the project. Visual Studio i Microsoft program called **MSBuild**. MSBuild creates the code to build your application so that it can be run. -An **automated build tool**, such as -MSBuild, is responsible for tasks like: +An **automated build tool**, such as MSBuild, is responsible for tasks like: - Compiling the source code - Managing dependencies @@ -20,6 +19,8 @@ MSBuild is included in the Visual Studio IDE and has so far been doing its work Other build tools are available for us to use in C# projects. However, like in the unit testing chapter, we will stick to the tools provided to us with the Visual Studio IDE. +For more on MSBuild, check out the `documentation `_. + .. index:: ! XML , ! Extensible Markup Language, ! MSBuild tasks, ! MSBuild targets, ! MSBuild properties, ! MSBuild items The Project File @@ -40,14 +41,16 @@ The four principal elements of a project file are: So far, in our simple projects, there is not much complexity in what MSBuild and the ``.csproj`` file need to do. Our C# code is designed to be tested and executed within the IDE with very few dependencies. When you are working as a C# developer on the job, things will start to get more -complicated. You will likely need at least three target environments for your -application: +complicated. You will likely need at least three target environments for your application: a. debugging in the IDE. b. a development server for testing your deployed program before it is released to the user. c. the final production environment. -You will also probably have a number of dependencies. These will have different responsibilities in those different environments. So while we don't do much with the project file yet, we will later on. +The ``.csproj`` file is where any project dependencies are stored and also organized. +These will have different responsibilities in those different environments. +So while we don't do much with the project file yet, we will later on. + The four elements summarized above provide the details needed to manage larger projects. To view a project file, right click on the project’s name in the Visual Studio file menu. From the dropdown menu, select *Edit Project File*. @@ -58,27 +61,32 @@ To view a project file, right click on the project’s name in the Visual Studio User selecting "Edit Project File". +.. admonition:: Note + + At the time of writing, the version of .NET Core used is 6.0. If that is no longer the most recent version, make note. + Barring any major updates to the framework, the following explanation still applies. + Most of our project files from this class will look like this: .. sourcecode:: XML + Exe - netcoreapp3.1 + net6.0 + -.. admonition:: Note - At the time of writing, the version of .NET Core used is 3.1. If that is no longer the most - recent version, make note. Barring any major updates to the framework, the following - explanation still applies. +This project example contains two property elements: ``OutputType`` and ``TargetFramework``. + +- ```` specifies the format of the build's output. ``OutputType`` is the key, and ``Exe`` is the value. This build outputs an ``.exe`` file. +- ```` provides the version of .NET Core that the program uses. -This project contains two property elements: ``OutputType`` and ``TargetFramework``. ```` specifies the format of -the build's output. ``OutputType`` is the key, and ``Exe`` is the value. This build outputs an ``.exe`` file. ```` -provides the version of .NET Core that the program uses. Both of these properties are wrapped in a ```` element. In +Both of these properties are wrapped in a ```` element. In fact, all property elements must be nested within a ```` tag. Finally, ```` is a special element that forms the base of all project files. @@ -91,11 +99,8 @@ Check Your Understanding What is the language of the C# project file? a. MSBuild - b. C# - c. csproj - d. XML .. ans: d, xml diff --git a/src/chapters/vstools/nuget.rst b/src/chapters/vstools/nuget.rst index 30d9f608..4cb0a3b6 100644 --- a/src/chapters/vstools/nuget.rst +++ b/src/chapters/vstools/nuget.rst @@ -3,34 +3,35 @@ NuGet .. index:: ! NuGet -**NuGet** is a package management tool for .NET software. To use a dependency in a C# project, -we can rely on NuGet to connect us with third-party code. NuGet allows us to bypass downloading -and hosting the dependency library ourselves. +**NuGet** is a package management tool for .NET software. +NuGet allows you to use external code sources without including the codebase itself. You can make +use of compiled libraries that other developers have already built. You can choose to use a +specific version of a package hosted by NuGet, and update that version as need be. + As with MSBuild, we will only scratch the surface of the utility of a .NET package manager. That -said, it is still a good idea to get familiar with these tools. As your programs grow larger, +said, it is still a good idea to get `familiar with these tools `_. As your programs grow larger, MSBuild and NuGet will help to maintain a robust codebase. NuGet packages are readily available within the IDE itself. Perhaps you have noticed the -*Dependencies* directory that is created in our projects? To browse available packages, right -click on that directory. From there, select “Manage NuGet Packages” from the dropdown menu: +*Dependencies* directory that is created in our projects? -.. figure:: figures/manage-nuget-packages.png - :scale: 50% - :alt: User selecting "Manage NuGet Packages" from dependencies dropdown menu +To browse available NuGet packages: - User selecting "Manage NuGet Packages". +#. Right-click on that directory +#. Select “Manage NuGet Packages” from the dropdown menu +#. The resulting window will show you a catalog of software packages you may add to your project -The resulting window shows a catalog of software packages you may add to your project. +Managing NuGet Packages +^^^^^^^^^^^^^^^^^^^^^^^ + +The following documentation can help you become more familiar with downloading and managing NuGet packages. + +**Windows Users:** `Follow this guide `_. + +**Mac Users:** `User this guide `_ -.. figure:: figures/browse-nuget-packages.png - :scale: 50% - :alt: Package browsing view of the NuGet package manager window - Browse available NuGet packages -NuGet allows you to use external code sources without including the codebase itself. You can make -use of compiled libraries that other developers have already built. You can choose to use a -specific version of a package hosted by NuGet, and update that version as need be. Check Your Understanding ------------------------ @@ -40,21 +41,17 @@ Check Your Understanding Select which item best describes the job of NuGet. a. NuGet compiles your C# programs to be deployed in different conditions. - b. NuGet is a marshmallow-like confection found in many candy bars. - c. NuGet is a package manager for .NET programs. - d. NuGet allows you to download dependency library source code into your solution. .. ans: c, NuGet is a package manager for .NET programs. .. admonition:: Question - True/False: NuGet and MSBuild share responsibilities and only one is needed to deploy a C# app. + NuGet and MSBuild share responsibilities and only one is needed to deploy a C# app. a. True - b. False .. ans: False, While NuGet gives you access to the dependencies you need for your application, From ebd03b58fd49c1c4721f3dab7c6745bad5edbcab Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Fri, 14 Oct 2022 14:04:45 -0500 Subject: [PATCH 06/15] updated wording, formatting, and starter code --- src/chapters/razor-views/create-template.rst | 21 +-- src/chapters/razor-views/layout-pages.rst | 22 +-- .../razor-views/template-conditionals.rst | 54 +++--- src/chapters/razor-views/template-forms.rst | 44 ++--- .../razor-views/template-iteration.rst | 167 +++++++++--------- src/chapters/razor-views/using-templates.rst | 12 +- src/chapters/razor-views/why-templates.rst | 60 +++---- 7 files changed, 192 insertions(+), 188 deletions(-) diff --git a/src/chapters/razor-views/create-template.rst b/src/chapters/razor-views/create-template.rst index 2a85ee02..7d30c135 100644 --- a/src/chapters/razor-views/create-template.rst +++ b/src/chapters/razor-views/create-template.rst @@ -87,22 +87,23 @@ string of HTML. In ``Views``, create a new subdirectory called ``Hello``. Within ``Hello`` create a new file of the *Razor View* file template. -**WINDOWS USERS:** Right click on the ``Views`` directory or any subdirectory and select *Add -> New Item*. -Avoid selecting *Add -> View* from your options. +**Windows Users:** + * Right click on the ``Views`` directory or any subdirectory and select *Add -> New Item*. + * The *Razor View - Empty* option is found in the *ASP.NET Core* menu. -**MAC USERS:** Right click on the ``Views`` directory or any subdirectory and select *Add -> New File*. - -**ALL USERS:** In the modal window that appears, look for the item labelled *Razor View*. - -.. figure:: figures/razor-view-template-selection.png - :alt: User selects the Razor View file template. - - Select the *Razor View* file template. +**Mac Users:** + * Right click on the ``Views`` directory or any subdirectory and select *Add -> New File*. + * The *Razor View* option is found in the *ASP.NET Core* menu. +**All Users:** + * Once you have your *Razor View* or *Razor View - Empty* selected, name it ``Index``. + * We are naming our Views after there corresponding action methods. Add the HTML form from the ``Index()`` method to your new template. Once you are done with that, update the ``Index()`` method to return ``View()``. +.. _layout.cshtml: + ``_Layout.cshtml`` ~~~~~~~~~~~~~~~~~~ diff --git a/src/chapters/razor-views/layout-pages.rst b/src/chapters/razor-views/layout-pages.rst index cae4b079..a02d4b39 100644 --- a/src/chapters/razor-views/layout-pages.rst +++ b/src/chapters/razor-views/layout-pages.rst @@ -1,7 +1,7 @@ The Shared Directory ==================== -Earlier in the lesson, we touched upon the role of ``_Layout.cshtml``. When we +:ref:`Earlier in the lesson `, we touched upon the role of ``_Layout.cshtml``. When we set ``Layout`` to ``null``, the header, footer, and Bootstrap disappear from our site and we are left with static HTML. ``_Layout`` is in the ``Shared`` directory of the ``Views`` directory. Files inside this ``Shared`` directory @@ -33,9 +33,9 @@ Let's assume that you want to add the same set of links to multiple pages within .. sourcecode:: HTML :linenos: - LaunchCode
- Play Well
- Other Building Blocks + LaunchCode
+ Play Well
+ Other Building Blocks Instead of pasting this code into every template, we will store the HTML in a separate file. @@ -64,11 +64,11 @@ Now let's see how to pull a partial view into a template: .. sourcecode:: HTML :linenos: - + + + - - - + When the code runs, the ``name`` attribute in the ```` tag helper gives the path to the partial view. In the example above, the partial view is named ``_LinkListPartial.cshtml`` and is in the ``Shared`` folder in the ``Views`` directory. @@ -84,9 +84,9 @@ Check Your Understanding .. sourcecode:: HTML :linenos: - LaunchCode
- Play Well
- Other Building Blocks + LaunchCode
+ Play Well
+ Other Building Blocks Which of the following would place the partial view inside a ``
`` element in the template? diff --git a/src/chapters/razor-views/template-conditionals.rst b/src/chapters/razor-views/template-conditionals.rst index e4bab3c3..8e3c4460 100644 --- a/src/chapters/razor-views/template-conditionals.rst +++ b/src/chapters/razor-views/template-conditionals.rst @@ -39,18 +39,18 @@ Let's look at an example: .. sourcecode:: guess :linenos: - @if (ViewBag.userSelection == "Instant") - { -

Are you sure about that?

- } - else if (ViewBag.userSelection == "French Roast") - { -

Oooh la la!

- } - else - { -

Thanks for your order

- } + @if (ViewBag.userSelection == "Instant") + { +

Are you sure about that?

+ } + else if (ViewBag.userSelection == "French Roast") + { +

Oooh la la!

+ } + else + { +

Thanks for your order

+ } The ``@if`` statement in line 1 compares a user's brew choice to the string ``"Instant"``. If they match, then Razor adds the paragraph element to the @@ -78,15 +78,15 @@ Just as we can nest loops, we can nest any C# in Razor for advanced control flow .. sourcecode:: guess :linenos: - @if (ViewBag.coffeeOptions.Count > 1) - { -
    - @foreach(string coffeeType in ViewBag.coffeeOptions) - { -
  1. @coffeeType
  2. - } -
- } + @if (ViewBag.coffeeOptions.Count > 1) + { +
    + @foreach(string coffeeType in ViewBag.coffeeOptions) + { +
  1. @coffeeType
  2. + } +
+ } The conditional in line 1 checks that ``coffeeOptions`` contains more than one @@ -136,12 +136,12 @@ the values in an unordered list. .. sourcecode:: html :linenos: -
    - @foreach(int number in ViewBag.numbers) - { -
  • @number
  • - } -
+
    + @foreach(int number in ViewBag.numbers) + { +
  • @number
  • + } +
.. admonition:: Question diff --git a/src/chapters/razor-views/template-forms.rst b/src/chapters/razor-views/template-forms.rst index 0c6510df..fe24dbdc 100644 --- a/src/chapters/razor-views/template-forms.rst +++ b/src/chapters/razor-views/template-forms.rst @@ -39,7 +39,7 @@ CodingEvents Setup - Text #. Within the action method, create an empty list and add a few event names to it. #. Add the list to ``ViewBag``. Then return the corresponding view. #. Within the ``Views`` directory, create a new directory named ``Events``. Within this directory, create a new view named ``Index.cshtml``. -#. Within the new template, loop over the list and display the name of each event. +#. Within the new template, loop over the list and display the name of each event. Make sure your template can handle an empty List. Create and Render a Form - Video -------------------------------- @@ -61,14 +61,14 @@ The method for the form should be of type ``post``. .. sourcecode:: html :linenos: - + -
- - -
+
+ + +
- + You can include as many inputs as you need in the form, and these can be of different types (e.g. text, email, checkbox, etc.). However, each different @@ -79,13 +79,13 @@ To *render* the form in the view, add a method to the controller with an ``[Http .. sourcecode:: csharp :lineno-start: 26 - [HttpGet] - public IActionResult Add() - { - // Any additional method code here + [HttpGet] + public IActionResult Add() + { + // Any additional method code here - return View(); - } + return View(); + } .. admonition:: Note @@ -118,22 +118,22 @@ a method to the controller using the ``[HttpPost]`` annotation: .. sourcecode:: csharp :lineno-start: 31 - [HttpPost] - [Route("/Events/Add")] - public IActionResult NewEvent(string name) - { - // Method code... + [HttpPost] + [Route("/Events/Add")] + public IActionResult NewEvent(string name) + { + // Method code... - return Redirect("/Events"); - } + return Redirect("/Events"); + } Some points to note: -#. Line 2: For each piece of data that needs to be retrieved from the form, +#. **Line 2:** For each piece of data that needs to be retrieved from the form, declare a parameter of the appropriate type. #. The method code performs any data manipulation required after the information gets submitted. -#. Line 6: We may want to send the user to a different page after they +#. **Line 6:** We may want to send the user to a different page after they successfully submit a form. Instead of re-rendering the form, we want to use ``Redirect()`` to *redirect* the user to a different template. diff --git a/src/chapters/razor-views/template-iteration.rst b/src/chapters/razor-views/template-iteration.rst index 3251d117..e54b228c 100644 --- a/src/chapters/razor-views/template-iteration.rst +++ b/src/chapters/razor-views/template-iteration.rst @@ -9,12 +9,12 @@ hard-coded coffee options in a list. .. sourcecode:: html :linenos: -
    -
  1. French Roast
  2. -
  3. Espresso
  4. -
  5. Kopi Luwak
  6. -
  7. Instant
  8. -
+
    +
  1. French Roast
  2. +
  3. Espresso
  4. +
  5. Kopi Luwak
  6. +
  7. Instant
  8. +
If we want to add, remove, or edit the list items, we need to go in and change the individual tags, which is a poor use of our time. Fortunately, there is a @@ -37,12 +37,12 @@ collection. .. sourcecode:: guess :linenos: -
    - @foreach (type collectionItem in ViewBag.collectionProperty) - { -
  1. @collectionItem
  2. - } -
+
    + @foreach (type collectionItem in ViewBag.collectionProperty) + { +
  1. @collectionItem
  2. + } +
#. The ``@foreach`` loop is initiated inside of a list element (either ``
    `` or ``
      ``). #. ``ViewBag.collectionProperty`` represents any collection that has been assigned as a property on ``ViewBag``. @@ -59,12 +59,12 @@ the coffee names as strings in a ``List`` called ``ViewBag.coffeeOptions``. .. sourcecode:: guess :linenos: -
        - @foreach (string coffeeType in ViewBag.coffeeOptions) - { -
      1. @coffeeType
      2. - } -
      +
        + @foreach (string coffeeType in ViewBag.coffeeOptions) + { +
      1. @coffeeType
      2. + } +
      Some points to note: @@ -89,15 +89,15 @@ Some points to note: .. sourcecode:: guess :linenos: -
      -

      Coffee Types

      - @foreach (string coffeeType in ViewBag.coffeeTypes) - { -
        -
      1. @coffeeType
      2. -
      - } -
      +
      +

      Coffee Types

      + @foreach (string coffeeType in ViewBag.coffeeTypes) + { +
        +
      1. @coffeeType
      2. +
      + } +
      The final HTML produced is one heading, 4 ordered lists, and 4 coffee names. When this view is rendered, each coffee type is labelled with "1". @@ -105,21 +105,24 @@ Some points to note: .. sourcecode:: html :linenos: -
      -

      Coffee Types

      -
        -
      1. French Roast
      2. -
      -
        -
      1. Espresso
      2. -
      -
        -
      1. Kopi Luwak
      2. -
      -
        -
      1. Instant
      2. -
      -
      +
      +

      Coffee Types

      +
        +
      1. French Roast
      2. +
      + +
        +
      1. Espresso
      2. +
      + +
        +
      1. Kopi Luwak
      2. +
      + +
        +
      1. Instant
      2. +
      +
      .. index:: ! var @@ -139,35 +142,35 @@ Sample Razor template: .. sourcecode:: html :linenos: - @foreach (var coffeeShop in ViewBag.coffeeShops) - { - @*Each shop name*@ -

      @coffeeShop.Name

      -
        - @foreach(string coffeeType in coffeeShop.CoffeeOptions) - { - @*Each coffee type available*@ -
      • @coffeeType
      • - } -
      - } + @foreach (var coffeeShop in ViewBag.coffeeShops) + { + @*Each shop name*@ +

      @coffeeShop.Name

      +
        + @foreach(string coffeeType in coffeeShop.CoffeeOptions) + { + @*Each coffee type available*@ +
      • @coffeeType
      • + } +
      + } Sample HTML output: .. sourcecode:: html :linenos: -

      Central Perk

      -
        -
      • Espresso
      • -
      • Instant
      • -
      +

      Central Perk

      +
        +
      • Espresso
      • +
      • Instant
      • +
      -

      Brews Brothers

      -
        -
      • French Roast
      • -
      • Kopi Luwak
      • -
      +

      Brews Brothers

      +
        +
      • French Roast
      • +
      • Kopi Luwak
      • +
      Apart from the nested loops displayed above, here are some other items you may find useful @@ -217,15 +220,15 @@ Check Your Understanding .. sourcecode:: guess :linenos: -
      -

      Coffee Types

      -
        - @foreach (string coffeeType in ViewBag.coffeeTypes) - { -
      1. @coffeeType
      2. - } -
      -
      +
      +

      Coffee Types

      +
        + @foreach (string coffeeType in ViewBag.coffeeTypes) + { +
      1. @coffeeType
      2. + } +
      +
      #. One heading, 4 ordered lists, and 4 coffee names (each name labeled as “1”)? #. One heading, one ordered list, and 4 coffee names (with the names labeled "1", "2", "3"…)? @@ -241,15 +244,15 @@ Check Your Understanding .. sourcecode:: guess :linenos: - @foreach (string coffeeType in ViewBag.coffeeTypes) - { -
      -

      Coffee Types

      -
        -
      1. @coffeeType
      2. -
      -
      - } + @foreach (string coffeeType in ViewBag.coffeeTypes) + { +
      +

      Coffee Types

      +
        +
      1. @coffeeType
      2. +
      +
      + } #. One heading, 4 ordered lists, and 4 coffee names (each name labeled as “1”)? #. One heading, one ordered list, and 4 coffee names (with the names labeled "1", "2", "3"…)? diff --git a/src/chapters/razor-views/using-templates.rst b/src/chapters/razor-views/using-templates.rst index 91c52725..5bd6204c 100644 --- a/src/chapters/razor-views/using-templates.rst +++ b/src/chapters/razor-views/using-templates.rst @@ -16,13 +16,13 @@ These methods have a structure similar to: .. sourcecode:: c# :linenos: - public IActionResult ActionMethod() - { - // method code here + public IActionResult ActionMethod() + { + // method code here - ViewBag.property = Data; - return View(); - } + ViewBag.property = Data; + return View(); + } **ViewBag** is an object that passes data into a template. ``Data`` can be a variable of any type, a number, a collection of some sort, or an object. diff --git a/src/chapters/razor-views/why-templates.rst b/src/chapters/razor-views/why-templates.rst index 6d02307c..6a6e8583 100644 --- a/src/chapters/razor-views/why-templates.rst +++ b/src/chapters/razor-views/why-templates.rst @@ -46,23 +46,23 @@ and each ``
    • `` element, in addition to a couple of fun links. The CSS file .. sourcecode:: html :linenos: - -

      Java Types

      -
      -
        -
      1. French Roast
      2. -
      3. Espresso
      4. -
      5. Kopi Luwak
      6. -
      7. Instant
      8. -
      -
      -
      - - + +

      Java Types

      +
      +
        +
      1. French Roast
      2. +
      3. Espresso
      4. +
      5. Kopi Luwak
      6. +
      7. Instant
      8. +
      +
      +
      + + We could drastically improve the appearance and content of the page by playing @@ -81,19 +81,19 @@ hard-coding, since data can change based on a user's actions. .. sourcecode:: bash :linenos: - -

      {templateInstructions}

      -
      -
        -
      • -
      -
      -
      - - + +

      {templateInstructions}

      +
      +
        +
      • +
      +
      +
      + + This HTML looks similar to the previous example, but it replaces some of the From 8931c5a6a299721deca5671f7bb918d33d8c1b96 Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Fri, 14 Oct 2022 14:39:48 -0500 Subject: [PATCH 07/15] versioning note added --- src/chapters/razor-views/template-forms.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/chapters/razor-views/template-forms.rst b/src/chapters/razor-views/template-forms.rst index fe24dbdc..1fb4ebd1 100644 --- a/src/chapters/razor-views/template-forms.rst +++ b/src/chapters/razor-views/template-forms.rst @@ -1,6 +1,13 @@ Razor Forms =========== +.. admonition:: Warning + + Many changes have happened in the world of Visual Studio and ASP.NET since the writing of this book. + We reviewed the videos and instructions in the latest environment and framework and made notes to help you through any discrepancies. + If you get stuck following along with a video, we suggest comparing the written instructions for the problematic area. + Notes have been added to the reading that will help you locate or code what is needed to complete each chapter project. + Already we have seen that templates allow us to build generic forms. Using templates, you can reuse the structure by rendering the same form, but with different labels and data. Thus, a single form can serve different purposes, saving you extra effort. From 657006b37ba4760f604a43376cca0af49c732091 Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Mon, 17 Oct 2022 16:30:30 -0500 Subject: [PATCH 08/15] updated guides for creating and cloning projects --- .../cloning-a-csharp-project.rst | 131 ++++++++++++----- .../creating-a-csharp-project.rst | 137 +++++++----------- 2 files changed, 144 insertions(+), 124 deletions(-) diff --git a/src/chapters/introduction-and-setup/cloning-a-csharp-project.rst b/src/chapters/introduction-and-setup/cloning-a-csharp-project.rst index edcb34ca..3f373f80 100644 --- a/src/chapters/introduction-and-setup/cloning-a-csharp-project.rst +++ b/src/chapters/introduction-and-setup/cloning-a-csharp-project.rst @@ -3,65 +3,120 @@ Cloning a C# Project ==================== -The steps here walk you through setting up a repository that you’ll -use to study example code and work on coding exercises. +Follow along with the provided walkthroughs to learn how to clone repos into Visual Studio. +Try it out on your own by cloning the `LaunchCodeEducation/csharp-web-dev-datatypes `__ +repository page and fork the repository into your own GitHub account by selecting *Fork* from the top right of the page. + -#. Visit the `LaunchCodeEducation/csharp-web-dev-datatypes `__ - repository page and fork the repository into your own GitHub account by - selecting *Fork* from the top right of the page. Windows Users ------------- -#. From within Visual Studio, choose the - *Team Explorer* tab near the bottom of the *Solution Explorer* pane. If - you don’t see this tab, you can open it via the application menu: *View - > Team Explorer*. The first time you do this, you will need to click - *Connect…* and then sign in to GitHub. +`Clone a Git Repository in Visual Studio `_ - .. figure:: ./figures/vs-windows-team-explorer.png - :alt: Visual Studio Team Explorer Connect to GitHub +Note the path where you save this repo. - Visual Studio Team Explorer Connect to GitHub +Mac Users +--------- - .. admonition:: Tip +`Cloning an Existing Repo `_ - If you are currently viewing the - :ref:`project opener pane `, you can - open the editor to access the Team Explorer tab by choosing - "Continue without code ->". +Be sure to note the Target Folder where this repo is saved. -#. Once connected, select *Clone* from the GitHub section of the *Team Explorer* and select - your ``csharp-web-dev-datatypes`` copy from the modal window. **Be sure to - change the Path field** to the location you would like the project to - live, ideally inside of a folder you’ve been using to store other - projects. +Exploring the Cloned Repo in Your Terminal +------------------------------------------ -Mac Users ---------- +Once you have cloned it into Visual Studio, locate the repo using your terminal. -#. With Visual Studio open, select *Version Control > Clone Repository* from the menu bar. +On a Windows machine, it is a path you saved your repo at. On a Mac, it's in the Target Folder. -#. This opens a window to connect to a remote repository. Copy the address for your forked exercises repository - and enter it into the *url* section of the form. The rest of the form fields will auto-populate: +Once you find the repo, ``cd`` into it. +Look for the **Solution** file which uses the ``.sln`` file type. - .. figure:: ./figures/vsmac-checkout-github.png - :alt: Visual Studio for Mac checkout Github repository +.. sourcecode:: - Visual Studio for Mac checkout Github repository + students-computer:csharp-web-dev-datatypes student$ ls + HelloMethods csharp-web-dev-datatypes.sln + TempConverter - .. admonition:: Note +.. admonition:: Note - We use SSH to clone the repo above, but you can use HTTPS if you prefer it. - If you're not sure which you want to use, that's ok too. + The ``csharp-web-dev-datatype`` solution contains 2 separate projects: ``HelloMethods`` and ``TempConverter``. + A single solution can hold multiple projects. -#. Enter the *Target Directory* where you would like to keep your project +Try to open the solution using the command line prompt: - .. admonition:: Tip - - Make this a new, empty folder inside of your designated C# practice directory. +* Windows Users: ``start *.sln`` +* Mac Users: ``open *.sln`` + + +Return to the terminal. Locate your ``Program.cs`` file for the ``HelloMethods`` project. +This will be contained in the project directory of the same name. + +.. sourcecode:: + + students-computer:csharp-web-dev-datatypes student$ ls + HelloMethods csharp-web-dev-datatypes.sln + TempConverter + + students-computer:csharp-web-dev-datatypes student$ cd HelloMethods + students-computer:csharp-web-dev-datatypes student$ ls + HelloMethods.csproj Message.cs Program.cs + +You have now stepped into the project files for ``HelloMethods``. +All of the files here are related to the ``HelloMethods`` project. + +As you work with repos in this unit, some solutions may contain a single project and others may contain multiple. + +How to Work with a Cloned Repo +------------------------------ + +We recommend using the terminal to open and work with your repos. You will be able to interact with git easily this way. +Use the terminal to locate the repo you wish to open. ``cd`` into the solution. +You can verify this by looking for a file that has the ``.sln`` type. +Use the command prompt above for your operating system. + +Open the solution file tree in Visual Studio. +If you see multiple projects, you can select which one to run two ways: + +#. Right-clicking on the name of the project and selecting the **Run** option. +#. Open the project's ``Program.cs`` file then use the run button in the menu bar. + +Check Your Understanding +------------------------ + +.. admonition:: Question + + Which file is the solution? + + .. sourcecode:: + + students-computer:csharp-web-dev-datatypes student$ ls + HelloMethods csharp-web-dev-datatypes.sln + TempConverter + + #. ``TempConverter`` + #. ``HelloMethods`` + #. ``csharp-web-dev-datatypes.sln`` + #. ``Program.cs`` + +.. ans: c, csharp-web-dev-datatypes.sln + +.. admonition:: Question + + Where would Willow find the ``Program.cs`` file for the ``TempConverter`` project? + + .. sourcecode:: + students-computer:csharp-web-dev-datatypes student$ ls + HelloMethods csharp-web-dev-datatypes.sln + TempConverter + #. Inside the ``TempConverter`` project + #. Inside the ``HelloMethods`` project + #. Inside the ``csharp-web-dev-datatypes.sln`` + #. None of the above +.. ans: a, Inside the ``TempConverter`` project \ No newline at end of file diff --git a/src/chapters/introduction-and-setup/creating-a-csharp-project.rst b/src/chapters/introduction-and-setup/creating-a-csharp-project.rst index 06d0e4d1..3c577541 100644 --- a/src/chapters/introduction-and-setup/creating-a-csharp-project.rst +++ b/src/chapters/introduction-and-setup/creating-a-csharp-project.rst @@ -5,98 +5,64 @@ Creating a C# Project Following the "Hello World" trend, let's create a new Visual Studio project. -#. Create a new folder to hold your C# practice files. Since you will be +1. Create a new folder to hold your C# practice files. Since you will be creating lots of small projects as you move through this course, we suggest that you also add sub-folders with names corresponding to the related chapters and projects. Something like ``csharp-practice/chapter-name/project-name``. -#. In Visual Studio, from the project opener window, select the - option to create a new Visual Studio project. +2. In Visual Studio, from the project opener window, select the + option to create a *New* Visual Studio project. -#. You next need to choose what project template to use. For this first project +3. You next need to choose what project template to use. For this first project (and those in the next several lessons), select the **.NET Core Console Application** option for C#. - **Mac Users:** + Mac Users: + * You can find this by selecting **Web and Console** options in the left menu. + * Select the **App** subdirectory + * Select **Console Application** from the **General** menu option in the center menu pane - .. figure:: figures/vsmac-console-app-template.png - :alt: MAC: Visual Studio console application template selection. + Windows Users: + * Select **Console App** + * If you can't find it easily, you can search "Console App" - MAC: Visual Studio console application template selection. +4. Select **.NET 6.0** as your Target Framework. - **Windows Users:** - - .. figure:: figures/vs-windows-console-app-template.png - :alt: WINDOWS: Visual Studio console application template selection. - - WINDOWS: Visual Studio console application template selection. - -#. Then, give your new project a name. Following :ref:`naming-conventions`, +5. Then, give your new project a name. Following :ref:`naming-conventions`, call your project ``HelloWorld``. The solution name will be the same. Choose where you want this project to be saved, ideally somewhere inside the - directory you created in Step 1 of this tutorial. - - **Mac Users:** - - Pick the option to use Git for version control. - - .. figure:: figures/vsmac-name-project.png - :alt: MAC: Name a new Visual Studio Project. - - MAC: Name a new Visual Studio project. - - **Windows Users:** - - .. figure:: figures/vs-windows-name-project.png - :alt: WINDOWS: Name a new Visual Studio Project. - - WINDOWS: Name a new Visual Studio project. - -#. Once created, Visual Studio opens a new project window. + directory you created in Step 1 of this tutorial. - **Mac Users:** + Mac Users: + * Pick the options for "Use git for version control." and "Create a .gitignore file to ignore inessential files" - You'll see the project file tree on the left and a file called ``Program.cs``. +6. Visual Studio will now create a **Solution** to hold your console **Project**. + The project is your current app. The project contains all of the files that app needs to build and run. + The solution is a workspace that combines multiple projects, which are usually related to each other. + The solution file type is *.sln*. - .. figure:: figures/vsmac-new-project.png - :alt: MAC: A new Visual Studio Project with run button indicated. + Once created, Visual Studio opens a new project window that displays your ``Program.cs`` file. - MAC: A new Visual Studio project with run button indicated. - - **Windows Users:** +7. To see the other files inside this solution, you will need to **View** either the + **Solution** (Mac Users) or the **Solution Explorer** (Windows Users). You'll see the project file tree containing a file called ``Program.cs`` in a pane called *Solution Explorer*. - - .. figure:: figures/vs-windows-new-project.png - :alt: WINDOWS: A new Visual Studio Project with run button indicated. - - WINDOWS: A new Visual Studio project with run button indicated. -#. You are new to C# and we'll go over the syntax present in ``Program.cs`` - in time. For now, can you guess what line 9 accomplishes? +8. You are new to C# and we'll go over the syntax present in ``Program.cs`` + in time. For now, can you guess what line 2 accomplishes? .. sourcecode:: csharp :linenos: - using System; + // See https://aka.ms/new-console-template for more information + Console.WriteLine("Hello, World!"); - namespace HelloWorld - { - class Program - { - static void Main(string[] args) - { - Console.WriteLine("Hello World!"); - } - } - } - - Click on the triangle button indicated in one of the images above to + Click on the **Run** button (a triangle button located above the ``Program.cs`` panel) indicated in one of the images above to run the project and see the output. -#. A console window should pop up with the line "Hello World" printed. +9. A console window should pop up with the line "Hello World" printed. That's it. You have created and executed your first C# application. .. admonition:: Tip @@ -106,6 +72,16 @@ Following the "Hello World" trend, let's create a new Visual Studio project. This may also take longer than a few seconds to run the very first time. +Troubleshooting +^^^^^^^^^^^^^^^ + +This app is printing to the terminal. If you are not able to see the output, look inside the project's terminal. + +If you would like more instructions on creating and running this project check out the following documentation: + +* `Windows Users `_ +* `Mac Users `_ + .. index:: ! solution @@ -139,39 +115,28 @@ Check Your Understanding .. sourcecode:: csharp :linenos: - class HelloWorld - { - static void Main(string[] args) - { - Console.WriteLine("Hello C# Students"); - } - } + // See https://aka.ms/new-console-template for more information + Console.WriteLine("Hello, World!"); #. Line 1 - #. Line 3 - #. Line 5 + #. Line 2 #. None of the above -.. ans: c, Line 5 +.. ans: b, Line 2 .. admonition:: Question - In the sourcecode, which line is responsible for defining the class? + Where does to the following code print out? .. sourcecode:: csharp :linenos: - class HelloWorld - { - static void Main(string[] args) - { - Console.WriteLine("Hello C# Students"); - } - } - - #. line 1 - #. line 3 - #. line 5 + // See https://aka.ms/new-console-template for more information + Console.WriteLine("Hello, World!"); + + #. In line 3 of the ``Program.cs`` file + #. In the browser + #. In the terminal #. None of the above -.. ans: a, Line 1 +.. ans: c, in the terminal From c82f5f867486275ad39038a3b11cacf45d742512 Mon Sep 17 00:00:00 2001 From: Courtney Frey <66076696+speudusa@users.noreply.github.com> Date: Wed, 19 Oct 2022 09:13:30 -0500 Subject: [PATCH 09/15] Update src/chapters/vstools/nuget.rst Co-authored-by: Sally Steuterman --- src/chapters/vstools/nuget.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/chapters/vstools/nuget.rst b/src/chapters/vstools/nuget.rst index 4cb0a3b6..a8d4a21d 100644 --- a/src/chapters/vstools/nuget.rst +++ b/src/chapters/vstools/nuget.rst @@ -28,7 +28,7 @@ The following documentation can help you become more familiar with downloading a **Windows Users:** `Follow this guide `_. -**Mac Users:** `User this guide `_ +**Mac Users:** `Follow this guide `_ From 66edd6911f26209526ab946aa53e7e1cea570e07 Mon Sep 17 00:00:00 2001 From: Courtney Frey <66076696+speudusa@users.noreply.github.com> Date: Wed, 19 Oct 2022 09:16:11 -0500 Subject: [PATCH 10/15] Update src/chapters/razor-views/template-forms.rst Co-authored-by: Sally Steuterman --- src/chapters/razor-views/template-forms.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/chapters/razor-views/template-forms.rst b/src/chapters/razor-views/template-forms.rst index 1fb4ebd1..46a2d5da 100644 --- a/src/chapters/razor-views/template-forms.rst +++ b/src/chapters/razor-views/template-forms.rst @@ -3,7 +3,7 @@ Razor Forms .. admonition:: Warning - Many changes have happened in the world of Visual Studio and ASP.NET since the writing of this book. + Many changes have happened in the world of Visual Studio and ASP.NET since the original writing of this book. We reviewed the videos and instructions in the latest environment and framework and made notes to help you through any discrepancies. If you get stuck following along with a video, we suggest comparing the written instructions for the problematic area. Notes have been added to the reading that will help you locate or code what is needed to complete each chapter project. From 73c15e7c00e486a96496bd9f9e45766f6a3c3331 Mon Sep 17 00:00:00 2001 From: Courtney Frey <66076696+speudusa@users.noreply.github.com> Date: Wed, 19 Oct 2022 09:16:33 -0500 Subject: [PATCH 11/15] Update src/chapters/razor-views/template-forms.rst Co-authored-by: Sally Steuterman --- src/chapters/razor-views/template-forms.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/chapters/razor-views/template-forms.rst b/src/chapters/razor-views/template-forms.rst index 46a2d5da..15a2c3ec 100644 --- a/src/chapters/razor-views/template-forms.rst +++ b/src/chapters/razor-views/template-forms.rst @@ -46,7 +46,7 @@ CodingEvents Setup - Text #. Within the action method, create an empty list and add a few event names to it. #. Add the list to ``ViewBag``. Then return the corresponding view. #. Within the ``Views`` directory, create a new directory named ``Events``. Within this directory, create a new view named ``Index.cshtml``. -#. Within the new template, loop over the list and display the name of each event. Make sure your template can handle an empty List. +#. Within the new template, loop over the List and display the name of each event. Make sure your template can handle an empty List. Create and Render a Form - Video -------------------------------- From cfeee982b4250d48c1644a71c31a110f90fe454e Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Thu, 20 Oct 2022 09:26:45 -0500 Subject: [PATCH 12/15] updated codeblock formatting --- .../validation-attributes.rst | 97 ++++++++++--------- .../validation-controller.rst | 50 +++++----- .../validation-views.rst | 2 +- .../aspdotnet-model-validation/viewmodels.rst | 8 +- 4 files changed, 79 insertions(+), 78 deletions(-) diff --git a/src/chapters/aspdotnet-model-validation/validation-attributes.rst b/src/chapters/aspdotnet-model-validation/validation-attributes.rst index 0f9043dc..4f3a5060 100644 --- a/src/chapters/aspdotnet-model-validation/validation-attributes.rst +++ b/src/chapters/aspdotnet-model-validation/validation-attributes.rst @@ -41,13 +41,13 @@ We'll use only a few of these attributes, but you can find a full list in the `d .. sourcecode:: csharp :linenos: - [Required] - [StringLength(12, MinimumLength = 3)] - public string Username { get; set; } + [Required] + [StringLength(12, MinimumLength = 3)] + public string Username { get; set; } - [Reguired] - [StringLength(20, MinimumLength=6)] - public string Password { get; set; } + [Reguired] + [StringLength(20, MinimumLength=6)] + public string Password { get; set; } Defining Validation Messages ---------------------------- @@ -64,13 +64,13 @@ Each of these attributes takes an optional ``ErrorMessage`` parameter that allow .. sourcecode:: csharp :linenos: - [Required(ErrorMessage = "Username is required")] - [StringLength(12, MinimumLength = 3, ErrorMessage = "Username must be between 3 and 12 characters long")] - public string Username { get; set; } + [Required(ErrorMessage = "Username is required")] + [StringLength(12, MinimumLength = 3, ErrorMessage = "Username must be between 3 and 12 characters long")] + public string Username { get; set; } - [Required(ErrorMessage = "Password is required")] - [StringLength(20, MinimumLength = 6, ErrorMessage = "Sorry, but the given password is too short. Passwords must be at least 6 characters long.")] - public string Password { get; set; } + [Required(ErrorMessage = "Password is required")] + [StringLength(20, MinimumLength = 6, ErrorMessage = "Sorry, but the given password is too short. Passwords must be at least 6 characters long.")] + public string Password { get; set; } We will see how to ensure these error messages are properly displayed in the next section, :ref:`validating-models`. @@ -95,13 +95,13 @@ For our ``AddEventViewModel`` class, we add ``[StringLength]`` and ``[Required]` .. sourcecode:: csharp :lineno-start: 8 - [Required(ErrorMessage = "Name is required.")] - [StringLength(50, MinimumLength = 3, ErrorMessage = "Name must be between 3 and 50 characters.")] - public string Name { get; set; } + [Required(ErrorMessage = "Name is required.")] + [StringLength(50, MinimumLength = 3, ErrorMessage = "Name must be between 3 and 50 characters.")] + public string Name { get; set; } - [Required(ErrorMessage = "Please enter a description for your event.")] - [StringLength(500, ErrorMessage = "Description is too long!")] - public string Description { get; set; } + [Required(ErrorMessage = "Please enter a description for your event.")] + [StringLength(500, ErrorMessage = "Description is too long!")] + public string Description { get; set; } The required ``MaximumLength`` and optional ``MinimumLength`` parameters for ``[StringLength]`` specify the maximum and minimum number of allowed characters, respectively. Omitting the minimum length requirement means that no min or max will be applied for the field. @@ -118,8 +118,8 @@ Thankfully, there is an ``[EmailAddress]`` validation attribute that we can appl .. sourcecode:: csharp :lineno-start: 16 - [EmailAddress] - public string ContactEmail { get; set; } + [EmailAddress] + public string ContactEmail { get; set; } Before we can start up our application, we need to add a new input to our form in ``Events/Add.cshtml`` to take in the contact email for an event organizer. While we don't demonstrate these items in the video above, we cover them on the next page before tackling validation in the controller. @@ -127,40 +127,41 @@ an event organizer. While we don't demonstrate these items in the video above, w .. sourcecode:: html :lineno-start: 14 -
      - - -
      +
      + + +
      We also need to add a new column to the ``Events/Index.cshtml`` template to make ``ContactEmail`` visible. .. sourcecode:: html :lineno-start: 20 - - - - - - - - @foreach (var evt in Model) - { - - - - - - - } +
      - Id - - Name - - Description - - Contact Email -
      @evt.Id@evt.Name@evt.Description@evt.ContactEmail
      + + + + + + + + @foreach (var evt in Model) + { + + + + + + + }
      + Id + + Name + + Description + + Contact Email +
      @evt.Id@evt.Name@evt.Description@evt.ContactEmail
      Now we can start up our application and test. diff --git a/src/chapters/aspdotnet-model-validation/validation-controller.rst b/src/chapters/aspdotnet-model-validation/validation-controller.rst index 27e18f7a..486af03e 100644 --- a/src/chapters/aspdotnet-model-validation/validation-controller.rst +++ b/src/chapters/aspdotnet-model-validation/validation-controller.rst @@ -17,20 +17,20 @@ objects from form submissions. .. sourcecode:: csharp :lineno-start: 32 - [HttpPost] - public IActionResult Add(AddEventViewModel addEventViewModel) - { - Event newEvent = new Event + [HttpPost] + public IActionResult Add(AddEventViewModel addEventViewModel) { - Name = addEventViewModel.Name, - Description = addEventViewModel.Description, - ContactEmail = addEventViewModel.ContactEmail - }; + Event newEvent = new Event + { + Name = addEventViewModel.Name, + Description = addEventViewModel.Description, + ContactEmail = addEventViewModel.ContactEmail + }; - EventData.Add(newEvent); + EventData.Add(newEvent); - return Redirect("/Events"); - } + return Redirect("/Events"); + } The flow of this request can be described as follows: @@ -110,25 +110,25 @@ Once we are done refactoring the ``Add()`` action method to use ``ModelState.IsV .. sourcecode:: csharp :lineno-start: 32 - [HttpPost] - public IActionResult Add(AddEventViewModel addEventViewModel) - { - if (ModelState.IsValid) + [HttpPost] + public IActionResult Add(AddEventViewModel addEventViewModel) { - Event newEvent = new Event + if (ModelState.IsValid) { - Name = addEventViewModel.Name, - Description = addEventViewModel.Description, - ContactEmail = addEventViewModel.ContactEmail - }; + Event newEvent = new Event + { + Name = addEventViewModel.Name, + Description = addEventViewModel.Description, + ContactEmail = addEventViewModel.ContactEmail + }; - EventData.Add(newEvent); + EventData.Add(newEvent); - return Redirect("/Events"); - } + return Redirect("/Events"); + } - return View(addEventViewModel); - } + return View(addEventViewModel); + } Now we have refactored our action method to handle any errors in form submission. However, if you submit a value that doesn't meet our conditions, you won't see any error messages indicating what was wrong with your submission. diff --git a/src/chapters/aspdotnet-model-validation/validation-views.rst b/src/chapters/aspdotnet-model-validation/validation-views.rst index 51a07473..c959b9a3 100644 --- a/src/chapters/aspdotnet-model-validation/validation-views.rst +++ b/src/chapters/aspdotnet-model-validation/validation-views.rst @@ -30,7 +30,7 @@ Now when we run our application and enter a bad event name or forget our descrip .. admonition:: Warning In the video, we note that the ```` element will only be materialized if the validation fails. This isn't true. The ```` element - to contain the error message is always created, it just doesn't contain any text if the validation rule it met. + to contain the error message is always created, it just doesn't contain any text if the validation rule it met. Check Your Understanding ------------------------ diff --git a/src/chapters/aspdotnet-model-validation/viewmodels.rst b/src/chapters/aspdotnet-model-validation/viewmodels.rst index df342c04..fab5df19 100644 --- a/src/chapters/aspdotnet-model-validation/viewmodels.rst +++ b/src/chapters/aspdotnet-model-validation/viewmodels.rst @@ -37,23 +37,23 @@ First, in ``EventsController``, we want to convert the collection of Events we h .. sourcecode:: csharp :lineno-start: 19 - List events = new List(EventData.GetAll()); + List events = new List(EventData.GetAll()); Now that we are storing our items in a ``List``, we need to import the model into our ``Events/Index.cshtml`` view so we can use the new ``events`` collection. We can add a small statement up on line 1 to do so: .. sourcecode:: csharp - @model List + @model List Or, as we write in the video: .. sourcecode:: csharp :linenos: - @using CodingEventsDemo.Models + @using CodingEventsDemo.Models - @model List + @model List Wherever we used our ``ViewBag`` property, we can now use ``Model`` syntax. Once the view has been updated, run the application! From 4e457ecdec6a8abca090178281a36bcbcc11c741 Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Thu, 20 Oct 2022 13:37:54 -0500 Subject: [PATCH 13/15] validation updates --- .../aspdotnet-model-validation/exercises.rst | 8 +- .../validation-views.rst | 73 +++++++++++++++++-- 2 files changed, 71 insertions(+), 10 deletions(-) diff --git a/src/chapters/aspdotnet-model-validation/exercises.rst b/src/chapters/aspdotnet-model-validation/exercises.rst index c5ed7914..9470596a 100644 --- a/src/chapters/aspdotnet-model-validation/exercises.rst +++ b/src/chapters/aspdotnet-model-validation/exercises.rst @@ -43,6 +43,8 @@ For the purposes of validation practice, make this property only able to be mark public bool IsTrue { get { return true; } } - With ``IsTrue`` in ``AddEventViewModel``, you can use a ``[Compare]`` attribute to compare the value of the ``IsTrue`` property which is always ``true`` and the value of the property you add for registration requirements. - The `documentation `__ has more information on how the ``[Compare]`` attribute. - + With ``IsTrue`` in ``AddEventViewModel``, you can use a ``[Compare]`` + attribute to compare the value of the ``IsTrue`` property which is always ``true`` + and the value of the property you add for registration requirements. The + `documentation `__ + has more information on how the ``[Compare]`` attribute. \ No newline at end of file diff --git a/src/chapters/aspdotnet-model-validation/validation-views.rst b/src/chapters/aspdotnet-model-validation/validation-views.rst index c959b9a3..fa625544 100644 --- a/src/chapters/aspdotnet-model-validation/validation-views.rst +++ b/src/chapters/aspdotnet-model-validation/validation-views.rst @@ -1,7 +1,14 @@ Validation and Views ==================== -While our application is properly handing errors, we need to display the error messages so that the users know what information they should be adding. +While our application is properly handing errors, +we need to display the error messages so that the users know what +information they should be adding. +Client-side validation like this can prevent faulty data submissions. + +Since the filming of this video, ASP.NET requires a different method +for changing the color of error messages. +Instructions for working with ``field-validation-valid`` have been updated below. Displaying Error Messages in our View - Video --------------------------------------------- @@ -18,19 +25,71 @@ Displaying Error Messages in our View - Video Displaying Error Messages in our View - Text -------------------------------------------- -Create a separate ``span`` element in the form. -In the ```` tag, we can add ``asp-validation-for`` to specify which property's validation error messages should be displayed if the conditions are not met. +Create a separate span element in the form. +In the ```` tag, we can add asp-validation-for to specify which property’s +validation error messages should be displayed if the conditions are not met. .. admonition:: Note - We don't have to add anything else to display error messages, because that validation is already built in! + We don’t have to add anything else to display error messages, + because that validation is already built in! -Now when we run our application and enter a bad event name or forget our description, we get the error message displaying what we should be entering! +Now when we run our application and enter a bad event name or forget our description, +we get the error message displaying what we should be entering! .. admonition:: Warning - In the video, we note that the ```` element will only be materialized if the validation fails. This isn't true. The ```` element - to contain the error message is always created, it just doesn't contain any text if the validation rule it met. + In the video, we note that the element will only be materialized if the validation fails. This isn’t true. The element + to contain the error message is always created, it just doesn’t contain any text if the validation rule it met. + + +Changing the Color of Error Messages +------------------------------------ + +Adding to the project's ``site.css`` will not change the color of your error messages. +We need to add more code to the project. + +One way to do this is by using **unobtrusive validation** methods, such as using a third-party library. + +The `jQuery Unobtrusive Validation `_ library. +contains scripts that will perform validation tasks, such as updating the color of error messages. +To utilize this library, we need to point to it in our ``_Layout.cshtml`` page and then +add more attributes to our Views. + +``_Layout.cshtml`` Updates +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To utilize the library, we need to add the following references to it within the +``
      `` area. + +.. sourcecode:: html + +
      + @RenderBody() + + + +
      + + +In the ``Add`` View, you will need to add more ``class`` attributes for the library to target. + +.. sourcecode:: html + :lineno-start: 8 + +
      + + + +
      + +Note in line 10 the addition of ``class="form-control`` and in line 11 ``class="text-danger"``. +These attributes will be noted by the jQuery Unobtrusive Validation library and print our red +if the client does not meet the requirements. + +You can read morea about client-side validation +and the jQuery Unobtrusive Validation library `here `_. +That is were we found the syntax for this portion of the project. Check Your Understanding ------------------------ From dbbe5ad06794a4d0159cdc8b7d80f0f39b102547 Mon Sep 17 00:00:00 2001 From: Courtney Frey Date: Thu, 20 Oct 2022 14:36:48 -0500 Subject: [PATCH 14/15] dotnet 6 updates added to text and links --- .../validation-attributes.rst | 6 ++-- .../validation-views.rst | 2 +- src/chapters/enums/enums-in-models.rst | 35 ++++++++++++------- 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/src/chapters/aspdotnet-model-validation/validation-attributes.rst b/src/chapters/aspdotnet-model-validation/validation-attributes.rst index 4f3a5060..623e0713 100644 --- a/src/chapters/aspdotnet-model-validation/validation-attributes.rst +++ b/src/chapters/aspdotnet-model-validation/validation-attributes.rst @@ -1,7 +1,8 @@ Validation Attributes ===================== -Within the ViewModel or model of a C# web application, we can define validation rules using attributes. +Within the ViewModel or model of a C# web application, +we can define validation rules using attributes. Validation attributes can be applied to model fields. .. index:: @@ -12,7 +13,8 @@ Validation attributes can be applied to model fields. Common Attributes ------------------ -We'll use only a few of these attributes, but you can find a full list in the `documentation `_. +We'll use only a few of these attributes, but you can find a +full list in the `documentation `_. .. list-table:: Common Validation Attributes :header-rows: 1 diff --git a/src/chapters/aspdotnet-model-validation/validation-views.rst b/src/chapters/aspdotnet-model-validation/validation-views.rst index fa625544..0440dc56 100644 --- a/src/chapters/aspdotnet-model-validation/validation-views.rst +++ b/src/chapters/aspdotnet-model-validation/validation-views.rst @@ -83,7 +83,7 @@ In the ``Add`` View, you will need to add more ``class`` attributes for the libr
-Note in line 10 the addition of ``class="form-control`` and in line 11 ``class="text-danger"``. +Note in line 10 the addition of ``class="form-control"`` and in line 11 ``class="text-danger"``. These attributes will be noted by the jQuery Unobtrusive Validation library and print our red if the client does not meet the requirements. diff --git a/src/chapters/enums/enums-in-models.rst b/src/chapters/enums/enums-in-models.rst index a6d8ebdc..6eb2afce 100644 --- a/src/chapters/enums/enums-in-models.rst +++ b/src/chapters/enums/enums-in-models.rst @@ -1,7 +1,9 @@ Enums in Model Classes ====================== -One application of enum types is to represent categories of objects. We will take this approach in our ``CodingEvents`` application to categorize events based on their type, such as *conference* or *meetup*. +One application of enum types is to represent categories of objects. +We will take this approach in our ``CodingEvents`` application to +categorize events based on their type, such as *conference* or *meetup*. Enum Types in Models - Video ---------------------------- @@ -11,8 +13,11 @@ Enum Types in Models - Video .. admonition:: Note - If you ever want to verify what code the video starts with, check out the `display-error-messages `__ branch in ``CodingEventsDemo``. - If you ever want to verify what code the video ends with, check out the `enums `__ branch in ``CodingEventsDemo``. + If you ever want to verify what code the video starts with, + check out the `display-error-messages `__ \ + branch in ``CodingEventsDemo``. If you ever want to verify what code the video ends with, + check out the `enums `__ + branch in ``CodingEventsDemo``. Enum Types in Models - Text --------------------------- @@ -53,7 +58,8 @@ we create a ``Type`` property in ``Event`` amongst the other properties declared // Event methods -Once we have added an ``EventType`` property to our model, we need to add an ``EventType`` property to our ViewModel. +Once we have added an ``EventType`` property to our model, we need to add an +``EventType`` property to our ViewModel. Add an Enum Property to a ViewModel ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -67,7 +73,8 @@ The first thing we need to do is add an ``EventType`` property to ``AddEventView public EventType Type { get; set; } -Now that we have a property to hold the event type that the user selects, we need to create a list of all of the possible event types. +Now that we have a property to hold the event type that the user selects, +we need to create a list of all of the possible event types. We will use this list to populate the ``select`` element in a later step. .. sourcecode:: csharp @@ -82,13 +89,17 @@ We will use this list to populate the ``select`` element in a later step. }; Because the ``EventType`` options are not changing, we can populate this property with a default value. -We add each of the constants to the ``EventTypes`` list. ``SelectListItem`` is an ASP.NET-provided class that represents each ``