0% found this document useful (0 votes)
25 views34 pages

Roadmap .NET-DEVELOPER

The document outlines a comprehensive guide for learning C# and understanding the .NET ecosystem, covering fundamentals such as variables, control flow, functions, and object-oriented programming. It also explains the differences between .NET Framework, .NET Core, and .NET 5+, along with the roles of CLR and CIL in application execution. Additionally, it introduces version control using Git, detailing essential commands and collaboration practices with platforms like GitHub and GitLab.

Uploaded by

tehzeebwaliya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views34 pages

Roadmap .NET-DEVELOPER

The document outlines a comprehensive guide for learning C# and understanding the .NET ecosystem, covering fundamentals such as variables, control flow, functions, and object-oriented programming. It also explains the differences between .NET Framework, .NET Core, and .NET 5+, along with the roles of CLR and CIL in application execution. Additionally, it introduces version control using Git, detailing essential commands and collaboration practices with platforms like GitHub and GitLab.

Uploaded by

tehzeebwaliya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

nd

TEHZEEB SHAH BSSE UOK 2 YEAR

Phase 1: Fundamentals (1-3 months)

✅ Learn C#

• Variables, data types, operators


• Control flow (if-else, loops, switch)
• Functions & methods
• Object-Oriented Programming (OOP) – Classes, Objects, Inheritance, Polymorphism, Encapsulation

Step 1: Learn C# Programming Basics


C# is the primary language used in .NET development. You need to start with the core concepts of C# before
moving forward.

1.1 Variables, Data Types, and Operators

Variables

A variable is a named storage location in memory that holds a value. In C#, you declare variables using a specific
data type.

csharp

int age = 25; // Integer typedouble salary = 50000.50; // Floating pointstring name = "John";
// Text databool isActive = true; // Boolean (true/false)

Data Types

C# has different data types, categorized into value types and reference types:

Type Example Description


int int num = 10; Whole numbers
double double pi = 3.14; Decimal numbers
char char letter = 'A'; Single character
string string name = "Hello"; Text data
bool bool isAvailable = true; Boolean (true/false)

Operators

Operators are symbols that perform operations on variables.

• Arithmetic Operators: +, -, *, /, %
• Comparison Operators: ==, !=, >, <, >=, <=
• Logical Operators: &&, ||, !

Example:
csharp
int a = 10, b = 5;int sum = a + b; // 15bool isGreater = a > b; // true

Step 2: Control Flow Statements


Control flow statements allow your program to make decisions and execute blocks of code.

2.1 Conditional Statements (if-else, switch)

if-else Statement

Used to execute code based on a condition.

csharp
..
int number = 10;if (number > 0)
{
Console.WriteLine("Positive number");
}else
{
Console.WriteLine("Negative number");
}

switch Statement

Used when multiple conditions need to be checked.

csharp
..
int day = 3;switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
default:
Console.WriteLine("Another day");
break;
}

2.2 Loops (for, while, do-while, foreach)

Loops allow executing a block of code multiple times.

for Loop

csharp
..
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Iteration: " + i);
}

while Loop

csharp
..
int count = 1;while (count <= 5)
{
Console.WriteLine("Count: " + count);
count++;
}

do-while Loop

Runs at least once before checking the condition.

csharp
..
int num = 1;do
{
Console.WriteLine("Number: " + num);
num++;
} while (num <= 5);

foreach Loop (for collections)

csharp
..
string[] fruits = { "Apple", "Banana", "Cherry" };foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}

Step 3: Functions & Methods


Methods (or functions) are reusable blocks of code.

Defining & Calling a Method

csharp
..
void Greet()
{
Console.WriteLine("Hello, World!");
}

Greet(); // Calling the method

Methods with Parameters & Return Values


csharp
..
int AddNumbers(int a, int b)
{
return a + b;
}
int sum = AddNumbers(5, 10);
Console.WriteLine("Sum: " + sum);

Method Overloading (Same method, different parameters)

csharp
..
int Add(int a, int b) { return a + b; }double Add(double a, double b) { return a + b; }

Step 4: Object-Oriented Programming (OOP)


OOP is the core of C# and .NET. It allows structuring code in an organized way.

4.1 Classes & Objects

A class is a blueprint, and objects are instances of that class.

csharp
..
class Car
{
public string model;
public int year;

public void DisplayCar()


{
Console.WriteLine("Car: " + model + ", Year: " + year);
}
}

