Skip to content

Faisal-Sahli/ZKAttendanceService

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

3 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

โš™๏ธ ZKAttendance Service

.NET Version C# License Platform

๐Ÿ“– Overview

Background Windows Service that automatically connects to ZKTeco biometric devices, pulls attendance records, and stores them in SQL Server. Runs continuously with intelligent peak-hour management and bulk processing capabilities.

๐ŸŽฏ Key Features

  • ๐Ÿ”Œ Auto-connects to ZKTeco devices via TCP/IP every 5 minutes
  • ๐Ÿ“ฅ Bulk insert operations (10,000 records/batch)
  • โธ๏ธ Smart scheduling - pauses during peak hours (check-in/check-out)
  • ๐Ÿ”„ Retry logic with 3 automatic attempts
  • ๐ŸŽฏ Incremental sync - only new records (last 365 days)
  • ๐Ÿ”‘ Duplicate prevention using UniqueHash algorithm

๐Ÿ—๏ธ System Architecture

graph LR
    A[โฐ Timer<br/>Every 5 min] --> B{Peak Hour?}
    B -->|Yes| C[โธ๏ธ Skip Cycle]
    B -->|No| D[๐Ÿ”Œ Connect Devices]
    D --> E[๐Ÿ“ฅ Pull Records]
    E --> F[๐Ÿ” Check Duplicates]
    F --> G[๐Ÿ’พ Bulk Insert]
    G --> H[โœ… Update Status]
    H --> I[โฐ Next Cycle]
    C --> I

    style A fill:#e3f2fd
    style B fill:#fff8e1
    style C fill:#ffebee
    style D fill:#e8f5e9
    style E fill:#f3e5f5
    style F fill:#fce4ec
    style G fill:#e0f2f1
    style H fill:#e8f5e9
    style I fill:#e3f2fd
Loading

Sync Process Flow:

โฐ Timer โ†’ Check Peak Hour โ†’ Connect Devices (5 parallel)
   โ†“
๐Ÿ“ฅ Pull Records โ†’ Calculate UniqueHash โ†’ Filter New Records
   โ†“
๐Ÿ’พ Bulk Insert (10k/batch) โ†’ Update Status โ†’ Log Results

Note: Works with ZKAttendanceWeb for complete attendance management.


๐Ÿ› ๏ธ Technology Stack

Core: .NET 8.0 Worker Service โ€ข C# 12 โ€ข Entity Framework Core

Device: zkemkeeper.dll (ZKTeco SDK) โ€ข TCP/IP Protocol

Database: SQL Server 2019+ โ€ข EFCore.BulkExtensions

Architecture: Dependency Injection โ€ข Service Layer โ€ข Repository Pattern


๐Ÿ“ Project Structure

