المشاركات

عرض الرسائل ذات التصنيف .NET Core

Entity Framework Core Basics

Lesson 8: Entity Framework Core Basics In this lesson, you will learn about Entity Framework Core (EF Core) , the main Object-Relational Mapper (ORM) for .NET applications. 🗄️ What is EF Core? Entity Framework Core is a lightweight, cross-platform ORM that: Maps C# classes to database tables. Handles CRUD operations automatically. Supports LINQ queries against your data. It works with many databases like SQL Server, SQLite, PostgreSQL, and more. 🔧 Setting Up EF Core To add EF Core, install the NuGet package: dotnet add package Microsoft.EntityFrameworkCore.SqlServer Then create a DbContext to manage your entities. 🏷️ Example Entity and DbContext Here is an example model and context: using Microsoft.EntityFrameworkCore; public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } public class AppDbContext : DbContext { public DbSet Products { g...

Introduction to ASP.NET Core

Lesson 7: Introduction to ASP.NET Core In this lesson, you will learn about ASP.NET Core , the modern framework for building web applications and APIs. 🌐 What is ASP.NET Core? ASP.NET Core is an open-source, cross-platform framework for building: Web applications (MVC and Razor Pages). RESTful APIs. Real-time apps (SignalR). It runs on Windows, Linux, and macOS. 🚀 Key Features ASP.NET Core provides: Cross-platform support: Run anywhere. High performance: Optimized for speed and scalability. Dependency Injection: Built-in DI container. Unified development model: For web UI and APIs. Modern hosting: Integrated with Kestrel server. 🛠️ Project Structure An ASP.NET Core project typically includes: Program.cs : Entry point for configuring the app. Startup.cs : (in older versions) Configures services and middleware. appsettings.json : Configuration file. Controllers : API or MVC controllers. Views : R...

Language Integrated Query (LINQ)

Lesson 6: Language Integrated Query (LINQ) In this lesson, you will learn about Language Integrated Query (LINQ) , a powerful feature that lets you query data in a consistent way across collections, databases, XML, and more. 🔍 What is LINQ? LINQ allows you to write queries directly in C# or VB.NET, using familiar syntax to manipulate: In-memory collections (LINQ to Objects). Databases (LINQ to SQL, Entity Framework). XML (LINQ to XML). 📝 Basic LINQ Query Here is an example querying an array of integers: using System; using System.Linq; class Program { static void Main() { int[] numbers = { 1, 2, 3, 4, 5, 6 }; var evenNumbers = from n in numbers where n % 2 == 0 select n; foreach (var num in evenNumbers) { Console.WriteLine(num); } } } ⚙️ Extension Methods Syntax You can also use method syntax with extension methods:...

The .NET Base Class Library (BCL)

Lesson 5: The .NET Base Class Library (BCL) In this lesson, you will discover the Base Class Library (BCL) , the set of core libraries that provides fundamental building blocks for all .NET applications. 📚 What is the BCL? The BCL is a collection of classes, interfaces, and types that cover essential functionality, including: Basic types (strings, numbers, dates). Collections and generics. File I/O. Networking. Reflection and metadata. These libraries are part of System.* namespaces. 🧩 Key Namespaces in the BCL Here are some important namespaces you will use often: System: Core types like String, Int32, DateTime. System.Collections: Non-generic collections. System.Collections.Generic: Generic collections like List<T> and Dictionary<TKey, TValue>. System.IO: Reading and writing files and streams. System.Net: Networking and HTTP communication. System.Linq: Language Integrated Query (LINQ) support. ...

Common Language Runtime (CLR)

Lesson 4: Understanding the Common Language Runtime (CLR) in Depth In this lesson, you will dive deeper into the Common Language Runtime (CLR) , the engine that powers all .NET applications. ⚙️ What is the CLR? The CLR is the runtime environment for .NET code. It manages the execution of programs written in different languages targeting .NET. Compiles Intermediate Language (IL) into native code. Provides memory management and garbage collection. Handles security, type safety, and exception handling. 🔄 Compilation Process When you build a .NET application: Your C# code is compiled into Intermediate Language (IL) . IL is stored in an assembly (DLL or EXE). At runtime, the Just-In-Time (JIT) compiler converts IL to native machine code. This process ensures high performance while keeping platform independence. 🧠 Key CLR Services The CLR offers many services that simplify development: Garbage Collection: Automatically fr...

.NET Architecture and Component

