###### tags: `Back-end`,`Restful API`,`ASP.NET CORE`,`AON` # Week 01 - Introduction & C# Basics # Introduction Welcome to this comprehensive course where you will learn to build modern, scalable restful api apps using the following: - **ASP.NET Core** for building efficient, RESTful APIs. - **SQLite/SQL** for database management. ## What You’ll Learn ### 1. **Web Apps Overview & Setup** - Introduction to modern web apps, tools, and setting up environments for .NET Core. ### 2. **C# Basics & OOP Refresher** - Core C# concepts (variables, loops, methods) and key OOP principles (classes, inheritance, encapsulation). ### 3. **ASP.NET Core APIs & CRUD** - Building RESTful APIs with ASP.NET Core. - Understanding the MVC structure and implementing CRUD operations. ### 4. **Repository Pattern & Data Layer** - Using the Repository Pattern for clean data access and managing API-database interactions. ### 5. **SQL & SQLite** - SQL basics and why we use **SQLite**: lightweight and ideal for learning. - Introduction to Entity Framework for database management. ### 6. **Security** - Implementing authentication, authorization, encryption, and securely handling sensitive data. ### 7. **Middleware & Logging** - Creating custom middleware and setting up logging to monitor applications. ### 8. **Deployment** - Deploying your ASP.NET Core API to a real server. ### 9. **Postman Collection** - Creating Postman collections for API testing and sharing with front-end developers. # Web Apps - High Level Overview ![API-Gateway-Diagram](https://hackmd.io/_uploads/HyGnbaaCA.png) In any web or mobile application, the back-end API is like the brain of the operation. It processes data, handles requests, and ensures that everything works smoothly behind the scenes. - **Endpoints (URLs)**: These are specific addresses (like URLs) where the API listens for incoming requests. Think of an endpoint as a door to your application's functionalities. For example, if you want to fetch user data, you send a request to an endpoint like `/api/users`. - **Receiving and Responding to Requests**: The API receives **HTTP requests** from the front-end. For example, when a user logs in or fetches data, the front-end sends a request, and the back-end API processes it and sends back a response, usually in the form of data (like JSON or XML) or instructions. - **Data Processing and Manipulation**: The back-end API doesn’t just send and receive requests, it also **processes the data**—performing actions like calculations, data validation, or transformi ng data before sending it back to the front-end. The front-end, which could be a web browser or a mobile app, needs data to display to users. It communicates with the back-end by sending HTTP requests. There are different types of HTTP requests # Environement Setup ## Option 1 - Using VS IDE - Download and Install Visual Studio Manegement IDE 2022 ![image](https://hackmd.io/_uploads/SJVbzTaAC.png) - Choose ASP.NET and Web Development ## Option 2 - Using VSCode - Install .NET SDK 8 from https://dotnet.microsoft.com/en-us/download - Download and Install VSCode editor ![image (1)](https://hackmd.io/_uploads/r1d7GTaCR.png) - Install Extensions in VS Code To improve your .NET development experience in VS Code, install the following extensions: - **C# Dev Kit** - NuGet Package Manager (Optional) Another Tools For Next Sessions: - Postman: https://www.postman.com/downloads/ - Version Control (Git): https://git-scm.com/downloads # GitHub GitHub is an online platform that allows developers to store, manage, and collaborate on code repositories. It’s built on Git, a version control system that helps you track changes to your code over time. With GitHub, you can collaborate with others, contribute to open-source projects, and build a portfolio showcasing your coding skills. 📘 Practice: Create GtHub account for you. Why GitHub is Important for This Course: - Task Submissions - Industry Relevance - Source Code Management # Getting Started With C# Basic ## Create a Console .Net App ### **In Visual Studio IDE:** 1. **Open Visual Studio:** - Launch **Visual Studio**. 2. **Create a New Project:** - Select **Create a new project** from the startup screen. - In the search bar, type **Console App**. - Choose **Console App (.NET Core)** or **Console App (.NET Framework)** depending on your requirement. ![image (2)](https://hackmd.io/_uploads/HJzjf6aA0.png) - Click Next. 3. Configure the Project: - Give your project a name (e.g., `MyConsoleApp`). - Choose a location to save your project. ![image (3)](https://hackmd.io/_uploads/H1ByXppCA.png) - Click Next. 4. Select Framework Version: Choose your desired .NET framework version (e.g., .NET 6.0 or .NET 8.0). ![image (4)](https://hackmd.io/_uploads/H1X-XppR0.png) Click Create. 5. **Write Code:** - Visual Studio will generate a basic `Program.cs` file with a `Main` method. - You can write your code in this file. For example, add: ```csharp Console.WriteLine("Hello World!"); ``` 6. **Run the Application:** - Click **Run** or press `F5` to run the console application. - A console window should appear with your output. ### **In VSCode:** 1. **Create a New Project:** - Open the terminal in VSCode, from the menu (**View > Terminal**). - Run the following command to create a new console application: ```bash dotnet new console -n HelloApp ``` - This will create a new folder named `HelloApp` with a basic console application structure. 2. **Open the Project Folder:** - Open the folder in VSCode by going to **File > Open Folder** and selecting the `HelloApp` folder. 1. **Write Code:** - In the `Program.cs` file, you’ll see a basic `Main` method. You can modify it to add your code, e.g.: ```csharp Console.WriteLine("Hello World!"); ``` 3. **Build and Run the Application:** - To build the project, run the following command in the terminal: ```bash dotnet build ``` - To run the application, execute: ```bash dotnet run ``` - The console should display the output from your application. ## Syntax C# is a statically typed, object-oriented language, and its syntax is similar to other C-based languages like C++, Java, or JavaScript. Let’s walk through some of the fundamental aspects of C# syntax. In previous versions of .NET, a console application required a boilerplate `Main` method with a `Program` class. ```csharp using System; namespace MyApp // Namespace declaration { class Program // Class declaration { static void Main(string[] args) // Main method { Console.WriteLine("Hello, World!"); // Output to the console } } } ``` But starting from .NET 6, a top-level statement feature was introduced, which greatly simplifies the structure for simple applications. ```csharp // No class or Main method needed Console.WriteLine("Hello, World!"); ``` ### Variables and Data Types ```csharp int age = 30; float pi = 3.14f; double price = 19.99; decimal accountBalance = 1000.75m; bool isActive = true; string name = "John Doe"; object anything = "Can be any type"; ``` Using `var`: Even though the type is not explicitly written, the compiler knows the type based on the assigned value. ```csharp var age = 25; // `age` is inferred as `int` var price = 19.99; // `price` is inferred as `double` var isActive = true; // `isActive` is inferred as `bool` ``` Declaring Variables Without Initialization In contrast to `var`, variables can still be declared without being initialized, but they must be explicitly typed: ```csharp int age; age = 30; // Now `age` is initialized ``` With `var`, you **must** initialize the variable at the time of declaration because the compiler needs the value to infer the type. ### input **`Console.ReadLine()`**: This method reads input from the user as a string. The input can be converted to other types (such as `int`, `double`, etc.) using conversion methods. ```csharp string ageInput = Console.ReadLine(); int age = int.Parse(ageInput); Console.WriteLine($"Hello {name}, you are {age} years old!"); ``` ```csharp Console.WriteLine("Enter a number:"); string input = Console.ReadLine(); int number; bool success = int.TryParse(input, out number); if (success) { Console.WriteLine($"You entered the number {number}"); } else { Console.WriteLine("That's not a valid number!"); } ``` ### Operators **Mathematical (Arithmetic) Operations** In C#, operations are used to perform actions on variables and values. The most common types of operations include **mathematical** (arithmetic) and **logical** (boolean) operations. Below are the basics of each, along with examples that will help your trainees understand how to use them in practice. | Operator | Description | Example | | --- | --- | --- | | `+` | Addition | `int sum = 10 + 5; // 15` | | --- | --- | --- | | `-` | Subtraction | `int diff = 10 - 5; // 5` | | --- | --- | --- | | `*` | Multiplication | `int product = 10 * 5; // 50` | | --- | --- | --- | | `/` | Division | `int quotient = 10 / 5; // 2` | | --- | --- | --- | | `%` | Modulus (remainder) | `int remainder = 10 % 3; // 1` | | --- | --- | --- | ```csharp int a = 20; int b = 6; Console.WriteLine(a + b); // Addition: 26 Console.WriteLine(a - b); // Subtraction: 14 Console.WriteLine(a * b); // Multiplication: 120 Console.WriteLine(a / b); // Division: 3 Console.WriteLine(a % b); // Modulus: 2 (remainder of 20 / 6) ``` ```csharp int result = 10 / 3; // Result is 3 double result = 10.0 / 3.0; // Result is 3.33 ``` ```csharp int result = 10 + 5 * 2; // 20 (5 * 2 is calculated first) int result = (10 + 5) * 2; // 30 (10 + 5 is calculated first) ``` #### Logical (Boolean) Operations Logical operators are used to perform boolean logic. They return `true` or `false` and are mainly used in decision-making structures (like `if` statements). **Logical Operators:** | Operator | Description | Example | | --- | --- | --- | | `&&` | Logical AND | `(a > 5 && b < 10)` | | ` '' | ` | | `!` | Logical NOT (negation) | `!(a > 5)` | ### Strings A **string** in C# is an object of the `System.String` class, which represents a sequence of characters. Strings in C# are **immutable**, meaning once a string is created, it cannot be changed. Any operation that modifies a string will create a new string object. ```csharp string name = "John Doe"; ``` **Important String Functions in C#** - **Length** - Returns the number of characters in the string. ```csharp string name = "John"; int length = name.Length; // Output: 4 ``` - **ToUpper() / ToLower()** - Converts all characters in the string to uppercase or lowercase. ```csharp string text = "Hello World"; string upper = text.ToUpper(); // Output: "HELLO WORLD" string lower = text.ToLower(); // Output: "hello world" ``` - **Substring(int startIndex, int length)** - Extracts a substring starting at `startIndex` for `length` characters. ```csharp string text = "Hello World"; string sub = text.Substring(0, 5); // Output: "Hello" ``` - **Contains()** - Checks if a string contains a specified substring. ```csharp csharp Copy code string text = "C# is great"; bool result = text.Contains("great"); // Output: true ``` - **Trim()** - Removes leading and trailing whitespace characters from the string. ```csharp string text = " Hello World "; string trimmedText = text.Trim(); // Output: "Hello World" ``` - **StartsWith() / EndsWith()** - Checks if a string starts or ends with a specified substring. ```csharp string text = "Hello World"; bool starts = text.StartsWith("Hello"); // Output: true bool ends = text.EndsWith("World"); // Output: true ``` ## Arrays & Loops ### Arrays An **array** is a collection of items stored at contiguous memory locations. In C#, arrays can store multiple elements of the same data type. Arrays are fixed in size Example of a Simple Array ```csharp int[] numbers = new int[5]; // Array of size 5 // acceess index and set values numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; for (int i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); } ``` ### Loops in C# **Loops** allow you to execute a block of code repeatedly. Common loop types in C# are `for`, `foreach`, `while`, and `do-while`. ```csharp for (int i = 0; i < 5; i++) { Console.WriteLine("Value of i: " + i); } ``` #### Foreach ```csharp int[] numbers = { 10, 20, 30, 40, 50 }; foreach (int number in numbers) { Console.WriteLine("Number: " + number); } ``` ## Practice ```csharp using System; class Program { static void Main(string[] args) { // Step 1: Declare an array to store 5 names string[] names = new string[5]; // Step 2: Input phase - Ask the user to enter 5 names for (int i = 0; i < names.Length; i++) { Console.Write($"Enter name {i + 1}: "); names[i] = Console.ReadLine(); } // Step 3: Display names in the order they were entered (for loop) Console.WriteLine("\nNames in the order entered:"); for (int i = 0; i < names.Length; i++) { Console.WriteLine($"{i + 1}. {names[i]}"); } // Step 4: Use Array.Reverse() to reverse the array in-place Array.Reverse(names); // Display reversed names Console.WriteLine("\nNames in reverse order:"); for (int i = 0; i < names.Length; i++) { Console.WriteLine($"{i + 1}. {names[i]}"); } // Step 5: Greet each person (foreach loop) Console.WriteLine("\nGreetings:"); foreach (string name in names) { Console.WriteLine($"Hello, {name}!"); } // End of program Console.WriteLine("\nProgram has ended."); } } ``` # Task 01 - Install .NET SDK or Visual Studio Management IDE (Version 8) - Verify intallaton f Dotnet 8 - Create a console application that simulates a simple login system. The application will prompt the user for their username and password, validate the input, and, if correct, generate a one-time password (OTP) for additional security: **Features:** 1. **User Input:** - Prompt the user for their username. - Prompt the user for their password. 2. **Input Validation:** - Check if the username or password is empty or null. - Compare the provided credentials with predefined constants in the application. 3. **Authentication:** - If the credentials are incorrect, display a rejection message and exit the application. - If the credentials are correct, generate a 6-digit OTP and display it to the user. 4. **OTP Verification:** - Prompt the user to enter the OTP. - Validate the entered OTP against the generated OTP. - If the OTP is correct, print a success message indicating the user is logged in. - If the OTP is incorrect, print an error message. **Workflow Pseudocode** 1. Start 2. Define constants for username and password: - const string USERNAME = "your_username"; - const string PASSWORD = "your_password"; 3. Initialize a variable for OTP. 4. Display welcome message: "Welcome to the Simple Login System!" 5. Prompt user for username: - Input username. 6. Prompt user for password: - Input password. 7. Check if username or password is empty: - If empty, display "Username or password cannot be empty." and go to step 1. 8. Compare user input with constants: - If username or password is incorrect: - Display "Invalid username or password. Access denied." - Exit the program. - If correct: - Generate a 6-digit OTP: a. Call GenerateOTP() function. b. Display the generated OTP. 9. Prompt user to enter the OTP: - Input OTP from user. 10. Compare user-entered OTP with generated OTP: - If OTP is incorrect: - Display "Invalid OTP. Access denied." - Exit the program. - If OTP is correct: - Display "Success! You are logged in." 1. End