Car myCar = new Car();


myCar.model = "Toyota";
myCar.year = 2023;
myCar.DisplayCar();

4.2 Inheritance

Inheritance allows a class to inherit properties from another class.

csharp
..
class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Barking...");
}
}

Dog myDog = new Dog();


myDog.Eat(); // Inherited from Animal
myDog.Bark();

4.3 Polymorphism

A method can have multiple implementations.

csharp
..
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal sound...");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof Woof!");
}
}

Animal myAnimal = new Dog();


myAnimal.MakeSound(); // Calls the Dog version

4.4 Encapsulation (Data Hiding)

Encapsulation hides data and only allows controlled access.

csharp
..
class BankAccount
{
private double balance = 0;

public void Deposit(double amount)


{
balance += amount;
}

public double GetBalance()


{
return balance;
}
}

BankAccount account = new BankAccount();


account.Deposit(500);
Console.WriteLine("Balance: " + account.GetBalance());

✅ Understand .NET Framework & .NET Core

• Differences between .NET Framework, .NET Core, and .NET 5+


• Introduction to CLR (Common Language Runtime) and CIL

Understanding .NET Framework, .NET Core, and .NET 5+


.NET is a software development framework created by Microsoft, which allows developers to build different types
of applications such as web, desktop, mobile, and cloud-based applications. Over the years, Microsoft has evolved
the .NET ecosystem, leading to multiple versions.

1. Differences Between .NET Framework, .NET Core, and .NET


5+
Feature .NET Framework .NET Core .NET 5+ (Latest .NET)
Cross-platform (Windows, Cross-platform (Windows,
Platform Windows-only
macOS, Linux) macOS, Linux)
Slower (due to older Optimized and high- Even faster with
Performance
architecture) performance continuous improvements
Monolithic (Large Modular (via NuGet
Modularity Unified and more modular
framework) packages)
All application types
Application Desktop, ASP.NET Web
Console, Web, Microservices (Web, Desktop, Cloud,
Types Forms, MVC
Mobile)
Open Source No Yes Yes
Latest .NET Framework 4.8 (No Last version: .NET Core 3.1 .NET 5, .NET 6, .NET
Version new versions planned) (Now merged into .NET 5+) 7, .NET 8 (LTS)
Future No new features; only No longer supported Actively developed with
Updates security fixes after .NET 5 new features

1.1 What is .NET Framework?


• First introduced in 2002, the .NET Framework is the original implementation of .NET.
• It is Windows-only and supports desktop (WinForms, WPF) and web applications (ASP.NET MVC, Web Forms).
• It relies on IIS (Internet Information Services) for hosting web applications.
• The latest and final version is .NET Framework 4.8, and no further development will happen beyond security updates.

When to Use .NET Framework?

• If you have an existing enterprise application that relies on Windows-specific features.


• If you need to use legacy technologies such as Web Forms, WCF, or Windows-only libraries.

1.2 What is .NET Core?

• Introduced in 2016, .NET Core was a complete redesign of .NET with cross-platform support.
• Modular: Instead of being a monolithic framework, it allows developers to include only necessary libraries via NuGet packages.
• Performance improvements: It is faster than .NET Framework due to enhancements in the runtime.
• It is open-source and maintained by Microsoft and the community.

When to Use .NET Core?

• If you need cross-platform support (Windows, macOS, Linux).


• If you want to build microservices-based architectures.
• If you need high-performance applications.

Final version: .NET Core 3.1 (Now merged into .NET 5).

1.3 What is .NET 5+? (Modern .NET)

• Introduced in 2020, .NET 5 unified .NET Core and .NET Framework into a single platform.
• The latest versions are .NET 6, .NET 7, and .NET 8 (LTS - Long Term Support).
• Supports all application types, including:

o Web (ASP.NET Core)


o Desktop (WPF, WinForms)
o Mobile (Xamarin/.NET MAUI)
o Cloud (Azure)
o Microservices and IoT applications

Why Use .NET 5+?

• Best performance across all .NET versions.


• Cross-platform development.
• Unified framework (single codebase for different application types).
• Regular updates and support.

Current LTS version: .NET 8 (Released in 2023, supported until 2026). Next version: .NET 9
(Expected in 2024).

2. Understanding CLR (Common Language Runtime)


