Skip to content

ubejdullah/ChatApp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 

Repository files navigation

ChatApp Complete Documentation

Table of Contents

  1. Project Overview
  2. ChatServer Documentation
  3. ChatClient Documentation
  4. Architecture Overview
  5. API Endpoints
  6. Database Schema
  7. Security Implementation

Project Overview

The ChatApp is a modern real-time chat application consisting of two main components:

  • ChatServer: ASP.NET Core Web API backend with SignalR for real-time communication
  • ChatClient: WinUI 3 desktop application with modern UI design

Key Features

  • Real-time messaging using SignalR
  • User authentication with JWT tokens
  • Secure password hashing
  • Message delivery and read status
  • Online/offline status tracking
  • Modern WinUI 3 interface
  • Azure SQL Database integration
  • Automatic database keep-alive service

ChatServer Documentation

Core Files

Program.cs

Purpose: Main entry point and application configuration Key Components:

  • JWT Authentication setup with custom events for SignalR
  • Entity Framework Core configuration with Azure SQL Server
  • CORS policy configuration for cross-origin requests
  • SignalR hub mapping
  • Database keep-alive background service
  • Comprehensive logging configuration

Database Keep-Alive Service:

  • Prevents Azure SQL Database from going to sleep
  • Executes every minute with a simple COUNT query
  • Includes retry logic and error handling
  • Logs connection status and response times

ChatServer.csproj

Dependencies:

  • .NET 9.0 framework
  • Microsoft.AspNetCore.Authentication.JwtBearer (9.0.0)
  • Microsoft.AspNetCore.OpenApi (9.0.8)
  • Microsoft.AspNetCore.SignalR (1.2.0)
  • Microsoft.EntityFrameworkCore (9.0.8)
  • Microsoft.EntityFrameworkCore.SqlServer (9.0.8)
  • System.IdentityModel.Tokens.Jwt (8.3.1)

Configuration Files

appsettings.json

Database Configuration:

  • Azure SQL Server connection string
  • Retry policy settings (3 retries, 30-second delay)

JWT Settings:

  • Secret key for token signing
  • Issuer: "ChatApp.Backend"
  • Audience: "ChatApp.Client"
  • Token expiration: 1440 minutes (24 hours)

Logging Configuration:

  • Information level for default logging
  • Warning level for ASP.NET Core components
  • Information level for SignalR

appsettings.Development.json

Development-specific settings:

  • Reduced logging levels for development environment
  • Simplified error handling

Controllers

AuthController.cs

Purpose: Handles user authentication and registration Endpoints:

  • POST /api/auth/register: User registration with validation
  • POST /api/auth/login: User authentication

Features:

  • Comprehensive input validation (username, email, password)
  • Password confirmation matching
  • Username and email uniqueness checks
  • Automatic JWT token generation on successful registration/login
  • German error messages for user-friendly feedback
  • Detailed logging for security monitoring

MessagesController.cs

Purpose: Manages conversations and messages Endpoints:

  • GET /api/messages/conversations: Retrieve user's conversations
  • GET /api/messages/history/{conversationId}: Get message history
  • POST /api/messages/send: Send new message
  • POST /api/messages/mark-delivered/{messageId}: Mark message as delivered

Features:

  • Automatic conversation creation when sending first message
  • Message read status tracking
  • Unread message count calculation
  • Conversation ordering by last message time
  • Automatic message truncation for conversation previews

UsersController.cs

Purpose: User management and search functionality Endpoints:

  • GET /api/users/search: Search users by username or display name
  • GET /api/users/{id}: Get specific user information

Features:

  • User search with query parameter
  • Excludes current user from search results
  • Returns limited results (max 20 users)
  • Online status information

Models

User.cs

Properties:

  • Id: Primary key
  • Username: Unique username (max 50 chars)
  • Email: Unique email address (max 100 chars)
  • PasswordHash: Secure password hash (max 255 chars)
  • DisplayName: User's display name (max 100 chars)
  • CreatedAt: Account creation timestamp
  • LastLoginAt: Last login timestamp
  • IsOnline: Current online status

Navigation Properties:

  • SentMessages: Collection of sent messages
  • ReceivedMessages: Collection of received messages

Conversation.cs

Properties:

  • Id: Primary key
  • Participant1Id: First participant user ID
  • Participant2Id: Second participant user ID
  • CreatedAt: Conversation creation timestamp
  • LastMessageAt: Last message timestamp
  • LastMessageContent: Preview of last message (max 500 chars)

Navigation Properties:

  • Participant1: First participant user object
  • Participant2: Second participant user object
  • Messages: Collection of conversation messages

Message.cs