Lesson 3: .NET Architecture and Components In this lesson, you will learn about the architecture of .NET and its main components that make development easier and more powerful. 🏛️ High-Level Architecture .NET consists of several building blocks that work together: Common Language Runtime (CLR): The execution engine that runs your code and provides services like garbage collection and security. Base Class Library (BCL): A set of APIs for common tasks such as collections, file I/O, and data types. Languages: C#, F#, Visual Basic, and more, all compiled to Intermediate Language (IL). Application Models: Web, desktop, mobile, cloud, IoT. ⚙️ Common Language Runtime (CLR) The CLR is the heart of .NET. It performs: Memory management: Automatic garbage collection. Exception handling: Unified error management. Type safety: Ensures code correctness and security. Just-In-Time (JIT) compilation: Compiles IL code to native machine c...

History and Evolution of .NET

Lesson 2: History and Evolution of .NET In this lesson, you will learn how .NET has evolved over time, from its early beginnings to the modern unified platform we have today. 📜 The Beginning Microsoft started working on .NET in the late 1990s to modernize software development for Windows. The first official release was: .NET Framework 1.0 in 2002 This version included the Common Language Runtime (CLR) and Base Class Library (BCL). 🔄 .NET Framework Growth Over the years, .NET Framework received many updates and improvements: ASP.NET: For building web applications. Windows Forms: For building desktop apps. WPF: Rich desktop applications with modern UI. WCF: Services and communication. Entity Framework: Object-relational mapping (ORM). 🌐 The Cross-Platform Revolution With the rise of Linux, macOS, and open-source development, Microsoft introduced: .NET Core 1.0 in 2016: Lightweight, modular, and cross-platform....

What is .NET?

Lesson 1: What is .NET? In this lesson, you will learn what .NET is, why it exists, and how it helps developers build modern applications. 🌟 What is .NET? .NET is a free, open-source, cross-platform development platform created by Microsoft. It enables you to build different types of applications, including: Web applications Desktop applications Mobile applications Cloud services Games Internet of Things (IoT) apps 🛠️ Core Components of .NET .NET Runtime: Executes your application code, manages memory, performs garbage collection, and enforces security. Base Class Library (BCL): A large collection of prebuilt APIs and classes for file operations, networking, data access, collections, and security. Languages: .NET supports C#, Visual Basic .NET (VB.NET), and F#. SDK: Tools, compilers, and libraries to create, build, and run .NET applications. 💡 Why Use .NET? Cross-Platform: Works on Windows, Linux, and macOS...

.NET Core - CI/CD باستخدام GitHub Actions أو Azure DevOps

7.4 .NET Core - CI/CD باستخدام GitHub Actions أو Azure DevOps CI/CD تعني "التكامل المستمر / النشر المستمر" (Continuous Integration / Continuous Deployment)، وهي آلية تلقائية لبناء واختبار ونشر الكود عند كل تحديث. في هذا الدرس سنتعرف على استخدام GitHub Actions وAzure DevOps لتطبيقات ‎.NET Core. 🔹 ما هو GitHub Actions؟ GitHub Actions هي منصة تلقائية مدمجة في GitHub تتيح لك تشغيل سكربتات عند أحداث معينة (مثل push أو pull request). 🔧 1) إعداد GitHub Actions لبيئة .NET في مجلد مشروعك على GitHub، أنشئ الملف التالي: .github/workflows/dotnet.yml name: Build and Deploy on: push: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup .NET uses: actions/setup-dotnet@v3 with: dotnet-version: '8.0.x' - name: Restore dependencies run: dotnet restore - name: Build run: dotnet build --no-restore - name: Test run...

.NET Core - استخدام Docker مع ‎.NET Core

7.3 .NET Core - استخدام Docker مع ‎.NET Core Docker هو بيئة تشغيل خفيفة الوزن (Containerization) تتيح لك تشغيل تطبيقك في "حاوية" (Container) مع كل ما يحتاجه للعمل. في هذا الدرس سنتعلم كيف تنشئ حاوية Docker لتطبيق ASP.NET Core وتقوم بتشغيله بشكل مستقل عن النظام. 🐋 ما الذي يميز Docker؟ سهولة النشر في أي بيئة (Windows, Linux, Cloud) بيئة تشغيل موحدة للتطبيق ومكتباته أداء قريب من الأداء الأصلي (native) إمكانية التشغيل داخل شبكات خاصة (Containers Networking) 🔹 1) تثبيت Docker Desktop حمل Docker من: https://www.docker.com/products/docker-desktop/ شغل البرنامج وتأكد أنه يعمل (رمز الحوت في شريط المهام) 🔹 2) إنشاء ملف Dockerfile في جذر مشروع ASP.NET Core، أنشئ ملف باسم Dockerfile يحتوي على التالي: FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base WORKDIR /app EXPOSE 80 FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src COPY . . RUN dotnet publish -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=bu...