The Common Language Runtime (CLR) is the execution environment for .NET applications. It is responsible
for:
Main Responsibilities of CLR:

1. Memory Management (Garbage Collection) – Automatically manages memory by removing unused objects.
2. Code Execution – Executes .NET applications efficiently.
3. Security – Enforces code access security and prevents unauthorized operations.
4. Exception Handling – Provides a structured approach to error handling.
5. Just-In-Time (JIT) Compilation – Converts CIL (Common Intermediate Language) into machine code at runtime.

3. Understanding CIL (Common Intermediate Language)


When you write C# code, it is not directly compiled into machine code. Instead, it is first compiled into an
intermediate language known as CIL (formerly called MSIL - Microsoft Intermediate Language).

How CIL Works?

1.

C# Code Compilation

o Your C# code is compiled into CIL (.dll or .exe files).

public class Program


{
public static void Main()
{
Console.WriteLine("Hello, World!");
}
}

2.

JIT (Just-In-Time) Compilation

3.

o At runtime, the CLR converts CIL into native machine code specific to the operating system.

Example of CIL Code (Simplified)

"Hello, World!"
call void [System.Console]::WriteLine(string)
ret

Why Use CIL?

• It allows .NET applications to run on different platforms.


• It enables multiple languages (C#, VB.NET, F#) to be used in .NET.
• It helps with performance optimizations by allowing JIT compilation.

4. Summary
• .NET Framework: Windows-only, legacy applications, no new features.
• .NET Core: Cross-platform, modern, modular, last version was 3.1.
• .NET 5+: Unified, cross-platform, high-performance, actively maintained.
• CLR (Common Language Runtime): Manages execution, memory, security, and JIT compilation.
• CIL (Common Intermediate Language): Intermediate compiled code that the CLR converts into native machine code.

✅ Version Control with Git

• Git basics (clone, commit, push, pull)


• GitHub or GitLab for project collaboration

Version Control with Git: A Beginner’s Guide


Git is a version control system that helps developers track changes, collaborate on projects, and manage code
efficiently. It ensures that multiple people can work on the same codebase without conflicts.

1. Why Use Git?


Tracks changes in your code, allowing you to revert if needed.
Facilitates collaboration by enabling multiple developers to work on the same project.
Backup and recovery of code via platforms like GitHub, GitLab, and Bitbucket.
Branching support allows working on different features simultaneously.

2. Install & Setup Git


Step 1: Install Git

Step 1: Install Git

• Download and install Git from git-scm.com.


• Verify installation

git --version

Step 2: Configure Git (First-Time Setup)

After installation, set up your name and email (used for commits):

git config --global user.name "Your Name"


git config --global user.email "[email protected]"

To check your Git configuration:

git config --list


3. Basic Git Commands
Here are the most important Git commands for managing projects.

Step 1: Initialize a Git Repository

A Git repository stores all the version history of a project.

• Create a new Git repository in a project folder

git init
This creates a .git folder inside the directory, initializing the repository.

Step 2: Cloning an Existing Repository

If you want to work on an existing project hosted on GitHub/GitLab, you can clone it.

• Clone a repository from GitHub

git clone https://github.com/username/repository.git

This downloads the repository to your local machine.

Step 3: Staging and Committing Changes

When you make changes in your project, Git tracks them. You need to stage and commit them.

Check Status of Changes

git status

This shows modified files and their status.

Stage Changes (Add Files to the Staging Area)

git add file1.cs file2.cs

or to add all changes:

git add .

Commit Changes (Save to Local Repository)

git commit -m "Added new feature"

What is a Commit?
A commit is a snapshot of your project at a certain point in time.

Step 4: Push Changes to GitHub/GitLab


After committing changes, you need to push them to a remote repository.

git push origin main

If the branch name is master instead of main, use:

git push origin master

Step 5: Pull Changes from Remote Repository

If other developers made changes to the remote repository, you can fetch and merge them into your local project.

git pull origin main

This ensures your local repository is up to date.

Step 6: Creating and Merging Branches

Branches allow you to work on different features separately.

Create a New Branch

git branch feature-branch

Switch to the New Branch

git checkout feature-branch

or (Git 2.23+)

git switch feature-branch

Merge Branch Back to Main

Once your feature is complete, merge it back into the main branch.

git checkout main


git merge feature-branch

Delete a Branch

git branch -d feature-branch

4. Using GitHub/GitLab for Collaboration


To share your work with teammates, you need to connect your local repository to a remote repository (GitHub
or GitLab).
Step 1: Create a Repository on GitHub/GitLab

1. Go to GitHub (https://github.com) or GitLab (https://gitlab.com).


2. Click New Repository.
3. Copy the repository URL.

Step 2: Connect Your Local Repo to Remote

After initializing Git locally (git init), link it to the GitHub repository:

git remote add origin https://github.com/your-username/repository.git

To verify the connection:

git remote -v

5. Additional Git Features


Check Commit History

git log

Undo Last Commit (Soft Reset)

git reset --soft HEAD~1

This keeps your changes but removes the last commit.

Undo Last Commit (Hard Reset - Deletes Changes)

git reset --hard HEAD~1

6. Summary of Commands
Command Description
git init Initialize a new repository
git clone URL Clone a repository from GitHub/GitLab
git status Check status of changes
git add . Add all changes to the staging area
git commit -m "Message" Save changes to the local repository
git push origin main Upload commits to GitHub
git pull origin main Get latest changes from remote
git branch feature-branch Create a new branch
git checkout feature-branch Switch to a branch
git merge feature-branch Merge a branch into main
git log View commit history
git reset --soft HEAD~1 Undo the last commit (keep changes)
Phase 2: Advanced C# & .NET Concepts (3-6 months)

✅ Advanced C# Concepts

• Collections, LINQ (Language Integrated Query)


• Delegates, Events, Lambda Expressions
• Asynchronous Programming (async/await, Task Parallel Library)
• Exception Handling & Logging

Advanced C# Concepts – Step by Step Guide


Once you have mastered the fundamentals of C#, it's time to explore advanced concepts that will enhance your
ability to write efficient, scalable, and maintainable applications.

1. Collections in C#
Collections in C# provide a way to store and manipulate groups of objects. The System.Collections.Generic
namespace provides type-safe collections.

1.1 List<T> (Dynamic Array)

• Stores elements dynamically (size grows automatically).


• Supports sorting, filtering, and searching.

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };


numbers.Add(6);
numbers.Remove(2);
Console.WriteLine(numbers.Count); // Output: 5

1.2 Dictionary<TKey, TValue> (Key-Value Pair)

• Stores unique keys with associated values.

Dictionary<string, int> studentScores = new Dictionary<string, int>


{
{ "Alice", 95 },
{ "Bob", 89 }
};

Console.WriteLine(studentScores["Alice"]); // Output: 95

1.3 Queue<T> (FIFO)

• First-In-First-Out collection.
Queue<string> tasks = new Queue<string>();
tasks.Enqueue("Task1");
tasks.Enqueue("Task2");
Console.WriteLine(tasks.Dequeue()); // Output: Task1

1.4 Stack<T> (LIFO)

• Last-In-First-Out collection.

Stack<string> history = new Stack<string>();


history.Push("Page1");
history.Push("Page2");
Console.WriteLine(history.Pop()); // Output: Page2

2. LINQ (Language Integrated Query)


LINQ allows querying collections in a concise and readable way.

2.1 Basic LINQ Operations

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


// Filtering even numbersvar evenNumbers = numbers.Where(n => n % 2 == 0);
Console.WriteLine(string.Join(", ", evenNumbers)); // Output: 2, 4, 6, 8, 10
// Finding max valueint max = numbers.Max();
Console.WriteLine(max); // Output: 10
// Orderingvar orderedNumbers = numbers.OrderByDescending(n => n);
Console.WriteLine(string.Join(", ", orderedNumbers)); // Output: 10, 9, 8, ...

3. Delegates, Events, and Lambda Expressions


3.1 Delegates (Function Pointers)

Delegates allow methods to be passed as parameters.

delegate void PrintMessage(string message);


class Program
{
static void ShowMessage(string msg) => Console.WriteLine(msg);

static void Main()


{
PrintMessage del = ShowMessage;
del("Hello from Delegate!"); // Output: Hello from Delegate!
}
}

3.2 Events in C#
Events allow loose coupling between components.

class Button
{
public event Action OnClick;

public void Click()


{
OnClick?.Invoke();
}
}
class Program
{
static void Main()
{
Button button = new Button();
button.OnClick += () => Console.WriteLine("Button Clicked!");
button.Click(); // Output: Button Clicked!
}
}

3.3 Lambda Expressions (Shorter Anonymous Functions)

Lambda expressions provide concise function syntax.

Func<int, int> square = x => x * x;


Console.WriteLine(square(5)); // Output: 25

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };var squares = numbers.Select(n => n * n);