Properties:

  • Id: Primary key
  • ConversationId: Foreign key to conversation
  • SenderId: Message sender user ID
  • ReceiverId: Message receiver user ID
  • Content: Message content
  • SentAt: Message send timestamp
  • IsDelivered: Delivery status
  • DeliveredAt: Delivery timestamp
  • IsRead: Read status
  • ReadAt: Read timestamp

Navigation Properties:

  • Conversation: Parent conversation object
  • Sender: Message sender user object
  • Receiver: Message receiver user object

DTOs (Data Transfer Objects)

ConversationDto.cs

Purpose: Data transfer object for conversation information Properties:

  • Id: Conversation ID
  • OtherUser: UserDto of the other participant
  • LastMessage: Preview of last message
  • LastMessageTime: Timestamp of last message
  • UnreadCount: Number of unread messages

LoginRequest.cs

Purpose: Request object for login endpoint Properties:

  • Username: User's username
  • Password: User's password

LoginResponse.cs

Purpose: Response object for authentication endpoints Properties:

  • Success: Boolean indicating success/failure
  • Token: JWT token (if successful)
  • ErrorMessage: Error description (if failed)
  • User: UserDto with user information (if successful)

MessageDto.cs

Purpose: Data transfer object for message information Properties:

  • Id: Message ID
  • ConversationId: Parent conversation ID
  • SenderId: Sender user ID
  • ReceiverId: Receiver user ID
  • Content: Message content
  • SentAt: Send timestamp
  • IsDelivered: Delivery status
  • IsRead: Read status
  • SenderName: Display name of sender

RegisterRequest.cs

Purpose: Request object for registration endpoint Properties:

  • Username: Desired username
  • Email: User's email address
  • Password: Desired password
  • ConfirmPassword: Password confirmation

SendMessageRequest.cs

Purpose: Request object for sending messages Properties:

  • ReceiverId: Target user ID
  • Content: Message content

UserDto.cs

Purpose: Data transfer object for user information Properties:

  • Id: User ID
  • Username: Username
  • Email: Email address
  • DisplayName: Display name
  • IsOnline: Online status

Services

IJwtService.cs

Purpose: Interface for JWT token operations Methods:

  • GenerateToken(User user): Creates JWT token for user
  • ValidateToken(string token): Validates token and returns user ID

JwtService.cs

Purpose: Implementation of JWT token operations Features:

  • Symmetric key encryption using HMAC SHA256
  • Configurable token expiration
  • Claims-based authentication
  • Token validation with comprehensive error handling

IPasswordHasher.cs

Purpose: Interface for password hashing operations Methods:

  • HashPassword(string password): Creates secure password hash
  • VerifyPassword(string password, string hash): Verifies password against hash

PasswordHasher.cs

Purpose: Implementation of secure password hashing Features:

  • PBKDF2 key derivation with SHA256
  • 128-bit salt generation
  • 256-bit key size
  • 10,000 iterations for security
  • Timing attack protection using fixed-time comparison

Data Layer

ChatDbContext.cs

Purpose: Entity Framework Core database context Features:

  • SQL Server provider configuration
  • Entity configuration with constraints and relationships
  • Unique indexes on username and email
  • Cascade delete configuration for messages
  • Foreign key relationships with proper delete behaviors

Entity Configurations:

  • User: Unique constraints on username and email
  • Conversation: Unique constraint on participant pair
  • Message: Proper foreign key relationships and cascading

SignalR Hub

ChatHub.cs

Purpose: Real-time communication hub using SignalR Features:

  • Connection management with user tracking
  • Online/offline status updates
  • Real-time message broadcasting
  • Message delivery confirmation
  • Read receipt functionality
  • Typing indicator support
  • Comprehensive error handling and logging

Hub Methods:

  • OnConnectedAsync(): Handles user connection
  • OnDisconnectedAsync(): Handles user disconnection
  • SendMessage(): Broadcasts messages to recipients
  • MarkAsRead(): Handles read receipts
  • NotifyTyping(): Sends typing indicators

Events:

  • ReceiveMessage: New message received
  • MessageSent: Message sent confirmation
  • MessageDelivered: Message delivery confirmation
  • MessageRead: Message read confirmation
  • UserTyping: Typing indicator
  • Error: Error notifications

ChatClient Documentation

Core Files

App.xaml

Purpose: Application-wide XAML resources and styling Features:

  • WinUI 3 control resources integration
  • Theme-specific color definitions (Light/Dark/Fallback)
  • Custom button styles with hover effects
  • Harmonious color scheme for chat bubbles
  • Consistent visual design across the application

App.xaml.cs

Purpose: Application entry point and initialization Features:

  • Custom application startup logic
  • LoginWindow as initial window
  • MainWindow only opened after successful authentication

ChatClient.csproj