ZKAttendanceService/
โ”œโ”€โ”€ ๐Ÿ“‚ Configuration/            # โš™๏ธ Configuration Classes
โ”‚   โ”œโ”€โ”€ BranchConfiguration.cs       # Branch settings
โ”‚   โ”œโ”€โ”€ DeviceConfiguration.cs       # Device settings
โ”‚   โ”œโ”€โ”€ SyncConfiguration.cs         # Sync timing & behavior
โ”‚   โ””โ”€โ”€ WebApiSettings.cs            # API integration settings
โ”‚
โ”œโ”€โ”€ ๐Ÿ“‚ Data/                     # ๐Ÿ’พ Database Context
โ”‚   โ”œโ”€โ”€ ZKAttendanceWebDbContext.cs  # EF Core DbContext
โ”‚   โ””โ”€โ”€ Migrations/                   # Database migrations
โ”‚
โ”œโ”€โ”€ ๐Ÿ“‚ Models/                   # ๐Ÿ“Š Domain Entities
โ”‚   โ”œโ”€โ”€ AttendanceLog.cs             # Attendance records
โ”‚   โ”œโ”€โ”€ Branch.cs                    # Branch/location info
โ”‚   โ”œโ”€โ”€ Department.cs                # Department data
โ”‚   โ”œโ”€โ”€ Device.cs                    # Biometric device info
โ”‚   โ”œโ”€โ”€ DeviceError.cs               # Device error logs
โ”‚   โ”œโ”€โ”€ DeviceStatus.cs              # Device health status
โ”‚   โ”œโ”€โ”€ Employee.cs                  # Employee information
โ”‚   โ”œโ”€โ”€ Holiday.cs                   # Holiday calendar
โ”‚   โ”œโ”€โ”€ SyncLog.cs                   # Sync operation logs
โ”‚   โ”œโ”€โ”€ SystemSetting.cs             # System settings
โ”‚   โ””โ”€โ”€ WorkShift.cs                 # Work shift definitions
โ”‚
โ”œโ”€โ”€ ๐Ÿ“‚ Services/                 # ๐Ÿ”ง Business Logic Layer
โ”‚   โ”œโ”€โ”€ ConfigurationService.cs      # Config management
โ”‚   โ”œโ”€โ”€ IConfigurationService.cs     # Config interface
โ”‚   โ”œโ”€โ”€ ISyncService.cs              # Sync interface
โ”‚   โ”œโ”€โ”€ IWebApiService.cs            # API interface
โ”‚   โ”œโ”€โ”€ IZKDeviceService.cs          # Device interface
โ”‚   โ”œโ”€โ”€ PeakHourService.cs           # Peak hour logic
โ”‚   โ”œโ”€โ”€ SyncService.cs               # Main sync operations
โ”‚   โ”œโ”€โ”€ WebApiService.cs             # Central server sync
โ”‚   โ””โ”€โ”€ ZKDeviceService.cs           # ZKTeco device communication
โ”‚
โ”œโ”€โ”€ ๐Ÿ“‚ ZKTecoSDK/                # ๐Ÿ“ฆ ZKTeco SDK Files
โ”‚   โ””โ”€โ”€ zkemkeeper.dll               # ZKTeco COM component
โ”‚
โ”œโ”€โ”€ ๐Ÿ“„ appsettings.json          # โš™๏ธ Configuration File
โ”œโ”€โ”€ ๐Ÿ“„ Program.cs                # ๐Ÿš€ Application Entry Point
โ””โ”€โ”€ ๐Ÿ“„ Worker.cs                 # โฐ Background Service Worker

๐Ÿš€ Getting Started

Prerequisites

  • .NET SDK 8.0+
  • SQL Server 2019+
  • ZKTeco SDK (zkemkeeper.dll)
  • Windows 10/Server 2019+
  • ZKTeco Devices

Installation

  1. Clone repository
git clone https://github.com/Faisal-Sahli/ZKAttendanceService.git
cd ZKAttendanceService
  1. Register ZKTeco SDK
regsvr32 "C:\Path\To\zkemkeeper.dll"
  1. Configure settings in appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=YOUR_SERVER;Database=ZKAttendance;Trusted_Connection=True;TrustServerCertificate=True;"
  },
  "DeviceConfiguration": {
    "Devices": [
      {
        "DeviceName": "Main Entrance",
        "DeviceIP": "192.168.1.201",
        "DevicePort": 4370,
        "IsActive": true
      }
    ]
  },
  "SyncConfiguration": {
    "EnableAutoSync": true,
    "SyncIntervalMinutes": 5,
    "SyncLastNDays": 365,
    "MaxRetryAttempts": 3,
    "PeakHours": [
      {
        "Name": "Morning Check-in",
        "StartTime": "07:00",
        "EndTime": "09:00",
        "RunImmediatelyAfter": true
      }
    ]
  }
}
  1. Apply migrations
dotnet restore
dotnet ef database update
  1. Run as console (development)
dotnet run
  1. Install as Windows Service (production)
sc create "ZKAttendanceService" binPath="C:\Path\To\ZKAttendanceService.exe"
sc start "ZKAttendanceService"

๐Ÿ”ง Configuration

Sync Settings

Setting Default Description
EnableAutoSync true Enable/disable auto-sync
SyncIntervalMinutes 5 Frequency in minutes
SyncLastNDays 365 Pull records from last N days
MaxRetryAttempts 3 Retry count on failure

Peak Hours

Configure times when device usage is high to avoid overload:

{
  "Name": "Morning Check-in",
  "StartTime": "07:00",
  "EndTime": "09:00",
  "RunImmediatelyAfter": true
}

๐Ÿ”„ How It Works

Sync Cycle

