- Project Overview
- ChatServer Documentation
- ChatClient Documentation
- Architecture Overview
- API Endpoints
- Database Schema
- Security Implementation
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
- 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
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
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)
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
Development-specific settings:
- Reduced logging levels for development environment
- Simplified error handling
Purpose: Handles user authentication and registration Endpoints:
POST /api/auth/register: User registration with validationPOST /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
Purpose: Manages conversations and messages Endpoints:
GET /api/messages/conversations: Retrieve user's conversationsGET /api/messages/history/{conversationId}: Get message historyPOST /api/messages/send: Send new messagePOST /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
Purpose: User management and search functionality Endpoints:
GET /api/users/search: Search users by username or display nameGET /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
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
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
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
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
Purpose: Request object for login endpoint Properties:
- Username: User's username
- Password: User's password
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)
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
Purpose: Request object for registration endpoint Properties:
- Username: Desired username
- Email: User's email address
- Password: Desired password
- ConfirmPassword: Password confirmation
Purpose: Request object for sending messages Properties:
- ReceiverId: Target user ID
- Content: Message content
Purpose: Data transfer object for user information Properties:
- Id: User ID
- Username: Username
- Email: Email address
- DisplayName: Display name
- IsOnline: Online status
Purpose: Interface for JWT token operations Methods:
GenerateToken(User user): Creates JWT token for userValidateToken(string token): Validates token and returns user ID
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
Purpose: Interface for password hashing operations Methods:
HashPassword(string password): Creates secure password hashVerifyPassword(string password, string hash): Verifies password against hash
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
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
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 connectionOnDisconnectedAsync(): Handles user disconnectionSendMessage(): Broadcasts messages to recipientsMarkAsRead(): Handles read receiptsNotifyTyping(): Sends typing indicators
Events:
ReceiveMessage: New message receivedMessageSent: Message sent confirmationMessageDelivered: Message delivery confirmationMessageRead: Message read confirmationUserTyping: Typing indicatorError: Error notifications
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
Purpose: Application entry point and initialization Features:
- Custom application startup logic
- LoginWindow as initial window
- MainWindow only opened after successful authentication
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)
Purpose: Windows app package manifest Features:
- Application identity and publisher information
- Visual elements and branding
- Capability declarations (runFullTrust)
- Target device family specifications
Purpose: Represents a contact in the chat sidebar Properties:
- Name: Contact's display name
- LastMessage: Preview of last message
- LastMessageTime: Timestamp of last message
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
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
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 authenticationRegisterAsync(): User registrationGetConversationsAsync(): Retrieve user conversationsGetMessageHistoryAsync(): Get conversation historySendMessageAsync(): Send new messageSearchUsersAsync(): Search for users
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 receivedMessageSent: Message sent confirmationMessageDelivered: Message delivery confirmationMessageRead: Message read confirmationUserTyping: Typing indicatorErrorOccurred: Error notifications
Methods:
ConnectAsync(): Establish SignalR connectionSendMessageAsync(): Send real-time messageMarkAsReadAsync(): Send read receiptNotifyTypingAsync(): Send typing indicatorDisconnectAsync(): Clean connection shutdown
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
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
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)
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
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
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
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
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 sidebarMessageItem: Represents a message in the chat
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ ChatClient │ │ ChatServer │ │ Azure SQL DB │
│ (WinUI 3) │◄──►│ (ASP.NET) │◄──►│ │
│ │ │ │ │ │
│ - LoginWindow │ │ - Controllers │ │ - Users │
│ - MainWindow │ │ - SignalR Hub │ │ - Conversations │
│ - Services │ │ - Services │ │ - Messages │
│ - Models │ │ - Models │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
- Authentication: Client → REST API → JWT Token
- Real-time Messaging: Client ↔ SignalR Hub ↔ Database
- Message History: Client → REST API → Database
- User Search: Client → REST API → Database
- 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
POST /api/auth/login- User loginPOST /api/auth/register- User registration
GET /api/messages/conversations- Get user conversationsGET /api/messages/history/{conversationId}- Get message historyPOST /api/messages/send- Send messagePOST /api/messages/mark-delivered/{messageId}- Mark as delivered
GET /api/users/search- Search usersGET /api/users/{id}- Get user details
/chatHub- Real-time communication endpoint
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
);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)
);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)
);- 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
- PBKDF2: Industry-standard key derivation
- Salt: Unique 128-bit salt per password
- Iterations: 10,000 iterations for security
- Timing Attack Protection: Fixed-time comparison
- HTTPS: All communications encrypted
- Input Sanitization: Comprehensive validation
- SQL Injection Prevention: Parameterized queries
- CORS Configuration: Controlled cross-origin access
- 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.