Configuration:

  • .NET 8.0 with Windows 10.0.19041.0 target
  • WinUI 3 framework integration
  • MSIX packaging support
  • Multi-platform support (x86, x64, ARM64)
  • Self-contained deployment option

Dependencies:

  • Microsoft.AspNetCore.SignalR.Client (9.0.9)
  • Microsoft.WindowsAppSDK (1.8.250907003)
  • Microsoft.Windows.SDK.BuildTools (10.0.26100.4948)

Package.appxmanifest

Purpose: Windows app package manifest Features:

  • Application identity and publisher information
  • Visual elements and branding
  • Capability declarations (runFullTrust)
  • Target device family specifications

Models

ChatContact.cs

Purpose: Represents a contact in the chat sidebar Properties:

  • Name: Contact's display name
  • LastMessage: Preview of last message
  • LastMessageTime: Timestamp of last message

ChatMessage.cs

Purpose: Represents a chat message in conversation Properties:

  • Text: Message content
  • Timestamp: When message was sent
  • IsFromMe: Whether message was sent by current user
  • SenderName: Display name of sender
  • IsDelivered: Delivery status for sent messages

User.cs

Purpose: Represents a registered user (client-side model) Properties:

  • Username: Unique username
  • Email: User's email address
  • Password: Hashed password (note: for client-side validation only)
  • RegistrationDate: Account creation date
  • DisplayName: User's display name

Services

ApiService.cs

Purpose: HTTP client service for API communication Features:

  • Centralized API endpoint management
  • JWT token management and automatic header injection
  • Comprehensive error handling with user-friendly messages
  • Response wrapper for consistent error handling

Base URL: https://chat-app-api-aka3c3cmaab9fdh0.germanywestcentral-01.azurewebsites.net

Methods:

  • LoginAsync(): User authentication
  • RegisterAsync(): User registration
  • GetConversationsAsync(): Retrieve user conversations
  • GetMessageHistoryAsync(): Get conversation history
  • SendMessageAsync(): Send new message
  • SearchUsersAsync(): Search for users

SignalRService.cs

Purpose: Real-time communication service using SignalR Features:

  • Automatic connection management with reconnection
  • Event-driven architecture for message handling
  • Connection state monitoring
  • Comprehensive error handling and logging

Events:

  • MessageReceived: New message received
  • MessageSent: Message sent confirmation
  • MessageDelivered: Message delivery confirmation
  • MessageRead: Message read confirmation
  • UserTyping: Typing indicator
  • ErrorOccurred: Error notifications

Methods:

  • ConnectAsync(): Establish SignalR connection
  • SendMessageAsync(): Send real-time message
  • MarkAsReadAsync(): Send read receipt
  • NotifyTypingAsync(): Send typing indicator
  • DisconnectAsync(): Clean connection shutdown

Helpers

AnimationHelper.cs

Purpose: Reusable animation utilities for UI enhancements Features:

  • Fade-in/fade-out animations
  • Slide-in animations with customizable direction
  • Shake animations for error feedback
  • Pop-in animations with bounce effects
  • Combined entrance animations
  • Smooth easing functions for natural motion

ValidationHelper.cs

Purpose: Input validation utilities Features:

  • String validation (not empty, minimum length)
  • Email format validation
  • Password strength validation
  • Password confirmation matching
  • Username format validation
  • Comprehensive validation with error messages

Views

Authentication Views

LoginWindow.xaml

Purpose: User authentication interface Features:

  • Modern two-panel layout with branding
  • Mica backdrop for Windows 11 integration
  • Animated form entrance
  • Real-time validation feedback
  • Error message animations with shake effects
  • Keyboard navigation support (Enter key)
LoginWindow.xaml.cs

Purpose: Login window logic and event handling Features:

  • Form validation and submission
  • API service integration
  • Animated transitions between windows
  • Error handling with user feedback
  • Success animations before navigation
  • Keyboard event handling
RegisterWindow.xaml

Purpose: User registration interface Features:

  • Comprehensive registration form
  • Input validation with real-time feedback
  • Success and error message animations
  • Scrollable content for smaller screens
  • Consistent design with login window
RegisterWindow.xaml.cs

Purpose: Registration window logic and event handling Features:

  • Multi-field validation
  • API service integration for registration
  • Animated feedback for all validation states
  • Automatic redirection after successful registration
  • Comprehensive error handling

Chat Views

MainWindow.xaml

Purpose: Main chat application interface Features:

  • Three-panel layout (sidebar, header, messages, input)
  • Modern chat bubble design
  • Real-time message display
  • Search functionality for conversations
  • New chat creation interface
  • Responsive design with proper spacing
MainWindow.xaml.cs