.NET Core - نشر التطبيق على IIS

7.1 .NET Core - نشر التطبيق على IIS إذا كنت تستخدم خادم Windows، فإن نشر تطبيق ASP.NET Core على IIS هو طريقة شائعة وفعالة للوصول إليه من الإنترنت أو الشبكة المحلية. في هذا الدرس سنتعلم خطوات إعداد IIS، وتجهيز التطبيق، ورفعه للعمل. 🔹 1) تثبيت المتطلبات على السيرفر تثبيت IIS من ميزات Windows (Server أو Client) تثبيت حزمة ASP.NET Core Hosting Bundle 📥 رابط الحزمة: https://dotnet.microsoft.com/en-us/download/dotnet اختر "Hosting Bundle" للنسخة المناسبة من .NET (مثلاً .NET 6 أو 8) 🔹 2) تجهيز المشروع للنشر افتح الطرفية داخل مشروعك ونفّذ: dotnet publish -c Release -o ./publish 📁 سيتم إنشاء مجلد publish يحتوي على الملفات الجاهزة للنشر. 🔹 3) إنشاء موقع جديد داخل IIS افتح IIS Manager انقر يمينًا على Sites ثم اختر Add Website اختر اسم الموقع (مثلاً: MyWebApi) حدد المسار إلى مجلد publish اختر منفذ (مثل: 8080) أو اسم نطاق داخلي 🔹 4) إعداد صلاحيات الوصول للمجلد امنح صلاحية "قراءة وتشغيل" لحساب المستخدم: I...

.NET Core - الأداء وتحسين السرعة (Performance Optimization)

6.4 .NET Core - الأداء وتحسين السرعة (Performance Optimization) تحسين أداء التطبيقات في ASP.NET Core هو عامل حاسم لنجاح أي مشروع، خصوصًا عند العمل مع عدد كبير من المستخدمين أو الطلبات. في هذا الدرس سنتعرف على أهم الطرق لتحسين السرعة، وتقليل استهلاك الموارد، وتقديم تجربة مستخدم أسرع. 🚀 1) التخفيف من الوصول المتكرر لقاعدة البيانات استخدم Caching (الذاكرة المؤقتة) لتخزين البيانات التي لا تتغير باستمرار. قلل من الاستعلامات غير الضرورية عبر Include() الذكي في Entity Framework. // استخدام الذاكرة المؤقتة builder.Services.AddMemoryCache(); // في الكود if (!_cache.TryGetValue("productList", out List<Product> products)) { products = _context.Products.ToList(); _cache.Set("productList", products, TimeSpan.FromMinutes(5)); } 📦 2) تفعيل ضغط الاستجابة (Response Compression) ضغط الـ Response يقلل حجم البيانات المرسلة للعميل. builder.Services.AddResponseCompression(); app.UseResponseCompression(); 🧵 3) استخدام Async/Await ...

.NET Core - التعامل مع الأخطاء (Exception Handling)