Console.WriteLine(string.Join(", ", squares)); // Output: 1, 4, 9, 16, 25

4. Asynchronous Programming
Asynchronous programming improves performance by allowing non-blocking execution.

4.1 Async & Await

async Task<int> GetDataAsync()


{
await Task.Delay(2000); // Simulate async work
return 42;
}
async Task Main()
{
Console.WriteLine("Fetching data...");
int result = await GetDataAsync();
Console.WriteLine($"Result: {result}");
}
4.2 Task Parallel Library (TPL)

TPL allows running multiple tasks in parallel.

Task task1 = Task.Run(() => Console.WriteLine("Task 1 running"));


Task task2 = Task.Run(() => Console.WriteLine("Task 2 running"));
await Task.WhenAll(task1, task2);

5. Exception Handling & Logging


Handling exceptions properly ensures stability.

5.1 Try-Catch-Finally

try
{
int result = 10 / 0; // Division by zero
}catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}finally
{
Console.WriteLine("Execution completed.");
}

5.2 Logging with Serilog

Serilog is a powerful logging framework.

using Serilog;
class Program
{
static void Main()
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();

Log.Information("Application started!");
}
}

6. Summary
Collections – Lists, Dictionaries, Queues, Stacks.
LINQ – Query collections easily with .Where(), .Select(), .OrderBy().
Delegates & Events – Pass functions as parameters and handle events.
Lambda Expressions – Short, inline functions.
Async Programming – Use async/await for non-blocking operations.
Exception Handling & Logging – Handle errors and log information.

✅ .NET Web Development (ASP.NET Core MVC or Web API)

• MVC architecture (Model, View, Controller)


• Razor views, Layouts, Tag Helpers
• Dependency Injection
• Middlewares & Filters

.NET Web Development with ASP.NET Core MVC


ASP.NET Core is a powerful framework for building modern web applications and APIs. This section will guide
you through ASP.NET Core MVC, covering MVC architecture, Razor views, dependency injection,
middlewares, and filters.

1. MVC Architecture (Model-View-Controller)


ASP.NET Core MVC follows the MVC design pattern, which separates concerns into three main components:

1.1 Components of MVC

Component Description
Model Represents data and business logic.
View Handles UI and presentation logic.
Controller Manages user requests and response handling.

1.2 Example of MVC Structure

MyApp/
│-- Controllers/
│ │-- HomeController.cs
│-- Models/
│ │-- Product.cs
│-- Views/
│ │-- Home/
│ │-- Index.cshtml
│-- wwwroot/
│-- Program.cs
│-- appsettings.json

2. Controllers in ASP.NET Core MVC


Controllers handle HTTP requests and return responses.

2.1 Creating a Controller


csharp
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
public IActionResult Index()
{
return View(); // Returns the Index.cshtml view
}

public IActionResult About()


{
return Content("About Page");
}
}

• IActionResult can return View(), Content(), Json(), File(), etc.


• The method names (Index, About) map to routes like /Home/Index.

2.2 Routing in Controllers

ASP.NET Core follows convention-based routing:

csharp
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

• Default URL: /Home/Index


• {id?} makes the parameter optional.

3. Razor Views, Layouts, and Tag Helpers


3.1 Razor Views (.cshtml)

Razor is a templating engine that combines HTML and C#.

Example: Views/Home/Index.cshtml

html

@{
ViewData["Title"] = "Home Page";
}<h1>Welcome to My Website</h1><p>Today's date: @DateTime.Now.ToShortDateString()</p>

• @{} allows inline C# code.


• @DateTime.Now dynamically generates content.

3.2 Layouts (_Layout.cshtml)

A layout defines a common structure for all views (like a master page).
Example: Views/Shared/_Layout.cshtml

<!DOCTYPE html><html><head>
<title>@ViewData["Title"]</title></head><body>
<header><h1>My Website</h1></header>
<main>@RenderBody()</main>
<footer>&copy; 2025</footer></body></html>

• @RenderBody() inserts the view content.

Using Layouts in Views

In Index.cshtml, reference the layout:

@{
Layout = "_Layout";
}

3.3 Tag Helpers