1. Timer triggers every 5 minutes
2. Check if current time is in peak hours
   โ””โ”€ YES โ†’ Skip cycle
   โ””โ”€ NO  โ†’ Continue
3. Connect to devices (5 parallel connections)
4. Pull all records using ZKTeco SDK
5. Calculate UniqueHash: {UserId}{DeviceId}{DateTime}
6. Query existing hashes from database
7. Filter only new records
8. Bulk insert (10,000 records/batch)
9. Update device status and create sync log
10. Wait for next cycle

Retry Logic

Attempt 1: Immediate
   โ†“ Fail โ†’ Wait 2 seconds
Attempt 2: After 2 seconds
   โ†“ Fail โ†’ Wait 4 seconds
Attempt 3: After 4 seconds
   โ†“ Fail โ†’ Log error and skip

โšก Performance

Metric Value
Sync Speed 1,000-5,000 records/second
Bulk Insert 10,000 records/batch
Parallel Devices 5 simultaneous
Memory Usage ~100-200 MB
CPU Usage 5-15% during sync

Optimization Tips:

  • Add database indexes on UniqueHash and AttendanceTime
  • Adjust batch size in SyncService.cs
  • Configure connection pooling
  • Balance sync interval with system load

๐Ÿ› Troubleshooting

Service fails to start

  • Register zkemkeeper.dll: regsvr32 zkemkeeper.dll
  • Verify .NET 8.0 Runtime is installed
  • Check Windows Event Viewer

Cannot connect to device

  • Verify IP and port (default: 4370)
  • Test connectivity: ping 192.168.x.x
  • Check firewall allows port 4370

Duplicate records

  • Verify UniqueHash calculation
  • Add index: CREATE INDEX IX_UniqueHash ON AttendanceLogs(UniqueHash)
  • Review SyncLogs table

Slow performance

  • Increase batch size in SyncService
  • Add database indexes
  • Reduce SyncLastNDays if not needed

๐Ÿ“Š Database Schema

Main Tables

Table Description
AttendanceLogs Employee attendance records
SyncLogs Sync operation history
DeviceStatuses Device health snapshots
Devices Device configurations

AttendanceLogs Structure

CREATE TABLE AttendanceLogs (
    AttendanceId INT PRIMARY KEY IDENTITY,
    BiometricUserId NVARCHAR(50) NOT NULL,
    AttendanceTime DATETIME2 NOT NULL,
    DeviceId INT NOT NULL,
    UniqueHash NVARCHAR(100) NOT NULL UNIQUE,
    CreatedDate DATETIME2 DEFAULT GETDATE()
);

CREATE INDEX IX_UniqueHash ON AttendanceLogs(UniqueHash);
CREATE INDEX IX_AttendanceTime ON AttendanceLogs(AttendanceTime DESC);

๐ŸŽฏ Roadmap

โœ… Phase 1 - Current

  • Auto-sync with retry logic
  • Bulk operations & peak hour management
  • Incremental sync & duplicate prevention

๐Ÿ”„ Phase 2 - Planned

  • Real-time push notifications from devices
  • Multi-branch support
  • Monitoring dashboard
  • Email alerts on failures

๐Ÿ”ฎ Phase 3 - Future

  • Cloud deployment (Azure)
  • Mobile app integration
  • AI anomaly detection
  • Predictive analytics

๐Ÿค Contributing

Contributions welcome! Please:

  1. Fork the repository
  2. Create feature branch (feature/AmazingFeature)
  3. Write tests and documentation
  4. Submit pull request

Standards: C# conventions, XML documentation, unit tests, meaningful commits


๐Ÿ“ License

MIT License - Copyright (c) 2025 Faisal-Sahli


๐Ÿ‘ค Author

Faisal Al-Sahli - Computer Programmer @ Al-Amal Advanced Medical Company

GitHub LinkedIn

๐Ÿ‡ธ๐Ÿ‡ฆ Riyadh, Saudi Arabia โ€ข 2+ years ASP.NET Core โ€ข Biometric Systems Specialist


๐Ÿ”— Related Projects


โš™๏ธ Automated Biometric Attendance Collection

GitHub last commit GitHub issues GitHub stars

โญ Star this repo if you find it useful!

Report Bug โ€ข Request Feature

Made with โค๏ธ by Faisal-Sahli