6.3 .NET Core - التعامل مع الأخطاء (Exception Handling) أي تطبيق معرض للأخطاء أثناء التشغيل مثل: أخطاء في قاعدة البيانات، أو Null Reference، أو مدخلات غير صحيحة. في ASP.NET Core، يمكنك التعامل مع هذه الأخطاء بطريقة مركزية وآمنة باستخدام Middleware مخصص أو الأدوات المدمجة. 🔹 الطرق الشائعة للتعامل مع الأخطاء استخدام try-catch داخل الأكشن. استخدام Middleware مخصص للتعامل مع الأخطاء عالميًا. استخدام ExceptionHandler Middleware الرسمي من ASP.NET Core. 🔹 الطريقة البسيطة: try-catch [HttpGet("{id}")] public IActionResult Get(int id) { try { var product = GetProductById(id); return Ok(product); } catch (Exception ex) { return StatusCode(500, $"خطأ: {ex.Message}"); } } 🔸 جيدة للسيناريوهات البسيطة، لكنها مملة ومكررة في المشاريع الكبيرة. 🔹 الطريقة الاحترافية: Middleware للتعامل مع الأخطاء 📄 إنشاء Middleware مخصص: public class ErrorHandlerMiddleware { private readonly RequestDe...

.NET Core - Middleware وكيفية استخدامها

6.2 .NET Core - Middleware وكيفية استخدامها في ‎ ASP.NET Core ، الـ Middleware هو مكون يعمل في سلسلة المعالجة (Pipeline) ويقوم بالتعامل مع الطلبات والردود (HTTP Request/Response). يمكن استخدام Middleware للتحقق من التوكن، تسجيل الأخطاء، إعادة التوجيه، التحقق من الصلاحيات، أو تعديل الـ Response. 🔹 ما هو Middleware؟ هو كود يتم تنفيذه عند مرور كل طلب HTTP عبر التطبيق. كل Middleware يمكنه: تنفيذ منطق معين قبل تمرير الطلب إلى التالي. إيقاف السلسلة وعدم تمرير الطلب. تنفيذ منطق بعد استلام الرد من الـ Middleware الذي يليه. 🔹 ترتيب الـ Middleware مهم جدًا في ملف Program.cs ، يتم تنفيذ Middleware بنفس ترتيب كتابتها. مثلًا: app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); إذا وضعت UseAuthorization() قبل UseAuthentication() فلن يتمكن النظام من معرفة المستخدم أصلاً. 🔹 مثال على Middleware مخصص لننشئ Middleware يقوم بتسجيل وقت بداية الطلب: public class Logging...

.NET Core - Dependency Injection في ‎.NET Core

6.1 .NET Core - Dependency Injection في ‎.NET Core Dependency Injection (DI) هي أحد المبادئ الأساسية في تصميم البرمجيات، وASP.NET Core يدعمها بشكل مدمج وأساسي. تساعد هذه التقنية على كتابة كود أكثر مرونة، قابل للاختبار، وقابل للصيانة. 🔹 ما المقصود بـ Dependency Injection؟ DI تعني "حقن التبعيات" — أي تمرير الكائنات التي تعتمد عليها الكلاسات بدلاً من إنشائها داخلها. بدل ما الكلاس ينشئ الكائن بنفسه، يتم تمريره إليه من الخارج عبر الـ Constructor. ❌ بدون DI: public class ProductService { private readonly ProductRepository _repo = new ProductRepository(); } ✅ باستخدام DI: public class ProductService { private readonly ProductRepository _repo; public ProductService(ProductRepository repo) { _repo = repo; } } ✅ هذا يجعل الكود أسهل للاختبار، ويمكن تبديل ProductRepository بأي نسخة أخرى عند الحاجة. 🔹 أنواع التسجيل في ASP.NET Core يتم تسجيل الخدمات داخل Program.cs باستخدام واحدة من الطرق التالية: AddSingleton : ...

.NET Core - إضافة التوثيق باستخدام Swagger

5.4 .NET Core - إضافة التوثيق باستخدام Swagger Swagger هو أداة قوية لتوليد واجهة تفاعلية لتوثيق وتجربة Web APIs في ASP.NET Core. يسمح لك بتجربة الـ endpoints، إدخال المعلمات، إرسال التوكن، ورؤية الرد مباشرة من المتصفح. 🔹 ما هو Swagger؟ Swagger (المعروف الآن باسم OpenAPI) يقوم بتوليد صفحة UI تفاعلية تمثل كل API endpoint في مشروعك، ويُستخدم أيضًا لتوليد مستندات JSON قابلة للاستيراد في Postman أو أدوات خارجية. 🔹 تثبيت حزمة Swashbuckle dotnet add package Swashbuckle.AspNetCore 🔹 تهيئة Swagger في Program.cs // في builder.Services builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); // في app app.UseSwagger(); app.UseSwaggerUI(); 🔸 الآن عند تشغيل المشروع، انتقل إلى الرابط: /swagger مثل: https://localhost:5001/swagger 🔹 تخصيص عنوان التوثيق builder.Services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new() { Title = "My API", Version = "v1" }); }); ...

.NET Core - التعامل مع JSON وModel Binding