Tag Helpers provide server-side functionality inside Razor views.

Example: Anchor Tag Helper

html
<a asp-controller="Home" asp-action="About">About</a>

This generates:

html
<a href="/Home/About">About</a>

Example: Form Tag Helper

html
<form asp-controller="Account" asp-action="Login">
<input type="text" name="username" />
<button type="submit">Login</button></form>

This binds the form submission to /Account/Login.

4. Dependency Injection (DI) in ASP.NET Core


Dependency Injection (DI) is a built-in feature in ASP.NET Core, used for managing service lifetimes.

4.1 Registering Services in Program.cs

builder.Services.AddScoped<IProductService, ProductService>();

• AddScoped<T> → Creates a new instance per request.


• AddSingleton<T> → Creates one instance for the app.
• AddTransient<T> → Creates a new instance every time.

4.2 Injecting Services into Controllers

public class HomeController : Controller


{
private readonly IProductService _productService;

public HomeController(IProductService productService)


{
_productService = productService;
}

public IActionResult Index()


{
var products = _productService.GetAllProducts();
return View(products);
}
}

5. Middleware in ASP.NET Core


Middleware handles HTTP requests before they reach controllers.

5.1 Built-in Middleware

var app = builder.Build();


app.UseRouting(); // Enables URL routing
app.UseAuthorization(); // Enables authentication
app.UseStaticFiles(); // Serves static files (CSS, JS, images)
app.UseMiddleware<CustomMiddleware>(); // Custom middleware
app.MapControllers();
app.Run();

5.2 Creating Custom Middleware

public class CustomMiddleware


{
private readonly RequestDelegate _next;

public CustomMiddleware(RequestDelegate next)


{
_next = next;
}

public async Task Invoke(HttpContext context)


{
Console.WriteLine("Request Path: " + context.Request.Path);
await _next(context);
}
}
// Register in `Program.cs`
app.UseMiddleware<CustomMiddleware>();

This logs every request path before executing further.

6. Filters in ASP.NET Core MVC


Filters run before or after an action executes.

6.1 Types of Filters

Filter Type Description


Authorization Filter Runs before accessing the action.
Resource Filter Runs before & after model binding.
Action Filter Runs before & after an action executes.
Exception Filter Handles unhandled exceptions.
Result Filter Runs before & after returning a response.

6.2 Creating a Custom Action Filter

public class LogActionFilter : ActionFilterAttribute


{
public override void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("Executing: " + context.ActionDescriptor.DisplayName);
}
}
// Apply to a Controller or Action
[LogActionFilter]public IActionResult Index()
{
return View();
}

7. Summary
MVC Architecture – Models (Data), Views (UI), Controllers (Logic).
Razor Views – Use .cshtml with C# and HTML.
Layouts & Tag Helpers – Shared templates and dynamic elements.
Dependency Injection – Inject services for scalability.
Middlewares – Custom logic in request pipelines.
Filters – Custom logic before or after actions.
✅ .NET API Development (RESTful APIs with ASP.NET Core Web API)

• Creating & consuming APIs


• Authentication & Authorization (JWT, OAuth)
• Swagger documentation

.NET API Development (RESTful APIs with ASP.NET Core Web API)

Let's break it down step by step:

1. Creating & Consuming APIs


Step 1: Setting Up an ASP.NET Core Web API Project

• Open Visual Studio and create a new ASP.NET Core Web API project.
• Choose .NET version and configure settings.
• The project structure will include:
o Controllers/ (where API controllers are defined)
o Program.cs (entry point for configuration)
o appsettings.json (configuration file)
o Models/ (for data models)
o Data/ (for database context, if using Entity Framework)

Step 2: Creating an API Controller

• Define a new controller inside Controllers/

Example: ProductsController.cs

[ApiController]

[Route("api/[controller]")]

public class ProductsController : ControllerBase

private static List<string> products = new() { "Laptop", "Mouse", "Keyboard" };

[HttpGet]

public IActionResult GetProducts()

return Ok(products);

}

o HttpGet → Handles GET requests.
o Ok(products) → Returns 200 OK response with data.

Step 3: Consuming APIs (Client-Side)

• Using Postman or Swagger UI for testing.


• Using HttpClient in C# to call APIs

HttpClient client = new HttpClient();

var response = await client.GetAsync("https://localhost:5001/api/products");

string result = await response.Content.ReadAsStringAsync();

. Authentication & Authorization (JWT, OAuth)


Step 1: Adding Authentication with JWT (JSON Web Token)

• Install JWT Authentication package

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Configure Program.cs:
Csharp
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

.AddJwtBearer(options =>

options.Authority = "https://your-auth-server/";

options.Audience = "your-api";

});

Protect an API endpoint

C sharp

[Authorize] [HttpGet("secure-data")] public IActionResult GetSecureData() { return


Ok("This is protected data"); }

Step 2: Implementing OAuth Authentication (Google, Facebook, IdentityServer)

• Install OAuth authentication:

dotnet add package Microsoft.AspNetCore.Authentication.Google

Configure OAuth provider in Program.cs

builder.Services.AddAuthentication()

.AddGoogle(options =>
{

options.ClientId = "your-client-id";

options.ClientSecret = "your-client-secret";

});

Now users can log in using Google authentication.

3. Swagger Documentation
Step 1: Install Swagger

• Install Swagger package:

dotnet add package Swashbuckle.AspNetCore

• En
ab
le
S
w
ag
ge
r
in
P
r
o
g
r
a
m
.
c
s:

csharp


..


builder.Services.AddSwaggerGen();



csharp
app.UseSwagger();
app.UseSwaggerUI();
• Run the API and visit https://localhost:5001/swagger to see the documentation.

Step 2: Adding API Descriptions

/// <summary>
/// Retrieves all products.
/// </summary>
[HttpGet]
public IActionResult GetProducts()
{
return Ok(products);
}

This will be reflected in the Swagger UI.

Conclusion

You now understand how to:

• Create & consume RESTful APIs in .NET.


• Secure APIs using JWT & OAuth authentication.
• Generate API documentation with Swagger.

✅ Databases (SQL & NoSQL)

• Microsoft SQL Server (T-SQL, Stored Procedures)


• Entity Framework Core (EF Core) for ORM
• NoSQL databases (MongoDB, Redis)

Databases (SQL & NoSQL) in .NET Development

1. Microsoft SQL Server (T-SQL, Stored Procedures)


Step 1: Setting Up SQL Server

• Install Microsoft SQL Server and SQL Server Management Studio (SSMS).
• Create a new database:

sql
CREATE DATABASE MyDatabase;

Step 2: Writing T-SQL Queries

• Create a table:

sql
CREATE TABLE Products (
Id INT PRIMARY KEY IDENTITY,
Name NVARCHAR(100),
Price DECIMAL(10,2)
);
Insert data:

sql
INSERT INTO Products (Name, Price) VALUES ('Laptop', 999.99);

• Select data:

sql
SELECT * FROM Products;

Step 3: Creating Stored Procedures

• Stored procedures encapsulate queries for reuse.

sql
CREATE PROCEDURE GetProductsASBEGIN
SELECT * FROM Products;END;
Execute the stored procedure:
sql
EXEC GetProducts;

2. Entity Framework Core (EF Core) for ORM


Step 1: Install EF Core

• Install EF Core in an ASP.NET Core project:

csharp
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Step 2: Define a Database Context

• Create a DbContext class:

csharp
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder options)


{
options.UseSqlServer("Server=.;Database=MyDatabase;Trusted_Connection=True;");
}
}

Define a Product model:

csharp
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

Step 3: Migrations & Database Creation

Run migrations to generate the database

pgsql
dotnet ef migrations add InitialCreate
dotnet ef database update

Step 4: Performing CRUD Operations

Insert a record:

csharP
using var context = new AppDbContext();
context.Products.Add(new Product { Name = "Phone", Price = 799.99M });
context.SaveChanges();

Retrieve data:

csharp

var products = context.Products.ToList();

3. NoSQL Databases (MongoDB, Redis)


MongoDB

Step 1: Install MongoDB

• Install MongoDB Community Edition and start the service.

Install the C# driver:

csharp
dotnet add package MongoDB.Driver

Step 2: Connect to MongoDB in .NET

Define a MongoDB connection:

csharp
var client = new MongoClient("mongodb://localhost:27017");var database =
client.GetDatabase("MyMongoDb");var collection =
database.GetCollection<Product>("Products");

Step 3: Insert & Retrieve Data


Insert a document:

Csharp
var product = new Product { Name = "Tablet", Price = 499.99M };
collection.InsertOne(product);