Purpose: Main window logic and chat functionality Features:

  • SignalR connection management
  • Real-time message handling
  • Conversation management
  • Message caching for performance
  • Animated message entrance effects
  • Online status tracking
  • Memory-efficient message display
  • Automatic scroll to bottom
  • Message delivery and read status indicators

Key Classes:

  • ConversationItem: Represents a conversation in the sidebar
  • MessageItem: Represents a message in the chat

Architecture Overview

System Architecture

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   ChatClient    │    │   ChatServer    │    │  Azure SQL DB   │
│   (WinUI 3)     │◄──►│   (ASP.NET)     │◄──►│                 │
│                 │    │                 │    │                 │
│ - LoginWindow   │    │ - Controllers   │    │ - Users         │
│ - MainWindow    │    │ - SignalR Hub   │    │ - Conversations │
│ - Services      │    │ - Services      │    │ - Messages      │
│ - Models        │    │ - Models        │    │                 │
└─────────────────┘    └─────────────────┘    └─────────────────┘

Communication Flow

  1. Authentication: Client → REST API → JWT Token
  2. Real-time Messaging: Client ↔ SignalR Hub ↔ Database
  3. Message History: Client → REST API → Database
  4. User Search: Client → REST API → Database

Security Implementation

  • JWT Authentication: Secure token-based authentication
  • Password Hashing: PBKDF2 with SHA256 and salt
  • HTTPS: All communications encrypted
  • Input Validation: Comprehensive server-side validation
  • SQL Injection Protection: Entity Framework Core parameterized queries

API Endpoints

Authentication

  • POST /api/auth/login - User login
  • POST /api/auth/register - User registration

Messages

  • GET /api/messages/conversations - Get user conversations
  • GET /api/messages/history/{conversationId} - Get message history
  • POST /api/messages/send - Send message
  • POST /api/messages/mark-delivered/{messageId} - Mark as delivered

Users

  • GET /api/users/search - Search users
  • GET /api/users/{id} - Get user details

SignalR Hub

  • /chatHub - Real-time communication endpoint

Database Schema

Users Table

CREATE TABLE Users (
    Id int IDENTITY(1,1) PRIMARY KEY,
    Username nvarchar(50) NOT NULL UNIQUE,
    Email nvarchar(100) NOT NULL UNIQUE,
    PasswordHash nvarchar(255) NOT NULL,
    DisplayName nvarchar(100) NOT NULL,
    CreatedAt datetime2 NOT NULL,
    LastLoginAt datetime2,
    IsOnline bit NOT NULL
);

Conversations Table

CREATE TABLE Conversations (
    Id int IDENTITY(1,1) PRIMARY KEY,
    Participant1Id int NOT NULL,
    Participant2Id int NOT NULL,
    CreatedAt datetime2 NOT NULL,
    LastMessageAt datetime2,
    LastMessageContent nvarchar(500),
    FOREIGN KEY (Participant1Id) REFERENCES Users(Id),
    FOREIGN KEY (Participant2Id) REFERENCES Users(Id),
    UNIQUE (Participant1Id, Participant2Id)
);

Messages Table

CREATE TABLE Messages (
    Id int IDENTITY(1,1) PRIMARY KEY,
    ConversationId int NOT NULL,
    SenderId int NOT NULL,
    ReceiverId int NOT NULL,
    Content nvarchar(max) NOT NULL,
    SentAt datetime2 NOT NULL,
    IsDelivered bit NOT NULL,
    DeliveredAt datetime2,
    IsRead bit NOT NULL,
    ReadAt datetime2,
    FOREIGN KEY (ConversationId) REFERENCES Conversations(Id) ON DELETE CASCADE,
    FOREIGN KEY (SenderId) REFERENCES Users(Id),
    FOREIGN KEY (ReceiverId) REFERENCES Users(Id)
);

Security Implementation

Authentication & Authorization

  • JWT Tokens: Secure, stateless authentication
  • Token Validation: Comprehensive server-side validation
  • SignalR Authentication: JWT token passed via query string
  • Authorization: Role-based access control ready

Password Security

  • PBKDF2: Industry-standard key derivation
  • Salt: Unique 128-bit salt per password
  • Iterations: 10,000 iterations for security
  • Timing Attack Protection: Fixed-time comparison

Data Protection

  • HTTPS: All communications encrypted
  • Input Sanitization: Comprehensive validation
  • SQL Injection Prevention: Parameterized queries
  • CORS Configuration: Controlled cross-origin access

Error Handling

  • Logging: Comprehensive security event logging
  • Error Messages: User-friendly without information disclosure
  • Exception Handling: Graceful error recovery
  • Validation: Multi-layer input validation

This documentation provides a comprehensive overview of the entire ChatApp codebase, covering both the server-side API and client-side application with detailed explanations of each component's purpose, functionality, and implementation details.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages