0%
أساسيات .NET لتطوير التطبيقات الحديثة

أساسيات .NET لتطوير التطبيقات الحديثة

دليل شامل لإتقان أساسيات .NET، منصة التطوير متعددة الاستخدامات من Microsoft، والمثالية لتطبيقات الويب وسطح المكتب والسحابة.

I

InSkillCoach

· دقيقة

أساسيات .NET لتطوير التطبيقات الحديثة

مقدمة إلى .NET

.NET منصة تطوير حرة ومفتوحة المصدر أنشأتها Microsoft، وتتيح بناء أنواع مختلفة من التطبيقات: الويب والجوال وسطح المكتب والألعاب وإنترنت الأشياء (IoT) والسحابة. وهي منظومة متكاملة توفر للمطورين الأدوات اللازمة لإنشاء تطبيقات حديثة وعالية الأداء وآمنة.

لماذا نختار .NET؟

  • تعدد الاستخدامات: طوّر تطبيقات لأنظمة Windows وLinux وmacOS وiOS وAndroid وغيرها
  • الأداء: مُحسَّنة من حيث السرعة واستهلاك الموارد
  • الأمان: تحديثات متكررة وميزات أمان مدمجة
  • المصدر المفتوح: مشروع مفتوح المصدر تدعمه Microsoft ومجتمع نشط
  • منظومة غنية: مكتبات كثيرة وأدوات عالية الجودة

التثبيت والإعداد

تثبيت .NET SDK

حزمة SDK (Software Development Kit) الخاصة بـ .NET ضرورية لتطوير تطبيقات .NET.

Windows:

# Télécharger depuis le site officiel
https://dotnet.microsoft.com/download

macOS (باستخدام Homebrew):

brew install --cask dotnet-sdk

Linux (Ubuntu):

wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
sudo apt-get update
sudo apt-get install -y apt-transport-https
sudo apt-get install -y dotnet-sdk-6.0

التحقق من التثبيت

dotnet --version

المفاهيم الأساسية

لغات البرمجة

يدعم .NET عدة لغات برمجة، وأكثرها شعبية:

  • C# - اللغة الرئيسية، كائنية التوجه وصارمة الأنواع
  • F# - لغة وظيفية لكتابة برامج أكثر إيجازًا
  • Visual Basic .NET - نسخة محدّثة من Visual Basic

بنية مشروع .NET

يحتوي مشروع .NET عادةً على العناصر التالية:

  • ملف .csproj / .fsproj / .vbproj - إعدادات المشروع
  • Program.cs - نقطة دخول التطبيق
  • المجلدات: Models وControllers وViews (لتطبيقات الويب) وServices وغيرها
  • appsettings.json - إعدادات التطبيق

إنشاء مشروع جديد

# Créer une application console
dotnet new console -n MonApplication

# Créer une application web ASP.NET Core
dotnet new webapp -n MonAppWeb

# Créer une API web
dotnet new webapi -n MonAPI

لغة C#

المتغيرات وأنواع البيانات

// Types de base
int nombre = 42;
double prix = 19.99;
bool estActif = true;
string nom = "Jean Dupont";
char lettre = 'A';

// Collections
int[] nombres = { 1, 2, 3, 4, 5 };
List<string> noms = new List<string> { "Alice", "Bob", "Charlie" };
Dictionary<string, int> ages = new Dictionary<string, int>
{
    { "Alice", 30 },
    { "Bob", 25 }
};

هياكل التحكم

// Conditions
if (age >= 18)
{
    Console.WriteLine("Majeur");
}
else
{
    Console.WriteLine("Mineur");
}

// Switch
switch (jour)
{
    case "Lundi":
        Console.WriteLine("Début de semaine");
        break;
    case "Vendredi":
        Console.WriteLine("Bientôt le weekend");
        break;
    default:
        Console.WriteLine("Un autre jour");
        break;
}

// Boucles
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

foreach (var nom in noms)
{
    Console.WriteLine(nom);
}

while (compteur > 0)
{
    Console.WriteLine(compteur);
    compteur--;
}

الدوال والأساليب

// Méthode simple
void AfficherMessage(string message)
{
    Console.WriteLine(message);
}

// Méthode avec retour
int Additionner(int a, int b)
{
    return a + b;
}

// Méthode avec paramètres optionnels
void Configurer(string nom, int age = 18, bool estActif = true)
{
    // ...
}

// Méthode d'extension
public static class StringExtensions
{
    public static bool EstPalindrome(this string texte)
    {
        string inverse = new string(texte.Reverse().ToArray());
        return texte.Equals(inverse, StringComparison.OrdinalIgnoreCase);
    }
}

البرمجة كائنية التوجه في C#

الأصناف والكائنات

// Définition d'une classe
public class Personne
{
    // Propriétés
    public string Nom { get; set; }
    public string Prenom { get; set; }
    public int Age { get; set; }
    
    // Constructeur
    public Personne(string nom, string prenom, int age)
    {
        Nom = nom;
        Prenom = prenom;
        Age = age;
    }
    
    // Méthode
    public string ObtenirNomComplet()
    {
        return $"{Prenom} {Nom}";
    }
}

// Utilisation
Personne personne = new Personne("Dupont", "Jean", 30);
Console.WriteLine(personne.ObtenirNomComplet());

الوراثة

public class Employe : Personne
{
    public string Poste { get; set; }
    public decimal Salaire { get; set; }
    
    public Employe(string nom, string prenom, int age, string poste, decimal salaire)
        : base(nom, prenom, age)
    {
        Poste = poste;
        Salaire = salaire;
    }
    
    public void AugmenterSalaire(decimal pourcentage)
    {
        Salaire += Salaire * (pourcentage / 100);
    }
}

الواجهات

public interface IPayable
{
    decimal CalculerPaiement();
}

public class Consultant : Personne, IPayable
{
    public decimal TarifHoraire { get; set; }
    public int HeuresTravaillees { get; set; }
    
    public Consultant(string nom, string prenom, int age, decimal tarifHoraire)
        : base(nom, prenom, age)
    {
        TarifHoraire = tarifHoraire;
    }
    
    public decimal CalculerPaiement()
    {
        return TarifHoraire * HeuresTravaillees;
    }
}

ASP.NET Core لتطوير الويب

ASP.NET Core إطار عمل ويب عالي الأداء ومتعدد المنصات ومفتوح المصدر لبناء تطبيقات ويب حديثة.

بنية تطبيق ويب ASP.NET Core

MonAppWeb/
├── Controllers/     # Contrôleurs MVC ou d'API
├── Models/          # Classes de modèles
├── Views/           # Vues Razor (pour MVC)
├── wwwroot/         # Fichiers statiques (CSS, JS, images)
├── appsettings.json # Configuration de l'application
├── Program.cs       # Point d'entrée
└── Startup.cs       # Configuration des services et du pipeline

إنشاء واجهة REST API بسيطة

// Controllers/PersonnesController.cs
[ApiController]
[Route("api/[controller]")]
public class PersonnesController : ControllerBase
{
    private static List<Personne> _personnes = new List<Personne>
    {
        new Personne { Id = 1, Nom = "Dupont", Prenom = "Jean", Age = 30 },
        new Personne { Id = 2, Nom = "Martin", Prenom = "Sophie", Age = 25 }
    };
    
    [HttpGet]
    public ActionResult<IEnumerable<Personne>> Get()
    {
        return _personnes;
    }
    
    [HttpGet("{id}")]
    public ActionResult<Personne> Get(int id)
    {
        var personne = _personnes.Find(p => p.Id == id);
        if (personne == null)
            return NotFound();
            
        return personne;
    }
    
    [HttpPost]
    public ActionResult<Personne> Post(Personne personne)
    {
        personne.Id = _personnes.Max(p => p.Id) + 1;
        _personnes.Add(personne);
        return CreatedAtAction(nameof(Get), new { id = personne.Id }, personne);
    }
}

Razor Pages للواجهات البسيطة

// Pages/Index.cshtml.cs
public class IndexModel : PageModel
{
    public List<Personne> Personnes { get; set; }
    
    public void OnGet()
    {
        Personnes = new List<Personne>
        {
            new Personne { Id = 1, Nom = "Dupont", Prenom = "Jean", Age = 30 },
            new Personne { Id = 2, Nom = "Martin", Prenom = "Sophie", Age = 25 }
        };
    }
}
<!-- Pages/Index.cshtml -->
@page
@model IndexModel
@{
    ViewData["Title"] = "Liste des personnes";
}

<h1>Liste des personnes</h1>

<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Prénom</th>
            <th>Nom</th>
            <th>Âge</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var personne in Model.Personnes)
        {
            <tr>
                <td>@personne.Id</td>
                <td>@personne.Prenom</td>
                <td>@personne.Nom</td>
                <td>@personne.Age</td>
            </tr>
        }
    </tbody>
</table>

Entity Framework Core للوصول إلى البيانات

Entity Framework Core هو أداة ORM (Object-Relational Mapping) تتيح التفاعل مع قاعدة بيانات باستخدام كائنات C#.

الإعداد الأساسي

// Models/Personne.cs
public class Personne
{
    public int Id { get; set; }
    public string Nom { get; set; }
    public string Prenom { get; set; }
    public int Age { get; set; }
}

// Data/ApplicationDbContext.cs
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
    
    public DbSet<Personne> Personnes { get; set; }
}

// Program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

عمليات CRUD البسيطة

// Services/PersonneService.cs
public class PersonneService
{
    private readonly ApplicationDbContext _context;
    
    public PersonneService(ApplicationDbContext context)
    {
        _context = context;
    }
    
    public async Task<List<Personne>> ObtenirToutesAsync()
    {
        return await _context.Personnes.ToListAsync();
    }
    
    public async Task<Personne> ObtenirParIdAsync(int id)
    {
        return await _context.Personnes.FindAsync(id);
    }
    
    public async Task AjouterAsync(Personne personne)
    {
        _context.Personnes.Add(personne);
        await _context.SaveChangesAsync();
    }
    
    public async Task MettreAJourAsync(Personne personne)
    {
        _context.Entry(personne).State = EntityState.Modified;
        await _context.SaveChangesAsync();
    }
    
    public async Task SupprimerAsync(int id)
    {
        var personne = await _context.Personnes.FindAsync(id);
        if (personne != null)
        {
            _context.Personnes.Remove(personne);
            await _context.SaveChangesAsync();
        }
    }
}

أفضل الممارسات في .NET

المعمارية الطبقية

بنية تقليدية لتطبيق .NET:

  1. طبقة العرض: واجهة المستخدم وواجهات API وغيرها
  2. طبقة التطبيق: الخدمات ومنطق الأعمال
  3. طبقة المجال: الكيانات ومنطق الأعمال الأساسي
  4. طبقة البنية التحتية: الوصول إلى البيانات والخدمات الخارجية

حقن التبعيات

// Enregistrement des services dans Program.cs
builder.Services.AddScoped<IPersonneService, PersonneService>();
builder.Services.AddScoped<IPersonneRepository, PersonneRepository>();

// Utilisation dans un contrôleur
public class PersonnesController : ControllerBase
{
    private readonly IPersonneService _personneService;
    
    public PersonnesController(IPersonneService personneService)
    {
        _personneService = personneService;
    }
    
    // ...
}

اختبارات الوحدة

// Tests/PersonneServiceTests.cs
public class PersonneServiceTests
{
    [Fact]
    public async Task ObtenirToutesAsync_RetourneToutesLesPersonnes()
    {
        // Arrange
        var mockRepository = new Mock<IPersonneRepository>();
        mockRepository.Setup(repo => repo.ObtenirToutesAsync())
            .ReturnsAsync(new List<Personne>
            {
                new Personne { Id = 1, Nom = "Dupont", Prenom = "Jean" },
                new Personne { Id = 2, Nom = "Martin", Prenom = "Sophie" }
            });
            
        var service = new PersonneService(mockRepository.Object);
        
        // Act
        var resultat = await service.ObtenirToutesAsync();
        
        // Assert
        Assert.Equal(2, resultat.Count);
    }
}

.NET في السحابة

Azure و.NET

توفر Azure دعمًا ممتازًا لتطبيقات .NET:

  • Azure App Service: نشر سهل لتطبيقات الويب
  • Azure Functions: دوال بلا خوادم (serverless)
  • Azure SQL Database: قاعدة بيانات SQL متوافقة مع Entity Framework
  • Azure Storage: تخزين سحابي (الكائنات الثنائية blobs والجداول وقوائم الانتظار)

Docker و.NET

# Dockerfile
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["MonApp.csproj", "./"]
RUN dotnet restore "MonApp.csproj"
COPY . .
RUN dotnet publish "MonApp.csproj" -c Release -o /app/publish

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS final
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MonApp.dll"]

مصادر لمواصلة التعلم

الخاتمة

.NET منصة ناضجة وعالية الأداء وفي تطور مستمر، وتوفر بيئة تطوير ممتازة لإنشاء تطبيقات حديثة. وتتيح مرونتها استهداف منصات مختلفة وتطوير أنواع متنوعة من التطبيقات، من الويب إلى الجوال مرورًا بسطح المكتب والسحابة. وبإتقان هذه الأساسيات تمتلك قاعدة متينة لاستكشاف مزيد من الإمكانات التي تتيحها منظومة .NET.

InSkillCoach

نبذة عن InSkillCoach

خبير في التدريب والتقنيات

مدرّب متخصص في التقنيات المتقدمة والذكاء الاصطناعي، تدعمه شركة GNeurone Inc.

الشهادات:

  • AWS Certified Solutions Architect – Professional
  • شهادات Google Cloud
  • Microsoft Certified: DevOps Engineer Expert
  • Certified Kubernetes Administrator (CKA)
  • CompTIA Security+
1.1k
155

التعليقات

التعليقات مدعومة عبر GitHub Discussions

سجّل الدخول باستخدام GitHub للمشاركة في النقاش

تم نسخ الرابط!