Introduction to the Console

Overview

When you have created an ASP.NET Core Web application, when you execute it, Microsoft Visual Studio opens a Hosting window and creates a website to display in a browser. The Hosting window is a Microsoft Windows object with a black background that displays some characters. Here is an example:

Add New Item

When the hosting window comes up, Microsoft Visual Studio writes some lines about the local server setup of your current application. You too can display some values about your application in that window. To allow you to display some values in the Hosting window, the .NET library provides a static class named Console.

Practical LearningPractical Learning: Introducing the Console

  1. Start Microsoft Visual Studio and create a new ASP.NET Core Web App that supports .NET 6.0 (Long-Term Support) named ObliqueTriangles3. Uncheck the Configure For HTTPS check box
  2. In the Solution Explorer, right-click wwwroot -> Add -> New Folder
  3. Type images and press Enter
  4. In the Solution Explorer, under wwwroot, right-click images -> Add -> Existing Item...
  5. Select the aas.png, asa.png, sas.png, and sss.png images you had saved from a previous lesson. Click Add to add them to the project
  6. In the Solution Explorer, under wwwroot, right-click css -> Add -> New Item...
  7. In the left list of the Add New Item dialog box, under Visual C#, expand ASP.NET Core. Expand Web, and click Content
  8. In the middle list, click Style Sheet
  9. Change the file Name to Trigonometry
  10. Press Enter
  11. Change the document as follows:
    body {
    }
    
    .bold        { font-weight:      bold;  }
    .text-right  { text-align:       right  }
    .delimiter   { margin:           auto;
                   width:            650px; }
    .top-bar     { border-bottom:    6px solid blue;
                   background-color: #800000 !important; }
    .common-font { font-family:      Georgia, Garamond, 'Times New Roman', serif; }
    .navbar-light .navbar-brand       { color:       white;  }
    .navbar-light .navbar-brand:hover { color:       yellow; }
    .navbar-light .navbar-brand:focus { color:       khaki;  }
    .navbar-light .navbar-brand       { font-family: Georgia, Garamond, 'Times New Roman', serif; }
    .nav-link                         { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  12. In the Solution Explorer, expand Pages
  13. In the Solution Explorer, under Pages, expand Shared
  14. In the Solution Explorer, under Pages and under Shared, double-click _Layout.cshtml
  15. Change the document as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - Oblique Triangles</title>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
        <link rel="stylesheet" href="~/css/Geometry.css" asp-append-version="true" />
    </head>
    <body>
        <header>
            <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3 top-bar">
                <div class="container">
                    <a class="navbar-brand" asp-area="" asp-page="/Index">Oblique Triangles</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                            aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/AAS">AAS</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/SAS">SAS</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/ASA">ASA</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/SSS">SSS</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>
        <div class="container">
            <main role="main" class="pb-3">
                @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted">
            <div class="container">
                <p class="text-center common-font">&copy; 2022 - Oblique Triangles - <a asp-area="" asp-page="/Privacy">Privacy</a></p>
            </div>
        </footer>
    
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @await RenderSectionAsync("Scripts", required: false)
    </body>
    </html>
  16. In the Solution Explorer, right-click Pages -> Add -> Razor Page...
  17. In the Add New Sacffolded Item dialox box, make sure Razor Page - Empty is selected.
    Click Add
  18. Change the file Name to AAS
  19. Click Add

Starting Console Code

The Console class is defined in the System namespace. Therefore, to use it in your application, in your code, you can type System followed by a period. If you are using the code Editor in Microsoft Visual Studio to create your application, its Intellisense would display the available classes of that namespace.

Since the Console class is static, you never have to declare a variable of it in order to use it. Therefore, to access the Console class in your code, after typing System and a period, type Console. To access a member of this class, type a period after its name.

Writing to the Console

To provide the ability to display one or more values to the screen, the Console class is equipped with a method named Write. To use the Write() method, inside its parentheses, type the value you want to display. Here is an example:

@{
    System.Console.Write("The Wonderful World of C# Programming");
}

To be able to handle any value of the data types we have used so far, the Write() method is overloaded with various versions. There is a version for each data type. The syntaxes are:

public static void Write(int value);
public static void Write(uint value);
public static void Write(string value);
public static void Write(long value);
public static void Write(ulong value);
public static void Write(float value);
public static void Write(double value);
public static void Write(decimal value);
public static void Write(object value);

Writing With a New Line

After displaying a value on the screen, the Write() method keeps the caret on the same line. To give you the ability to move the caret to the next line after displaying a value, the Console class is equipped with a method named WriteLine. Like Write(), the WriteLine() method has a version for each of the data types we have used so far:

public static void WriteLine(int value);
public static void WriteLine(uint value);
public static void WriteLine(string value);
public static void WriteLine(long value);
public static void WriteLine(ulong value);
public static void WriteLine(float value);
public static void WriteLine(double value);
public static void WriteLine(decimal value);
public static void WriteLine(object value);

Besides these versions, the Write() and the WriteLine() methods have each a version that takes an unlimited number of arguments. Their syntaxes are:

public static void WriteLine(. . .);
public static void WriteLine(. . .);

To get skeleton code for System.Console.WriteLine, right-click the line where you want to add it, position the mouse on Snippet, and click Insert Snippet... Double-click Visual C#. In the list, double-click cw:

cw

Practical LearningPractical Learning: Introducing Data Writing

  1. Change the AAS.cshtml document as follows:
    @page
    @model ObliqueTriangles3.Pages.AASModel
    @{
        double side1 = 0.00, side2 = 0.00, side3 = 0.00;
        double angle1 = 0.00, angle2 = 0.00, angle3 = 0.00;
    
        if (Request.HasFormContentType)
        {
            try
            {
                angle1 = double.Parse(Request.Form["txtAASAngle1"]);
            }
            catch (FormatException)
            {
                System.Console.WriteLine("You must type a value for the lower left angle of the AAS shape.");
            }
    
            try
            {
                  angle2 = double.Parse(Request.Form["txtAASAngle2"]);
            }
            catch (FormatException)
            {
                System.Console.WriteLine("You must type a value for the lower right angle of the AAS shape.");
            }
    
            try
            {
                side1 = double.Parse(Request.Form["txtAASSide1"]);
            }
            catch (FormatException)
            {
                System.Console.WriteLine("You must type a value for the right side of the AAS shape.");
            }
    
            // Here, we use the law of sines
            angle3 = 180 - (angle1 + angle2);
            side2 = side1 * Math.Sin(angle2 * Math.PI / 180) / Math.Sin(angle1 * Math.PI / 180);
            side3 = side1 * Math.Sin(angle3 * Math.PI / 180) / Math.Sin(angle1 * Math.PI / 180);
    
            System.Console.WriteLine("======================================================================");
            System.Console.WriteLine("Oblique Triangles - AAS Shape");
            System.Console.WriteLine("======================================================================");
            System.Console.WriteLine("Known Values: 2 Angles and 1 Side");
            System.Console.WriteLine("----------------------------------------------------------------------");
            System.Console.WriteLine("Known Angle   1:  " + angle1.ToString());
            System.Console.WriteLine("Known Angle   2:  " + angle2.ToString());
            System.Console.WriteLine("Known Side    1:  " + side1.ToString());
            System.Console.WriteLine("======================================================================");
            System.Console.WriteLine("Unknown Values: 1 Angle and 2 Sides");
            System.Console.WriteLine("----------------------------------------------------------------------");
            System.Console.WriteLine("Unknown Angle 3:  " + angle3.ToString());
            System.Console.WriteLine("Unknown Side  2:  " + side2.ToString());
            System.Console.WriteLine("Unknown Side  3:  " + side3.ToString());
            System.Console.WriteLine("======================================================================");
        }
    }
    
    <div class="delimiter common-font">
        <h2 class="text-center bold">Oblique Triangles - AAS Shape</h2>
        <hr />
        <h5 class="text-right">Known Values: 2 Angles and 1 Side</h5>
        <hr />
       <form name="frmGeometry" method="post">
          <table>
              <tr>
                  <td style="width: 300px" rowspan="3">
                      <img src="~/images/aas.png" width="258" height="159" alt="Oblique Triangles - AAS Shape">
                  </td>
                  <td style="width: 150px">Known Angle 1:</td>
                  <td>@Html.TextBox("txtAASAngle1", @angle1, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>Known Angle 2:</td>
                  <td>@Html.TextBox("txtAASAngle2", @angle2, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>Known Side 1:</td>
                  <td>@Html.TextBox("txtAASSide1", @side1, new { @class = "form-control text-right" })</td>
              </tr>
          </table>
          
          <hr />
                  
          <table>
              <tr>
                  <td style="width: 350px">&nbsp;</td>
                  <td style="text-align: center"><input type="submit" name="btnSubmit" value="Find Unknown Values" /></td>
              </tr>
          </table>
      </form>
    
      <hr />
      
      <h5 class="text-right">Unknown Values: 1 Angle and 2 Sides</h5>
      
      <hr />
      
      <table>
          <tr>
              <td style="width: 300px">&nbsp;</td>
              <td style="width: 150px">Unknown Angle 3:</td>
              <td>@Html.TextBox("txtAASAngle3", @angle3, new { @class = "form-control text-right" })</td>
          </tr>
          <tr>
              <td>&nbsp;</td>
              <td>Unknown Side 2:</td>
              <td>@Html.TextBox("txtAASSide2", @side2, new { @class = "form-control text-right" })</td>
          </tr>
          <tr>
              <td>&nbsp;</td>
              <td>Unknown Side 3:</td>
              <td>@Html.TextBox("txtAASSide3", @side3, new { @class = "form-control text-right" })</td>
          </tr>
      </table>
    </div>
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. Click the AAS link

    Oblique Triangles - AAS

  4. Click the Known Angle 1 text box and type 38
  5. Click the Known Angle 2 text box and type 21
  6. Click the Known Side 1 text box and type 24

    Oblique Triangles - AAS

  7. Display the Hosting window and the browser side by side
  8. Click the Find Unknown Values button:

    Oblique Triangles - AAS - The Hosting Window

    Oblique Triangles - AAS

  9. Return to your programming environment
  10. In the Solution Explorer, right-click Pages -> Add -> Razor Page...
  11. In the Add New Sacffolded Item dialox box, make sure Razor Page - Empty is selected.
    Click Add
  12. Change the file Name to SAS
  13. Click Add

Accessing the Members of the Console Class

Remember that, to access any class, you can qualify it from its namespace. Here is an example of calling a method of the Console class that is defined in the System namespace:

@{
    System.Console.WriteLine("The Wonderful World of C# Programming");
}

Using a Namespace

As you may know by now, to use a namespace, in your code, usually in the top section, type using followed by the name of the namespace. If you are writing your code in a razor page, in the top section, after the @page and the other top lines, type @using System. After doing any of this, you can access a class of the namespace in your code.

Practical LearningPractical Learning: Using a Namespace

  1. Change the document as follows:
    @page
    @model ObliqueTriangles3.Pages.SASModel
    @using System
    @{
        double side1 = 0.00, side2 = 0.00, side3 = 0.00;
        double angle1 = 0.00, angle2 = 0.00, angle3 = 0.00;
    
        if (Request.HasFormContentType)
        {
            try
            {
                side1 = double.Parse(Request.Form["txtSASSide1"]);
            }
            catch (FormatException)
            {
                Console.WriteLine("You must type a value for one of the known sides of the SAS shape.");
            }
    
            try
            {
                  angle1 = double.Parse(Request.Form["txtSASAngle1"]);
            }
            catch (FormatException)
            {
                Console.WriteLine("You must type a value for the known angle of the SAS shape.");
            }
    
            try
            {
                side2 = double.Parse(Request.Form["txtSASSide2"]);
            }
            catch (FormatException)
            {
                Console.WriteLine("You must type a value for the other known side of the SAS shape.");
            }
    
            // Here, we use the law of cosines
            side3 = Math.Sqrt((side1 * side1) +
                              (side2 * side2) -
                              (2 * side1 * side2 * Math.Cos(angle1 * Math.PI / 180)));
            angle2 = Math.Acos(((side3 * side3) +
                               (side2 * side2) -
                               (side1 * side1)) /
                               (2 * side3 * side2)) * 180 / Math.PI;
            angle3 = 180 - (angle1 + angle2);
    
            System.Console.WriteLine("======================================================================");
            System.Console.WriteLine("Oblique Triangles - SAS Shape");
            System.Console.WriteLine("======================================================================");
            System.Console.WriteLine("Known Values: 2 Sides and 1 Angle");
            System.Console.WriteLine("----------------------------------------------------------------------");
            System.Console.WriteLine("Known Side    1:  " + side1.ToString());
            System.Console.WriteLine("Known Angle   1:  " + angle1.ToString());
            System.Console.WriteLine("Known Side    2:  " + side2.ToString());
            System.Console.WriteLine("======================================================================");
            System.Console.WriteLine("Unknown Values: 1 Side and 2 Angles");
            System.Console.WriteLine("----------------------------------------------------------------------");
            System.Console.WriteLine("Unknown Angle 2:  " + angle2.ToString());
            System.Console.WriteLine("Unknown Side  3:  " + side3.ToString());
            System.Console.WriteLine("Unknown Angle 3:  " + angle3.ToString());
            System.Console.WriteLine("======================================================================");
        }
    }
    
    <div class="delimiter common-font">
        <h2 class="text-center bold">Oblique Triangles - SAS  Shape</h2>
        <hr />
        <h5 class="text-right">Known Values: 2 Sides and 1 Angle</h5>
        <hr />
       <form name="frmGeometry" method="post">
          <table>
              <tr>
                  <td style="width: 300px" rowspan="3">
                      <img src="~/images/sas.png" width="260" height="138" alt="Oblique Triangles - SAS Shape">
                  </td>
                  <td style="width: 150px">Known Side 1:</td>
                  <td>@Html.TextBox("txtSASSide1", @side1, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>Known Angle 1:</td>
                  <td>@Html.TextBox("txtSASAngle1", @angle1, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>Known Side 2:</td>
                  <td>@Html.TextBox("txtSASSide2", @side2, new { @class = "form-control text-right" })</td>
              </tr>
          </table>
          
          <hr />
                  
          <table>
              <tr>
                  <td style="width: 350px">&nbsp;</td>
                  <td style="text-align: center"><input type="submit" name="btnSubmit" value="Find Unknown Values" /></td>
              </tr>
          </table>
      </form>
    
      <hr />
      
      <h5 class="text-right">Unknown Values: 1 Side and 2 Angles</h5>
      
      <hr />
      
      <table>
          <tr>
              <td style="width: 300px">&nbsp;</td>
              <td style="width: 150px">Unknown Angle 2:</td>
              <td>@Html.TextBox("txtSASAngle2", @angle2, new { @class = "form-control text-right" })</td>
          </tr>
          <tr>
              <td>&nbsp;</td>
              <td>Unknown Side 3:</td>
              <td>@Html.TextBox("txtSASSide3", @side3, new { @class = "form-control text-right" })</td>
          </tr>
          <tr>
              <td>&nbsp;</td>
              <td>Unknown Angle 3:</td>
              <td>@Html.TextBox("txtSASAngle3", @angle3, new { @class = "form-control text-right" })</td>
          </tr>
      </table>
    </div>
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. If the browser presents a Resend button, click it, or refresh the browser
  4. Click the SAS link:

    Oblique Triangles - SAS

  5. Click the Known Side 1 text box and type 24
  6. Click the Known Angle 1 text box and type 34
  7. Click the Known Side 2 text box and type 36.5

    Oblique Triangles - SAS

  8. Click the Find Unknown Values button:

    Oblique Triangles - SSS - The Hosting Window

    Oblique Triangles - SAS

  9. Return to your programming environment

Statically Using a Namespace

Remember that, to access a static method, you can include using static followed by the name of the class in the top section of the document. If you are writing your code in a razor page, after the @page and the other top lines, type @using static System.Console. After applying one of those options, where needed, you can access one the static members of the Console class.

Practical LearningPractical Learning: Using a Namespace

  1. In the Solution Explorer, right-click Pages -> Add -> Razor Page...
  2. In the Add New Sacffolded Item dialox box, make sure Razor Page - Empty is selected.
    Click Add
  3. Change the file Name to ASA
  4. Click Add
  5. Change the document as follows:
    @page
    @model ObliqueTriangles3.Pages.ASAModel
    @using static System.Console
    @{
        double side1 = 0.00, side2 = 0.00, side3 = 0.00;
        double angle1 = 0.00, angle2 = 0.00, angle3 = 0.00;
    
        if (Request.HasFormContentType)
        {
            try
            {
                angle1 = double.Parse(Request.Form["txtASAAngle1"]);
            }
            catch (FormatException)
            {
                WriteLine("You must type a value for one of the known angles of the ASA shape.");
            }
    
            try
            {
                  side1 = double.Parse(Request.Form["txtASASide1"]);
            }
            catch (FormatException)
            {
                WriteLine("You must type a value for the side that is between the angles whose values are about the ASA shape.");
            }
    
            try
            {
                angle2 = double.Parse(Request.Form["txtASAAngle2"]);
            }
            catch (FormatException)
            {
                WriteLine("You must type a value for the other known angle of the ASA oblique triangle.");
            }
    
            // Here, we use the law of sines
            angle3 = 180 - (angle1 + angle2);
            side2 = side1 * Math.Sin(angle2 * Math.PI / 180) / Math.Sin(angle1 * Math.PI / 180);
            side3 = side1 * Math.Sin(angle3 * Math.PI / 180) / Math.Sin(angle1 * Math.PI / 180);
    
            WriteLine("======================================================================");
            WriteLine("Oblique Triangles - ASS Shape");
            WriteLine("======================================================================");
            WriteLine("Known Values: 2 Angles and 1 Side joining them");
            WriteLine("----------------------------------------------------------------------");
            WriteLine("Known Angle   1:  " + angle1.ToString());
            WriteLine("Known Side    1:  " + side1.ToString());
            WriteLine("Known Angle   2:  " + angle2.ToString());
            WriteLine("======================================================================");
            WriteLine("Unknown Values: 2 Sides and 1 Angle between them");
            WriteLine("----------------------------------------------------------------------");
            WriteLine("Unknown Side  2:  " + side2.ToString());
            WriteLine("Unknown Angle 3:  " + angle3.ToString());
            WriteLine("Unknown Side  3:  " + side3.ToString());
            WriteLine("======================================================================");
        }
    }
    
    <div class="delimiter common-font">
        <h2 class="text-center bold">Oblique Triangles - ASA  Shape</h2>
        <hr />
        <h5 class="text-right">Known Values: 2 Angles and 1 Side joining them</h5>
        <hr />
       <form name="frmGeometry" method="post">
          <table>
              <tr>
                  <td style="width: 300px" rowspan="3">
                      <img src="~/images/asa.png" width="260" height="138" alt="Oblique Triangles - SAS Shape">
                  </td>
                  <td style="width: 150px">Known Angle 1:</td>
                  <td>@Html.TextBox("txtASAAngle1", @angle1, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>Known Side 1:</td>
                  <td>@Html.TextBox("txtASASide1", @side1, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>Known Angle 2:</td>
                  <td>@Html.TextBox("txtASAAngle2", @angle2, new { @class = "form-control text-right" })</td>
              </tr>
          </table>
          
          <hr />
                  
          <table>
              <tr>
                  <td style="width: 350px">&nbsp;</td>
                  <td style="text-align: center"><input type="submit" name="btnSubmit" value="Find Unknown Values" /></td>
              </tr>
          </table>
      </form>
    
      <hr />
      
      <h5 class="text-right">Unknown Values: 2 Sides and 1 Angle between them</h5>
      
      <hr />
      
      <table>
          <tr>
              <td style="width: 300px">&nbsp;</td>
              <td style="width: 150px">Unknown Side 2:</td>
              <td>@Html.TextBox("txtASASide2", @side2, new { @class = "form-control text-right" })</td>
          </tr>
          <tr>
              <td>&nbsp;</td>
              <td>Unknown Angle 3:</td>
              <td>@Html.TextBox("txtASAAngle3", @angle3, new { @class = "form-control text-right" })</td>
          </tr>
          <tr>
              <td>&nbsp;</td>
              <td>Unknown Side 3:</td>
              <td>@Html.TextBox("txtASASide3", @side3, new { @class = "form-control text-right" })</td>
          </tr>
      </table>
    </div>
  6. In the Solution Explorer, right-click Pages -> Add -> Razor Page...
  7. In the Add New Sacffolded Item dialox box, make sure Razor Page - Empty is selected.
    Click Add
  8. Change the file Name to SSS
  9. Click Add
  10. Change the document as follows:
    @page
    @model ObliqueTriangles3.Pages.SSSModel
    @using static System.Console
    @{
        double side1 = 0.00, side2 = 0.00, side3 = 0.00;
        double angle1 = 0.00, angle2 = 0.00, angle3 = 0.00;
    
        if (Request.HasFormContentType)
        {
            try
            {
                side1 = double.Parse(Request.Form["txtSSSSide1"]);
            }
            catch (FormatException)
            {
                WriteLine("You must type a value for one of the known sides of the SSS shape.");
            }
    
            try
            {
                  side2 = double.Parse(Request.Form["txtSSSSide2"]);
            }
            catch (FormatException)
            {
                WriteLine("You must type a value for another side of the SSS triangle.");
            }
    
            try
            {
                side3 = double.Parse(Request.Form["txtSSSSide3"]);
            }
            catch (FormatException)
            {
                WriteLine("You must type a value for the remaining known side of the SSS oblique triangle.");
            }
    
            // Here, we use the law of cosines
            angle1 = Math.Acos(((side3 * side3) +
                                (side2 * side2) -
                                (side1 * side1)) /
                                (2 * side3 * side2)) * 180 / Math.PI;
                
            angle2 = Math.Acos(((side3 * side3) +
                                (side1 * side1) -
                                (side2 * side2)) /
                                (2 * side3 * side1)) * 180 / Math.PI;
          
            angle3 = 180 - (angle1 + angle2);
    
            WriteLine("======================================================================");
            WriteLine("Oblique Triangles - SSS Shape");
            WriteLine("======================================================================");
            WriteLine("Known Values: All 3 Sides");
            WriteLine("----------------------------------------------------------------------");
            WriteLine("Known Side    1:  " + side1.ToString());
            WriteLine("Known Side    2:  " + side2.ToString());
            WriteLine("Known Side    3:  " + side3.ToString());
            WriteLine("======================================================================");
            WriteLine("Unknown Values: All 3 Angles");
            WriteLine("----------------------------------------------------------------------");
            WriteLine("Unknown Angle 1:  " + angle1.ToString());
            WriteLine("Unknown Angle 2:  " + angle2.ToString());
            WriteLine("Unknown Angle 3:  " + angle3.ToString());
            WriteLine("======================================================================");
        }
    }
    
    <div class="delimiter common-font">
        <h2 class="text-center bold">Oblique Triangles - SSS  Shape</h2>
        <hr />
        <h5 class="text-right">Known Values: All 3 Sides</h5>
        <hr />
       <form name="frmGeometry" method="post">
          <table>
              <tr>
                  <td style="width: 300px" rowspan="3">
                      <img src="~/images/sss.png" width="259" height="137" alt="Oblique Triangles - SSS Shape">
                  </td>
                  <td style="width: 150px">Known Side 1:</td>
                  <td>@Html.TextBox("txtSSSSide1", @side1, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>Known Side 2:</td>
                  <td>@Html.TextBox("txtSSSSide2", @side2, new { @class = "form-control text-right" })</td>
              </tr>
              <tr>
                  <td>Known Side 3:</td>
                  <td>@Html.TextBox("txtSSSSide3", @side3, new { @class = "form-control text-right" })</td>
              </tr>
          </table>
          
          <hr />
                  
          <table>
              <tr>
                  <td style="width: 350px">&nbsp;</td>
                  <td style="text-align: center"><input type="submit" name="btnSubmit" value="Find Unknown Values" /></td>
              </tr>
          </table>
      </form>
    
      <hr />
      
      <h5 class="text-right">Unknown Values: All 3 Angles</h5>
      
      <hr />
      
      <table>
          <tr>
              <td style="width: 300px">&nbsp;</td>
              <td style="width: 150px">Unknown Angle 1:</td>
              <td>@Html.TextBox("txtSSSAngle1", @angle1, new { @class = "form-control text-right" })</td>
          </tr>
          <tr>
              <td>&nbsp;</td>
              <td>Unknown Angle 2:</td>
              <td>@Html.TextBox("txtSSSAngle2", @angle2, new { @class = "form-control text-right" })</td>
          </tr>
          <tr>
              <td>&nbsp;</td>
              <td>Unknown Angle 3:</td>
              <td>@Html.TextBox("txtSSSAngle3", @angle3, new { @class = "form-control text-right" })</td>
          </tr>
      </table>
    </div>
  11. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging
  12. Click the ASA link:

    Oblique Triangles - ASA

  13. Click the Known Angle 1 text box and type 131
  14. Click the Known Angle 2 text box and type 10
  15. Click the Known Side 1 text box and type 23

    Oblique Triangles - ASA

  16. Click the Find Unknown Values button:

    Oblique Triangles - SSS - The Hosting Window

    Oblique Triangles - ASA

  17. Click the SSS link

    Oblique Triangles - SSS

  18. Click the Known Side 1 text box and type 2.8
  19. Click the Known Side 2 text box and type 4.7
  20. Click the Known Side 3 text box and type 3.5

    Oblique Triangles - SSS

  21. Click the Find Known Values

    Oblique Triangles - SSS - The Hosting Window

    Oblique Triangles - SSS

  22. Close the window and return to your programming environment
  23. Start a new ASP.NET Core Web App named CompoundInterest2 that uses the .NET 6.0 (Long-Term Support). Uncheck the Configure For HTTPS check box
  24. In the Solution Explorer, expand wwwroot
  25. In the Solution Explorer, under wwwroot, right-click css -> Add -> New Item...
  26. In the left list of the Add New Item dialog box, under Visual C#, expand ASP.NET Core. Expand Web, and click Content
  27. In the middle list, click Style Sheet
  28. Change the file Name to CompoundInterest
  29. Press Enter
  30. Change the document as follows:
    body {
    }
    
    .bold        { font-weight:      bold;  }
    .text-right  { text-align:       right  }
    .delimiter   { margin:           auto;
                   width:            650px; }
    .top-bar     { border-bottom:    6px solid blue;
                   background-color: #5f2c19 !important; }
    .common-font { font-family:      Georgia, Garamond, 'Times New Roman', serif; }
    .navbar-light .navbar-brand       { color:       white;  }
    .navbar-light .navbar-brand:hover { color:       yellow; }
    .navbar-light .navbar-brand:focus { color:       khaki;  }
    .navbar-light .navbar-brand       { font-family: Georgia, Garamond, 'Times New Roman', serif; }
    .nav-link                         { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  31. In the Solution Explorer, expand Pages
  32. In the Solution Explorer, under Pages, expand Shared
  33. In the Solution Explorer, under Pages and under Shared, double-click _Layout.cshtml
  34. Change the document as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - Compound Interest</title>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
        <link rel="stylesheet" href="~/css/CompoundInterest.css" asp-append-version="true" />
    </head>
    <body>
        <header>
            <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3 top-bar">
                <div class="container">
                    <a class="navbar-brand" asp-area="" asp-page="/Index">Compound Interest</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                            aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/Index">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/Privacy">Privacy</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>
        <div class="container">
            <main role="main" class="pb-3">
                @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted">
            <div class="container">
                <p class="text-center common-font">&copy; 2022 - Compound Interest - <a asp-area="" asp-page="/Privacy">Privacy</a></p>
            </div>
        </footer>
    
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @await RenderSectionAsync("Scripts", required: false)
    </body>
    </html>
  35. In the Solution Explorer, under Pages, double-click Index.cshtml to open it

Clearing the Console

If the console screen is filled with text you don't need anymore, you can empty it. To allow you to clear the screen, the Console class is equipped with a method named Clear. It syntax is:

public static void Clear();

Practical LearningPractical Learning: Clearing the Console

  1. Change the Index.cshtml document as follows:
    @page
    @model IndexModel
    @{
        string strError          = "";
        string strFrequency      = "";
    
        double periods           = 0.00;
        double principal         = 0.00;
        double interestRate      = 0.00;
    
        string strFutureValue    = "0.00";
        string strInterestEarned = "0.00";
    
        if (Request.HasFormContentType)
        {
            try
            {
                principal = double.Parse(Request.Form["txtInitialValue"]);
            }
            catch(FormatException fe)
            {
                strError = "There was an error related to the Principal. The error is as follows: " + 
                            Environment.NewLine + fe.Message;
            }
    
            try
            {
                interestRate = double.Parse(Request.Form["txtInterestRate"]);
            }
            catch (FormatException fe)
            {
                strError = "The program produced an error related to the interest rate. The error was as follows: " +
                            Environment.NewLine + fe.Message;
            } 
    
            try
            {
                periods = double.Parse(Request.Form["txtPeriods"]);
            }
            catch (FormatException fe)
            {
                strError = "An error resulted from the value meant for the period. Please report the error as follows: " +
                            Environment.NewLine + fe.Message;
            } 
    
    
            double frequency   = 12.00;
            
            strFrequency = Request.Form["rdoFrequency"];
    
            switch (strFrequency)
            {
                case "Daily":
                    frequency = 365.00;
                    break;
                case "Weekly":
                    frequency = 52.00;
                    break;
                case "Monthly":
                    frequency = 12.00;
                    break;    
                case "Quaterly":
                    frequency = 4.00;
                    break;
                case "Semiannually":
                    frequency = 2.00;
                    break;
                case "Annually":
                    frequency = 1.00;
                    break;
            }
    
            double per            = periods / 100;
            double futureValue    = principal * Math.Pow((1.00 + (interestRate / frequency)), frequency * per);
            double interestEarned = futureValue - principal;
    
            strFutureValue        = $"{futureValue:F}";
            strInterestEarned     = $"{interestEarned:F}";
    
            System.Console.Clear();
            
            System.Console.WriteLine("======================================================");
            System.Console.WriteLine("Compound Interest");
            System.Console.WriteLine("======================================================");
            System.Console.WriteLine("Principal:        {0:f}", principal);
            System.Console.WriteLine("Interest Rate:    {0:f}%", interestRate);
            System.Console.WriteLine("Periods:          {0} years", periods);
            System.Console.WriteLine("------------------------------------------------------");
            System.Console.WriteLine("Future Value:     {0:f}", futureValue);
            System.Console.WriteLine("Interest Earned:  {0:f}", interestEarned);
            System.Console.WriteLine("======================================================");
        }
    }
    
    <h1 class="common-font text-center bold">Compound Interest</h1>       
    
    <hr />
    
    <form name="PayrollEvaluation" method="post" class="common-font delimiter">
    
    <h4>Compound Values:</h4>
    
    <hr />
        <table>
            <tr>
                <td style="width: 150px">@Html.Label("txtInitialValue", "Principal:", new { @class = "bold" })</td>
                <td>@Html.TextBox("txtInitialValue", @principal, new { @class = "form-control" })</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>@Html.Label("txtInterestRate", "Interest Rate:", new { @class = "bold" })</td>
                <td>@Html.TextBox("txtInterestRate", @interestRate, new { @class = "form-control" })</td>
                <td>%</td>
            </tr>
            <tr>
                <td>@Html.Label("txtPeriods", "Periods:", new { @class = "bold" })</td>
                <td>@Html.TextBox("txtPeriods", @periods, new { @class = "form-control" })</td>
                <td>years</td>
            </tr>
        </table>
    
        <hr />
    
        <h4>Compound Frequency:</h4>
    
        <hr />
    
        <table>
            <tr>
                <td style="width: 100px"><label for="rdoDaily">Daily</label></td>
                <td><input type="radio" id="rdoDaily" name="rdoFrequency" value="Daily" /></td>
                <td style="width: 50px">&nbsp;</td>
                <td style="width: 100px"><label for="rdoQuaterly">Quaterly</label></td>
                <td><input type="radio" id="rdoQuaterly" name="rdoFrequency" value="Quaterly" /></td>
            </tr>
            <tr>
                <td><label for="rdoWeekly">Weekly</label></td>
                <td><input type="radio" id="rdoWeekly" name="rdoFrequency" value="Weekly" /></td>
                <td>&nbsp;</td>
                <td><label for="rdoSemiannually">Semiannually</label></td>
                <td><input type="radio" id="rdoSemiannually" name="rdoFrequency" value="Semiannually" /></td>
            </tr>
            <tr>
                <td><label for="rdoMonthly">Monthly</label></td>
                <td><input type="radio" id="rdoMonthly" name="rdoFrequency" value="Monthly" /></td>
                <td>&nbsp;</td>
                <td><label for="rdoAnnually">Annually</label></td>
                <td><input type="radio" id="rdoAnnually" name="rdoFrequency" value="Annually" /></td>
            </tr>
        </table>
    
        <hr />
    
        <table>
            <tr>
                <td style="width: 150px">&nbsp;</td>
                <td><input type="submit" value="Evaluate Compound Interest" name="btnCalculate" style="width: 250px" /></td>
            </tr>
        </table>
    
        <hr />
        
        <table>
            <tr>
                <td style="width: 200px" class="bold">Compound Frequency:</td>
                <td style="text-align: right">@strFrequency</td>
            </tr>
            <tr>
                <td class="bold">Future Value:</td>
                <td style="text-align: right">@strFutureValue</td>
            </tr>
            <tr>
                <td class="bold">Interest Earned:</td>
                <td style="text-align: right">@strInterestEarned</td>
            </tr>
        </table>
    </form>
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Compount Interest

  3. Click the Principal text box and type 12668.74
  4. Click the Interest Rate text box and type 10.85
  5. Click the Periods text box and type 4

    Compount Interest

  6. Click each of the radio buttons and click the Evaluate Compound Interest button:

    Compount Interest

    Compount Interest

    Compount Interest

    Compount Interest

  7. Close the browser and return to your programming environment, press Enter

Formatting Data Display

Introduction

Instead of using two Write() methods or a combination of theWrite() and the WriteLine() methods to display data, you can convert a value to a string and display it directly. To do this, you can provide two sections to the Write() or the WriteLine() methods and separate them with a comma:

  1. The first part is the first argument to the Write() or the WriteLine() method. Normally, this argument is passed as a string that would display to the user. This string argument can itself be made of different sections:
    1. One section is a string in any way you want it to display
    2. Another section is a number included between an opening curly bracket "{" and a closing curly bracket "}". This combination of "{" and "}" is referred to as a placeholder
      You can put the placeholder anywhere inside the string. The first placeholder must have number 0. The second must have number 1, and so on. With this technique, you can create the string anyway you like and use the placeholders anywhere inside the string
  2. The second section of the arguments passed to the Write() or the WriteLine() method is one or more values you want to display. It can be one value if you used only one placeholder with 0 in the first string argument. If you used different placeholders, you can then provide a different value for each one of them in this second part, separating the values with a comma

Here are examples:

@{
    var fullName = "Anselme Bogos";
    var age = 15;
    var hSalary = 22.74;

    Console.WriteLine("Full Name: {0}", fullName);
    Console.WriteLine("Age: {0}", Age);
    Console.WriteLine("Distance: {0}", hSalary);
}

This would produce:

Full Name: Anselme Bogos
Age: 15
Distance: 22.74

As mentioned already, the numeric value typed in the curly brackets of the first part is an ordered number. If you want to display more than one value, provide each incremental value in its curly brackets. The syntax used is:

Write("To Display {0} {1} {2} {n}", First, Second, Third, nth);

You can use the sections between a closing curly bracket and an opening curly bracket to create a meaningful sentence.

Conversion To String

We mentioned earlier that everything the user types using the keyboard is primarily a string and it's your job to convert it to the appropriate type. In reverse, if you have a value that is not a string, you can easily convert it to a string. To support this, the .NET Framework structure of each data type is equipped with a method named ToString. Normally, in C#, as we have done so far, this conversion is automatically or transparently done by the compiler. In some cases, you will need to perform the conversion yourself.

To convert a value of a primitive data type to a string, type the name of the variable, followed by a period, followed by ToString(). Here is an example:

@{
    string fullName = "Anselme Bogos";
    int age = 15;
    double hSalary = 22.74;

    Console.WriteLine("Full Name: {0}", fullName);
    Console.WriteLine("Age: {0}", age.ToString());
    Console.WriteLine("Distance: {0}", hSalary.ToString());
}

In some cases, you will type something in the parentheses of ToString().

Number Formatting

To properly display data in a friendly and most familiar way, you can format it. Formatting tells the compiler what kind of data you are using and how you want the compiler to display it to the user.

The System namespace provides a specific letter you can use in the Write() or WriteLine()'s placeholder for each category of data to display. To format a value, in the placeholder of the variable or value, after the number, type a colon and one of the appropriate letters from the following table. If you are using ToString(), then, in the parentheses of ToString(), you can include a specific letter or combination inside of double-quotes. The letters and their meanings are:

Character Description
c C Currency values
d D Decimal numbers
e E Scientific numeric display such as 1.45e5
f F Fixed decimal numbers
d D General and most common type of numbers
n N Natural numbers
r R Roundtrip formatting
s S Hexadecimal formatting
p P Percentages

Here are examples:

@{
    var Distance = 248.38782;
    var age = 15;
    var NewColor = 3478;
    var hSalary = 22.74;
    var HoursWorked = 35.5018473;
    var WeeklySalary = hSalary * HoursWorked;

    Console.WriteLine("Distance: {0}", Distance.ToString("E"));
    Console.WriteLine("Age: {0}", age.ToString());
    Console.WriteLine("Color: {0}", NewColor.ToString("X"));
    Console.WriteLine("Weekly Salary: {0} for {1} hours",
                          WeeklySalary.ToString("c"),
              		      HoursWorked.ToString("F"));
}

This would produce:

Distance: 2.483878E+002
Age: 15
Color: D96
Weekly Salary: $807.31 for 35.50 hours

As you may have noticed, if you leave the parentheses of ToString() empty, the compiler would use a default formatting to display the value.

As opposed to calling ToString(), you can use the above letters in the curly brackets of the first part of Write() or WriteLine(). In this case, after the number in the curly brackets, type the colon operator followed by the letter.

Line Formatting

In the above programs, to display a line of text, we easily used Write() or WriteLine(). To position text of different lengths one above the other, we had to "corrupt" a string by including extra-empty spaces. Such a technique is uncertain and less professional. Fortunately, you can format how a string or a line of text should display. The .NET Framework provides mechanisms to control the amount of space used to display a string of text and how to align that string on its line.

To specify the amount of space used to display a string, you can use its placeholder in Write() or WriteLine(). To do this, in the placeholder, type the number or the variable in the curly brackets. Then, type a comma followed by the number of characters equivalent to the desired width. Here are examples:

@{
    string fullName = "Anselme Bogos";
    int age = 15;
    double hSalary = 22.74;

    Console.WriteLine("Full Name: {0,20}", fullName);
    Console.WriteLine("Age:{0,14}", age.ToString());
    Console.WriteLine("Distance: {0:C,8}", hSalary.ToString());
}

This would produce:

Full Name:        Anselme Bogos
Age:            15
Distance: 22.74

The sign you provide for the width is very important. If it is positive, the line of text is aligned to the right. This should be your preferred alignment for numeric values. If the number is negative, then the text is aligned to the left.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2022, FunctionX Friday 26 November 2021 Next