Retrieve documents:

csharp

var products = collection.Find(_ => true).ToList();

Redis (Caching)

Step 1: Install Redis

• Install Redis Server and run it.

Add Redis to your project:

csharp
dotnet add package StackExchange.Redis

Step 2: Connect to Redis

Create a connection:

csharp
var redis = ConnectionMultiplexer.Connect("localhost");var db = redis.GetDatabase();

Store and retrieve data:

csharp

db.StringSet("username", "JohnDoe");string username = db.StringGet("username");

Conclusion

Now you understand:

• SQL Server (T-SQL, Stored Procedures)


• EF Core for ORM
• NoSQL databases (MongoDB, Redis)

Phase 3: Practical Development (6-12 months)

✅ Full-Stack Development (Optional)

• Frontend Basics: HTML, CSS, JavaScript


• JavaScript Frameworks: React, Angular, or Blazor
• Consuming APIs in frontend

Full-Stack Development (Optional) – Step by


Step Guide
To become a full-stack .NET developer, you need frontend skills along with your backend expertise. This phase
covers HTML, CSS, JavaScript, frontend frameworks (React, Angular, Blazor), and API integration.

1. Frontend Basics: HTML, CSS, JavaScript


1.1 HTML (Structure of Web Pages)

HTML is the backbone of web pages, defining structure using elements like:

html
<!DOCTYPE html><html><head>
<title>My Website</title></head><body>
<h1>Welcome</h1>
<p>This is a paragraph.</p>
<a href="https://example.com">Click me</a></body></html>

• <h1> → Headings
• <p> → Paragraphs
• <a> → Links
• <img> → Images

1.2 CSS (Styling Web Pages)

CSS enhances design and layout:

css
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
h1 {
color: blue;
text-align: center;
}

• background-color → Sets page background


• font-family → Defines text font
• text-align → Centers text
1.3 JavaScript (Making Pages Interactive)

JavaScript adds interactivity:

html
<button onclick="showMessage()">Click Me</button><script>
function showMessage() {
alert("Hello, World!");
}</script>

• onclick triggers showMessage()


• alert() shows a popup

2. JavaScript Frameworks: React, Angular, or Blazor


Modern applications use frontend frameworks for faster development.

2.1 React (Popular Library by Meta)

React is a component-based UI library.

jsx
function App() {
return <h1>Hello from React!</h1>;
}export default App;

React features:

• Reusable components
• Virtual DOM for speed
• State management with hooks

2.2 Angular (Google's Framework)

Angular is a full-fledged frontend framework.

typescript
@Component({
selector: 'app-root',
template: `<h1>Hello from Angular!</h1>`
})export class AppComponent { }

Angular uses:

• TypeScript
• Two-way data binding
• Built-in form validation

2.3 Blazor (Microsoft’s .NET Frontend)


Blazor allows C# in the frontend.

razor
@page "/"
<h1>Hello from Blazor!</h1>
<button @onclick="ShowMessage">Click Me</button>

@code {
void ShowMessage() {
Console.WriteLine("Blazor button clicked!");
}
}

Blazor features:

• C# instead of JavaScript
• Component-based architecture
• Tight integration with .NET backend

3. Consuming APIs in the Frontend


Frontend apps interact with backend RESTful APIs.

3.1 Fetch API (Vanilla JavaScript)

javascript
fetch("https://api.example.com/products")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));

3.2 Fetching Data in React

jsx
import { useEffect, useState } from "react";
function Products() {
const [products, setProducts] = useState([]);

useEffect(() => {
fetch("https://api.example.com/products")
.then(res => res.json())
.then(data => setProducts(data));
}, []);

return (
<ul>
{products.map(p => <li key={p.id}>{p.name}</li>)}
</ul>
);
}

3.3 Fetching Data in Angular (HttpClient)

typescript
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {}
getProducts() {
this.http.get<Product[]>('https://api.example.com/products')
.subscribe(products => console.log(products));
}

3.4 Fetching Data in Blazor

razor
@code {
private List<Product> products = new();

protected override async Task OnInitializedAsync()


{
products = await
Http.GetFromJsonAsync<List<Product>>("https://api.example.com/products");
}
}

4. Summary
HTML, CSS, JavaScript – Core frontend technologies.
React, Angular, Blazor – Choose a frontend framework.
Consuming APIs – Fetch data in frontend apps.

You might also like