(vs-community)=
# Visual Studio 2022 Community 

We'll now setup Visual Studio 2022 Community, which we'll refer to as *VS*.

For the following tutorial I used a computer with an Intel x86-64 bit processor with Windows 11 OS build 26100 (refer to `System Information`). Even the following steps should also work for other processors like ARM, I could not test.

[VS does not support macOS](https://learn.microsoft.com/en-us/visualstudio/releases/2022/what-happened-to-vs-for-mac). You can use [VirtualBox](https://www.virtualbox.org/) and use Windows as a virtual machine on macOS.


## Installation

1. Open `Microsoft Store`.
1. Search for `Visual Studio` and select `Visual Studio Community 2022` (*not* `Visual Studio Code`). A purple white installation page will show up.
1. Click on install. It will download the installer which is few MB. A `User Account Control` window will pop up and ask for permission.
1. Click `Yes`. `Visual Studio Installer` window will pop up.
1. Click `Continue`. The installer will start downloading components. In the end, a new window `Installing - Visual Studio Community ...` will pop up and will then show you installable components called `Workloads`.
1. Scroll down `Desktop & Mobile` and make a tick on `.NET desktop development`. On the right, `Installation details` should show up.
1. Leave the default components active. Click on `Install`. The installer will start downloading and installing. It took about 10 minutes on my computer. Look into [Introduction C#](https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/hello-world) until the installation ends.

   After the installation a window with `Sign in to Visual Studio` should pop up.
1. You can close the `Visual Studio Installer` and `Microsoft Store` window.
1. Go back to the VS. We will organize our code on repositories and also experiment with GitHub Copilot. So, click on `Sign in with GitHub`. A web-browser will pop up. Login with your credentials or create an account.

1. During login, GitHub will ask you for permissions to exchange data with VS. Accept them. The web-browser will forward you to VS again and you will see `Personalize your Visual Studio experience`.
1. You can close the formerly opened web browser window.
1. Go back to VS. Click on the `Development settings` drop-down menu and select `Visual C#`.

   Pick a color theme that fits your environment and your taste. [A study](https://doi.org/10.1111/tgis.13038) found out that a light theme is best in a well-lit environment during the day, and dark during the night. 

1. Click on `Start Visual Studio`. A welcome window should pop up with `Open recent` and `Get started`.

## Creating a project

1. On the welcome window, click `Create a new project`. A list of templates will show up.
1. Double click on `Console App`, which should be the first one on the list.
1. We will create an online currency converter. Name the project `CurrencyConverter`.
1. Activate `Place solution and project in the same directory`. This will create less directories which is more convenient for small projects for us as beginners.
1. Click on `Next`. `Additional information` window will show up.
1. You can leave the three settings in their defaults. 

   :::{dropdown} If you are curious about these settings:
   1. Typically every .NET version comes with new language features. The framework can stay at the default, because we don't need the latest language features as beginners.
   1. `Do not use top-level statements`: Top-level statements are in contrast to object-oriented programming (OOP). In short, top-level statements allow us to write minimal code, but OOP is more modular. We will introduce these concepts later in detail. We don't activate this, because we will also use top-level statements.
   1. `Enable native AOT publish`: AOT stands for *ahead of time compilation*. Typically Visual C# programs are translated to an intermediate language, which is then translated to machine code first time the program is run. AOT may lead to more efficient programs in resource-constrained computers and we don't need this feature in our case.
   :::
1. Click on `Create`. A progress window will pop up and after that the editor window with `Program.cs` containing a hello-world program.

## Running a program with debugging features

We will introduce the term *debugging* later.

1. Click on ![green play button](https://learn.microsoft.com/en-us/visualstudio/extensibility/ux-guidelines/media/0405-03_actionmodifierrun.png){h=20px} `CurrencyConverter` on the toolbar or <kbd>F5</kbd>. 

   This step will start the compiler which translates the code to a format that can be executed by our computer. It will be run with debugging features, which we will talk about in a bit. After the compilation is done, the program will be executed automatically. Then we will see the message `Hello, World!` printed by our program.

console application
: a program designed to be used via a text-only user interface

We will use console applications for learning fundamental programming concepts, because a console application has less complexity compared to a graphical user interface (GUI). Later we will also create GUIs.

compiler
: a computer program that translates program code written in one programming language into another

Our program has finished running at this point.

## Debugging a program

debugging
: the process of finding the causes and possible fixes for bugs

When our programs get more complicated, debugging will be very useful to find the bugs. In debugging mode, the code will pause at the program line where the first error happened at will give us the opportunity, e.g., which values the variables have to inspect the *crime scene* like a detective 🕵️.

To learn how debugging works, copy the following code and replace `Program.cs` on your editor:

:::{code-block} csharp
:linenos:

Console.WriteLine("Before");
int[] numbers = [1, 2, 3];
Console.WriteLine(numbers[5]);
Console.WriteLine("After");
:::
1. Press <kbd>F5</kbd>
1. The program should stop at third line. VS is in debugging mode and will show you actions like ⤍/ (show next statement), {{stop}} (stop debugging).

   VS should show you the error cause `Index was outside the bounds of the array.`.
   
   How can this happen? Let us overlook for a moment that we initialized the array with three elements for the sake of demonstrating the debugger. An idea is that we check the content of the array `numbers`, *exactly at the time* when the error happened. 

   :::{figure} ../img/debugging-numbers-array.png
   :name: debugging-numbers-array
   :align: right
   :figwidth: 40%
   When we hover our mouse over a data structure in debugging mode, we can see information about its contents. When we click on the > symbol, we can further expand and see actual contents.
   :::

   This is a superpower of a debugger: we can *pause* our program and inspect contents of data structures, or *computer memory* in general. In this case, our program was automatically paused by the debugger.

1. Hover your mouse over `numbers` in the editor, you see first the size of the array as in {numref}`debugging-numbers-array` and if you expand using the > symbol, you see its contents.

   We see that the array has three elements with indexes 0, 1, and 2. However we used the index 5 which does not exist. We can fix our code by adding more elements to the array or using an index of an existing element, e.g., 2.
1. Stop debugging by using {{stop}}.
1. Change the index from 5 to 2 and restart the debugger by pressing <kbd>F5</kbd>.

   You will see that our program runs and exists without any errors.

## Running a program without debugging features

There is a second option to start our program – without debugging.

1. On the right of the last button, you will see another play button <span style="color: green;">▷</span>, which stands for `Start Without Debugging`. 

  Our program will start faster and execute probably also faster in this mode, because debugging features also affect performance.

1. Close the console by pressing a key. You should be back on your editor.

We don't care about performance for now and can simply use <kbd>F5</kbd> for starting our program. When we start a typical program on our operating system, it is started without debugging features.

## Saving our code on a repository

Now we will learn how to store our code on a repository primarily for keeping a diary about our work and sharing it.

repository
: (in context of version control systems) a data structure that stores metadata for a set of files or directory structure. The main purpose of a repository is to store a set of files, as well as the history of changes made to those files.

version control
: the software engineering practice of controlling, organizing, and tracking different versions in history of computer files; primarily source code text files, but generally any type of file.

Keeping a history of changes is helpful if we or someone else who also work in the project would like to understand changes in the project which is useful for *collaboration*. Keeping a history helps also to roll changes back if something does not work as intended.

Keeping projects in a repository is also helpful to collaborate and share code. You will use it later to share or submit your projects. You maybe already downloaded something from the code forges [GitHub](https://github.com), [GitLab](https://gitlab.com), or [Codeberg](https://codeberg.org), where GitHub is the most popular one and on which most of the open source projects in the world are organized.

code forge
: a web interface to a version control system

We had already logged in on GitHub with VS, so let us create our first repository on GitHub.

1. On the right you should see a sidebar with the title `GitHub Copilot Chat`. On the bottom of that sidebar, click on the tab `Git Changes`. You should now see `Git Changes tab`.
1. Click on {{git}} `Create Git Repository`. A new window with the same name will pop up.
1. If you want to share your project, e.g., for submitting homework using a URL:

   - activate `Add a README.md` to add information about your project.
   - Change visibility to `Public`.
1. Click `Create and Push`. You may be asked whether you want to save your files before pushing.

   During this process your repository will be created.

   If you get the error `error setting cerificate file: ...`, refer to [here](project:#vs-error-during-git-create-and-push).

   If you want to push your code again, e.g., in case of an error, then use ⬆️ on the Git bar.

   If successful, you should see `ℹ️ Successfully pushed ...`.

1. Now check how your pushed code look like on the code forge GitHub by clicking on `...` on the `Git changes` bar and clicking on `Open in Browser` or simply browsing `https://github.com/*YOUR-USERNAME*/CurrencyConverter`.

   You should see something similar to:

   ```text
   user and user  Add project files.   ... 2 Commits

   .gitattributes
   .gitignore
   CurrencyConverter.csproj
   CurrencyConverter.sln
   Program.cs
   README.md
   ```

   - Files beginning with `.git` are for Git configuration. These are templates from VS that we don't need to understand right now.
   - `*.csproj` and `*.sln` are project and solution files. VS takes care of them when we save our project.
   - `Program.cs` is our source code
   - `README.md` contains information about our project that we will fill with info later.

source code
: a plain text computer program written in a programming language

README
: contains info about files in a directory of computer software. It is a form of documentation.

On GitHub, click on the `2 Commits`.

:::{tip}
If you cannot find a word or identifier from this tutorial immediately on the web page, use <kbd>Ctrl</kbd><kbd>f</kbd> to search for it.
:::

changeset
: list of differences between two successive versions in a repository

commit
: the operation of committing such a changeset to the repository

VS automatically created two *commits* and added some information message to each commit. When we use repositories we make our changes in *commits*.

Ideally each commit should be a set of changes that adds one or many describable feature like *improved user name handling* or *added robot program*. The advantage is that the programmer can roll back changes if these features led to problems later. Sometimes people don't want to put so much structuring work and use a repository as a *diary* and commit code at the end of the day, which is not a good practice in a professional environment.

You see that the commits are associated with `user` which should be the username of your operating system account. Let us change it to our GitHub username:
1. Click on the top menu on `Git` -> ⚙️ `Settings`. `Options` window should pop up.
1. Enter your GitHub username and email.
1. To test, make a small change in your code like adding a new line to your code (<kbd>Enter</kbd>).
1. Now save your file using <kbd>Ctrl</kbd><kbd>s</kbd>. You should see a change on the `Git bar` in the `Changes` list. This will list your changes compared to the last commit.
   
   Without any change, we cannot create a commit
1. On the `Git Changes` bar, write a test message like `testing new username` onto the box `Exter a message`.
1. Click on `Commit All`. You should see `Commit ... created locally`, which means that we created a commit on our local project, but the code forge is not aware of our changes right now.

   If you see `ℹ️ Nothing to commit`, then you probably did not change any file.
   :::{figure} ../img/github-testing-new-username.png
   :align: right
   :name: github-testing-new-username
   :figwidth: 30%
   GitHub commit after setting the username correctly
   :::
1. Click on ⬆️ to synchronize our repository with the repository on the code forge GitHub.
1. Check the commits on your web web browser. Now you should see your username like in {numref}`github-testing-new-username`.

:::{margin}
More on [Git with VS](https://learn.microsoft.com/en-us/visualstudio/version-control/git-with-visual-studio)
:::

## Improvement suggestions with the Screwdriver ({{screwdriver}}) and traditional C# style
 
:::{figure} ../img/screwdriver-on-currencyconverter-code.png
:align: right
:name: screwdriver-on-currencyconverter-code

Screwdriver gives typically improvement suggestions
:::
On the default template code, you should see the screwdriver icon {{screwdriver}} on the top. This gives you typically improvement suggestions that you can use as seen in {numref}`screwdriver-on-currencyconverter-code`.

1. Click on the {{screwdriver}} and click on the suggestion about `Convert to 'Program.Main' style program`. You will see additional code that wraps the original code as follows:

   ```csharp
   internal class Program
   {
      private static void Main(string[] args)
      {
         Console.WriteLine("Hello, World!");
      }
   }
   ```
1. Press <kbd>F5</kbd>. You should see the same program output.

This is the traditional C# code that shows the actual structure of a top-level program. *Top-level* means the entry point (to the program) – the functions that first get executed when we start a program.

Actually `Console.WriteLine` line is enough to have the same behavior. But why would you write code that serves no functional purpose? As long as we don't have to use this functionality somewhere else, there is no need to write class declarations. But as software evolves with time, this functionality may become a component of a more complex program, which means that the top-level may change. In this case we have to introduce such a class structure. Nevertheless, we will prefer top-level statements to traditional top-level C# code to simplify our code.

If you encounter C# code on the internet, you may see both versions, so it is important to know the difference.

Last but not least, *suggestions* may not always *improve* your code. So be critical.

:::{margin}
More on [quick actions](https://learn.microsoft.com/en-us/visualstudio/ide/quick-actions)
:::

## A currency converter with input & Code style

Let us finally try a more meaningful program — a currency converter. We will also talk about code style.

Replace `Program.cs` with the following:

:::{code-block} csharp
:emphasize-lines: 1-3,7
:linenos:

using System.Text.Json;var client=new HttpClient ( );
string json= 
await client.GetStringAsync("https://api.frankfurter.dev/v1/latest?base=DKK");
var dkk_in_eur = JsonDocument.Parse(json).RootElement.GetProperty("rates").GetProperty("EUR").GetDouble();

Console.WriteLine(      $"1 DKK = {dkk_in_eur} EUR");
Console.Write("Enter amount in DKK: ");

var dkk_amount = Convert.ToDouble(Console.ReadLine());
var eur_amount = dkk_amount * dkk_in_eur;
Console.WriteLine($"{dkk_amount} DKK = {eur_amount:F2} EUR");
:::

1. Run the program using <kbd>F5</kbd>.
1. Try the program with an input.

Now let us speak about code style. Look at the highlighted lines. Does something catch your eye? Think about it some seconds before you continue.

If you have the feeling that the code is not easy to read, then you are on the right track! When we write ordinary text, then we pay attention that the words that belong to a sentence belong to the same line unless we continue on the next line as follows:
```text
The program converts between DKK and EUR.
```
Now look at the following:
```text
The
program
converts
between DKK and EUR.
```
Both text have the same meaning, but the former is more readable. When we write programs we also pay attention to *programming style*.

programming style
: also known as *coding style*, are the conventions and patterns used in writing source code, resulting in a consistent and readable code

Some style mistakes in the first lines are:

1. A typical statement ends with a semicolon `;`. Every statement is typically on a separate line.
1. We use spaces around `=`, e.g., `a = b `
1. We don't leave spaces after a function name and between empty parentheses: `HttpClient()`.
1. We typically separate lines that logically do not belong together, e.g.,:

   ```csharp
   using System.Text.Json;

   var client = new HttpClient();
   ```

   Additionally we could also separate `Console.WriteLine` functions for better readability, as they print something on the terminal. 

   A similar analogy would be writing *paragraphs* in written text.

We humans may not behave consistently and make mistakes but machines typically do more consistent work. Fortunately, editors can automatically format the code for us:

1. Click on the first line. An icon similar to {{lightbulb}} should appear in the beginning of the line. Click on {{lightbulb}}, then a menu will come up.

1. Click on `Fix Formatting`. You will see that most of the style issues are fixed, but not all. The formatter cannot understand everything in our code, so we have to still may attention to writing "paragraphs" in our code.

Instead of formatting our code every time manually, let us format our code whenever we save our project:

1. `Tools` -> `Options` -> `Text Editor` -> `Code Cleanup`
1. Activate `Run Code Cleanup profile on Save` and click on `OK`.
1. Save your document <kbd>Ctrl</kbd><kbd>s</kbd>. You should see that the formatting on line 7 is fixed too.

## Using Copilot as an assistant

A LLM (large language model) can support us better than editor assistance tools during coding, because a LLM can have a deeper understanding. As an example, we will use the LLM agent Copilot for formatting and explaining the code.

1. On the bottom of the right bar, click on the `GitHub Copilot Chat`.
1. Ask Copilot: `format code`. Here is the output from ChatGPT 4.1:

   ```csharp
   using System.Text.Json;

   var client = new HttpClient();
   string json = await client.GetStringAsync("https://api.frankfurter.dev/v1/latest?base=DKK");
   var dkk_in_eur = JsonDocument.Parse(json)
       .RootElement
       .GetProperty("rates")
       .GetProperty("EUR")
       .GetDouble();

   Console.WriteLine($"1 DKK = {dkk_in_eur} EUR");
   Console.Write("Enter amount in DKK: ");
   var dkk_amount = Convert.ToDouble(Console.ReadLine());
   var eur_amount = dkk_amount * dkk_in_eur;
   Console.WriteLine($"{dkk_amount} DKK = {eur_amount:F2} EUR");
   ```

   We see that ChatGPT not only added a nice wrapping on the fifth line (VS can also do this with {{lightbulb}}, but it is manual anyway) but also separated our code logically by separating the header (`using System...`), getting and parsing the data (second block) and outputting the data (last block).

1. Apply these suggestions by clicking `Apply` on the top of the suggestions. VS may ask you to accept some changes with <kbd>Tab</kbd>.
1. Try the program again to be sure that it still works.

You probably used ChatGPT for explaining you things. Let us try the AI agent too.

1. Ask Copilot: `this is my first programming language. explain me the code`. You should see explanations line by line.

:::{tip}
One of the learning goals of this course is to identify and explain core programming concepts *without a GPT* to be able to criticize the output of a GPT. I recommend you to write the programs yourself and ask the GPT as a second step only for getting feedback, improvements or explanations.
:::

Lastly let us finish this project for now by writing minimal documentation to `README.md` and committing our changes:

1. On the bottom of the right bar, click on `Solution Explorer tab. Open `README.md`.
1. Under the title `# CurrencyConverter`, write, e.g., `An online currency converter from DKK to EUR.`
1. Save `README.md`.
1. Go to the `Git Changes` tab.
1. Try to think about a message which summarizes your commit before you continue to read.

   I came up with: `initial currency converter`

   Now try generating a commit message using Copilot by pressing the pen icon similar to 🖊️. I got the following message:

   > Add DKK to EUR conversion functionality
   > 
   > Updated `Program.cs` to implement currency conversion from Danish Krone (DKK) to Euro (EUR) using an external API. The program now fetches exchange rates, prompts the user for an amount in DKK, and displays the equivalent amount in EUR. 
   >
   > Modified `README.md` to include a description of the program as an online currency converter.

   This is more detailed and correct. You have to choice whether you accept it or not.

1. Commit your changes.
1. Push your changes.

(vs-error-during-git-create-and-push)=
## VS: Error during Git `create and push`: `error setting certificate file ...`

The problem could be that you have a `gitconfig` from a previous Git installation in `Program Files/Git`. Delete this folder as a solution.

The whole error message is here:

```
Git failed with a fatal error.
unable to access ...
error setting certificate file: C:/Program Files/Git/mingw64/etc/ssl/certs/ca-bundle.crt
```
