Laboratory 4

by Paweł Paduch published 2022/10/28 15:36:00 GMT+2, last modified 2023-10-17T14:41:31+02:00
Introduction to C#
  1. First steps in VS (0.5 points)
    • Start Visual Studio
    • Create a new project
      image.png
    • Select the .net core console application
      image.png
    • Set the project name to HelloWorld and the solution name to Lab01 the rest can be left by default
      image.png
    • Make sure your version is .net core 3.1 (or newer)
      image.png
    • As you can see the application wrote itself :)
    • You can run it by pressing F5 key.

  2. Code overview and various launch attempts. (0.5 points)
    • using System;
      
      namespace HelloWorld
      {
          class Program
          {
              static void Main(string [] args)
              {
                  Console.WriteLine("Hello World!");
              }
          }
      }
      
    • At the very top of the source code we have defined the namespaces used. In this case, System. This is where we find the Static Console class. Without it, any use of Console class would require us to write the prefix System.
      • Remove the "using" line and try compiling (F5).
      • Add the System prefix. to the Console.
        You can write it manually or use a hint (expand the bulb symbol):
        image.png
      • The clue indicates 4 solutions. Let's choose the latter - the System.
      • prefix
      • As you can see the error has disappeared, but the next reference to classes in the System namespace will require us to enter the System prefix. Therefore it is more convenient to specify it once with "using" at the begining of the file.
    • When there is a naming conflict (eg identical class name in two different namespaces) the full prefix or alias can be used. e.g. using s = System; and then  You can type s.Console
    • Our project also has its "HelloWorld" namespace. When writing a library project, you can refer to classes contained in it using the prefix HelloWorld or use using HelloWorld.
    • The proper declaration of classes and variables is in the namespace.
    • Console programs must have a static Main method called when the program starts. This method has a string array parameter as args.
    • Console.WriteLine ("text") prints the given string to text.
    • Find the directory on the disk where the walkthrough was created.
    • Go to the directory HelloWorld/bin/Debug/netcoreapp3.1
    • There you will find the compiled program with configuration files
    • Run HelloWorld.exe by double clicking (the program will start and close).
    • In the system bar, click search and enter cmd.
      image.png
    • Run Developer Command Prompt for VS
    • Copy the directory location from the explorer's file bar and run cd < path to the directory >
      image.png
    • Run HelloWorld.exe
    • Now as you can see it is actually displayed.

  3. Passing parameters and simple constructions. (0.5 points)
    • Position the cursor below the line saying Hello World and type "fore". Note that intelisence prompts you to expand this word to foreach. image.png
    • Press the TAB key twice to auto-generate the code for the field loop. In the event that the "clue" disappears, you can reactivate it by "ctrl + Space" combination
      image.png
    • You can set the data type of the collection, the iterator name, and point to the collection. Use the TAB key to switch between the individual fields.
      Complete the loop code with writing out particular arguments
       foreach (string arg in args)
                   {
                   Console.WriteLine($ "Argument: {arg}");
                    } 
    • Right click on the Hello World project in the Solution Explorer panel and start rebuild
      image.png
    • Re-open the location HelloWorld.exe from developer console or commands (cmd) and run the program as follows:
      HelloWorld.exe Ala has a cat
      Hello World !
      Argument: Ala
      Argument: has
      Argument: cat
    • Use the context menu to open the properties of the HelloWorld project (or Alt + Enter) go to the "Debug" tab and enter your arguments in the Application arguments field.
      image.png
    • Run the program in debug mode (F5)
    • Instead of Hello World, display the number of arguments supplied by the user. You can use the args.Length
    • property
    • Add variable declaration of type int: int counter = 0; In addition to the value of the argument, print the value of the counter, with post-increment at the same time (counter ++);

  4. Debug (0.5 points)
    • Position yourself on the line with the output of the argument number and value and press F9. You can also click in the left margin area to add a break point.
      image.png
    • Run in debug mode (F5)
    • The program will stop and we can preview the values ​​of the variables by pointing the mouse to the values ​​we are interested in:
      image.png
    • Follow the program step by step to F10 or enter method (F11). Continue to next breakpoint F5
    • By right-clicking on the counter variable we can add the variable tracking in the "Watch" window.
      image.png

      image.png
    • Right click on break point and select "conditions"
    • from the context menu
    • image.png
    • There we put a stop condition at the given break point counter == 2
    • We run the program with F5 and check the value of the counter on the first stop.

  5. Downloading data (0.5 points)
    • In the solution explorer, select Add / New Project
    • from the context menu for the solution
    • Add a console application named MultiplicationTable
    • From the context menu of the new project, set the default startup project:
      image.png
    • Declare the two variables xMax and yMax of integer type.
    • Declare two variables of type xStr and yStr.
    • Use Console.WriteLine to print the prompt for the entry of the value x
    • Use Console.ReadLine() to read the user entered string.
    • Using the static int.TryParse method, try to convert the string into an integer value int.TryParse(xStr, out x)
    • We get true / false back. Check with the if statement if the conversion was successful, otherwise give an error message.
    • Get yStr from the user
    • Convert yStr to y with int.Parse.
    • Run the program with incorrect data (eg letters instead of numbers).
    • In the second case we will get an exception
      image.png
    • Put the parsing part in a try catch
      block
       try
              {
                  y = int.Parse(yStr);
              }
      catch (FormatException fe)
              {
                  Console.WriteLine("Oh no!" + Fe.Message);
              }
      finally
              {
                  Console.WriteLine("something else");
              } 
    • The catch part is executed when we catch an exception of the specified type
    • Add the following functionality to the above project:
      • user specifies the maximum size of the multiplication table
      • A tag of the given size is displayed
      • Use.
      • for this task
        • double for loop,
        • formatted (up to 2 digits) display of numbers {number: d2},
        • printing without breaking Console.Write lines
      • The effect should look something like this:
        image.png

  6. New class (0.5 points)
    • From the project context menu (in the solution explorer) select Add / New Item and select Class there (you can also use the Add / New Class shortcuts)
    • Give the name of the FormField
      image.png
    • Implement the Field method as follows:
       namespace MultiplicationTable
      {
      public static class FormatField
      {
      public static string Field(int number, int width)
      {
      return number.ToString().PadLeft(width) + "|";
       }
      }
      } 
    • Use FormatField.Field for formatting.

  7. New library (0.5 points)
    • Add a new class library project to the walkthrough
      image.png
    • Let's call it TableCreatorLib
    • Select the code Class1.cs and rename it (F2) to TableCreator
      image.png
    • Visual will also propose to rename the class. We agree.
    • We implement the class in accordance with the following:
       using System;
      using System.Linq;
      
      namespace TableCreatorLib
      {
          public class TableCreator
          {
              private int[,] table;
              private int x, y;
              public int Count {get; private set; }
              public TableCreator(int x, int y)
              {
                  Count = 0;
                  this.x = x;
                  this.y = y;
                  table = new int[x, y];
              }
              public bool AddItem(int item)
              {
                  if (Count >= x * y) return false;
                  table[Count%x, Count/x] = item;
                  Count ++;
                  return true;
              }
      
              public void PrintTable()
              {
                  int maxValue = table.Cas <int>().Max();
                  int maxLength = maxValue.ToString().Length;
                  for (int i = 0; i < y; i++)
      {
                          for (int j = 0; j < x; j++)
      {
      Console.Write(table[j, i].ToString().PadLeft(maxLength) + "|");
      }
                           Console.WriteLine();
      }
              }
          }
      } 
    • In the MultiplicationTable project we add a reference to the new library
      image.png

      image.png
    • We will use the TableCreatorLib library to collect and display the table.
    • Modify giving code to display the table so as to add the counted items to the TableCreator(tc) at the same time.
    • TableCreator counts its maximum value and adjusts the formatting depending on it. Call examples:
      image.png

  8. Independent task (1.5 points)
    • Create a new solution in which you will include a console .net core project and a library project.
    • In the library there should be a class that creates a Fibonacci sequence (the next element of the string is the sum of the previous two)
    • A class should have a constructor with a parameter to which element the string should be counted.
    • There should be two methods in the class, Print and Get . Print will print the string to the screen. Get will get the string as list int .
    • In a console project, Demonstrate how the library works. So get some value from the user, create an object of our class and call appropriate methods.