5.3 .NET Core - التعامل مع JSON وModel Binding في Web APIs باستخدام ASP.NET Core، يتم إرسال واستقبال البيانات عادةً بتنسيق JSON . يتم تحويل هذه البيانات تلقائيًا إلى كائنات C# باستخدام ما يسمى بـ Model Binding ، وهو ميكانيزم مدمج في ASP.NET. 🔹 ما هو JSON؟ JSON (JavaScript Object Notation) هو تنسيق خفيف وسهل القراءة لتمثيل البيانات باستخدام أزواج (key/value). مثال: { "id": 1, "name": "Monitor", "price": 1200 } 🔸 في Web APIs، يتم إرسال هذا النوع من البيانات من وإلى السيرفر تلقائيًا. 🔹 ما هو Model Binding؟ Model Binding هي الآلية التي تستخدمها ASP.NET Core لتحويل البيانات القادمة من الطلب (مثل JSON) إلى كائنات C# تلقائيًا. 📦 مثال على Model: public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } 📨 مثال على API يستقبل JSON: [HttpPost] public IActionResult AddProduct([FromBody] Product product) { return Ok($"تم ا...

.NET Core - استخدام Postman لاختبار الـ APIs

5.2 .NET Core - استخدام Postman لاختبار الـ APIs بعد إنشاء Web API في ASP.NET Core، تحتاج إلى أداة قوية لاختبار هذه الـ APIs قبل ربطها بتطبيق فعلي. وهنا يأتي دور Postman ، وهي أداة مجانية وسهلة الاستخدام لإرسال الطلبات (Requests) واستعراض الردود (Responses). 🔹 ما هو Postman؟ Postman هو تطبيق لسطح المكتب أو المتصفح يُستخدم لاختبار RESTful APIs، يدعم أنواع مختلفة من الطلبات مثل: GET , POST , PUT , DELETE ، ويعرض لك النتيجة بشكل منسق. 🔹 تحميل وتشغيل Postman اذهب إلى https://www.postman.com/downloads/ قم بتنزيل الإصدار المناسب لنظام التشغيل لديك بعد التثبيت، شغّل البرنامج وأنشئ حسابًا (اختياريًا) 🔹 مثال عملي: اختبار API لإدارة المنتجات 📥 1) إرسال طلب GET: GET https://localhost:5001/api/products - اختر GET من القائمة العلوية - أدخل رابط API - اضغط Send 🔸 ستظهر لك قائمة المنتجات في قسم Response. ➕ 2) إرسال طلب POST (إضافة منتج): POST https://localhost:5001/api/products Content-Type: application/json في تبويب Body → اختر raw → واكتب...

.NET Core - إنشاء Web API في ASP.NET Core

5.1 .NET Core - إنشاء Web API في ASP.NET Core Web API هو نوع من التطبيقات يتيح للأنظمة والأجهزة التفاعل معًا من خلال إرسال واستقبال البيانات عبر HTTP. في هذا الدرس سنتعلم كيفية إنشاء Web API باستخدام ASP.NET Core خطوة بخطوة. 🔹 الخطوة 1: إنشاء مشروع Web API جديد dotnet new webapi -n MyApiDemo cd MyApiDemo 📁 سيتم إنشاء مشروع جاهز يحتوي على Controller افتراضي باسم WeatherForecastController . 🔹 محتوى مشروع Web API ستجد المجلدات والملفات التالية: Program.cs : إعدادات التطبيق وتهيئة الـ middleware. Controllers/WeatherForecastController.cs : مثال جاهز على API. appsettings.json : إعدادات التطبيق مثل الاتصال بقاعدة البيانات. 🔹 مثال: إنشاء API لإدارة المنتجات 📄 نموذج Product: public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } 📁 Controller: ProductsController.cs [ApiController] [Route("api/[controller]")] public class ProductsController : Controller...

.NET Core - حماية الـ APIs باستخدام JWT

.NET Core - حماية الـ APIs باستخدام JWT عند بناء Web APIs في ASP.NET Core، واحدة من أكثر الطرق استخدامًا لحمايتها هي استخدام التوثيق بواسطة JWT (JSON Web Token) . JWT تتيح للمستخدم تسجيل الدخول مرة واحدة، ومن ثم يتم إرسال رمز (Token) في كل طلب لاحق للتحقق من الهوية. 🔹 ما هو JWT؟ JWT هو رمز مشفر يحتوي على معلومات المستخدم مثل UserId وRoles وClaims، ويتم توقيعه باستخدام مفتاح سري لضمان صحته. 🔹 تثبيت الحزمة المطلوبة dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer 🔹 إعداد JWT في Program.cs using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true...