# 🛠️ AGENT C# IMPLEMENTATION GUIDE

## Overview
This guide provides step-by-step instructions for implementing the 5 monitoring features in the PCMonitorAgent C# service.

---

## 📸 FEATURE #1: SCREENSHOT CAPTURE SERVICE

### File to Create:
```
agent-csharp/Services/ScreenshotService.cs
```

### Requirements:
- Capture full screen screenshot every 30 seconds
- Convert to base64 string
- Send to `POST /api/screenshot` endpoint
- Handle errors gracefully

### Code Template:

```csharp
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace PCMonitorAgent.Services
{
    public class ScreenshotService
    {
        private readonly string _agentId;
        private readonly string _apiUrl;
        private readonly HttpClient _httpClient;
        private bool _isRunning = false;

        public ScreenshotService(string agentId, string apiUrl)
        {
            _agentId = agentId;
            _apiUrl = apiUrl;
            _httpClient = new HttpClient();
        }

        // Start screenshot capture service
        public async Task StartAsync()
        {
            _isRunning = true;
            
            while (_isRunning)
            {
                try
                {
                    // Capture screenshot
                    var screenshot = CaptureScreenshot();
                    
                    // Convert to base64
                    string base64 = ImageToBase64(screenshot);
                    
                    // Send to API
                    await SendScreenshotToAPI(base64);
                    
                    // Wait 30 seconds
                    await Task.Delay(TimeSpan.FromSeconds(30));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Screenshot error: {ex.Message}");
                    await Task.Delay(TimeSpan.FromSeconds(5)); // Retry after 5 sec
                }
            }
        }

        // Capture screenshot from entire screen
        private Bitmap CaptureScreenshot()
        {
            int screenWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
            int screenHeight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;

            Bitmap bitmap = new Bitmap(screenWidth, screenHeight, PixelFormat.Format32bppArgb);
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));
            
            return bitmap;
        }

        // Convert image to base64 string
        private string ImageToBase64(Bitmap image)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Save as PNG format for better compression
                image.Save(ms, ImageFormat.Png);
                byte[] imageBytes = ms.ToArray();
                return Convert.ToBase64String(imageBytes);
            }
        }

        // Send screenshot to API
        private async Task SendScreenshotToAPI(string base64Data)
        {
            var json = new
            {
                agent_id = _agentId,
                screenshot_data = base64Data,
                captured_at = DateTime.UtcNow.ToString("O"),
                file_size = base64Data.Length
            };

            var content = new StringContent(
                System.Text.Json.JsonSerializer.Serialize(json),
                Encoding.UTF8,
                "application/json"
            );

            var response = await _httpClient.PostAsync(
                $"{_apiUrl}/api/screenshot",
                content
            );

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"API error: {response.StatusCode}");
            }
        }

        public void Stop()
        {
            _isRunning = false;
        }
    }
}
```

### Integration in Program.cs:

```csharp
var screenshotService = new ScreenshotService(agentId, apiUrl);
_ = screenshotService.StartAsync(); // Fire and forget
```

---

## 📦 FEATURE #2: RUNNING APPLICATIONS MONITOR

### File to Create:
```
agent-csharp/Services/RunningAppsService.cs
```

### Requirements:
- Get list of running processes every 60 seconds
- Collect: process name, window title, CPU %, memory MB, PID, path
- Send to `POST /api/activity` with action=update_processes
- Filter system processes if needed

### Code Template:

```csharp
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text;

namespace PCMonitorAgent.Services
{
    public class RunningAppsService
    {
        private readonly string _agentId;
        private readonly string _apiUrl;
        private readonly HttpClient _httpClient;
        private bool _isRunning = false;
        private PerformanceCounter _cpuCounter;

        public RunningAppsService(string agentId, string apiUrl)
        {
            _agentId = agentId;
            _apiUrl = apiUrl;
            _httpClient = new HttpClient();
            InitializePerformanceCounters();
        }

        private void InitializePerformanceCounters()
        {
            try
            {
                _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            }
            catch { }
        }

        // Start monitoring service
        public async Task StartAsync()
        {
            _isRunning = true;
            
            while (_isRunning)
            {
                try
                {
                    // Get running processes
                    var processes = GetRunningProcesses();
                    
                    // Send to API
                    await SendProcessesToAPI(processes);
                    
                    // Wait 60 seconds
                    await Task.Delay(TimeSpan.FromSeconds(60));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"App monitoring error: {ex.Message}");
                    await Task.Delay(TimeSpan.FromSeconds(10));
                }
            }
        }

        // Get list of running processes with details
        private List<ProcessInfo> GetRunningProcesses()
        {
            var processes = new List<ProcessInfo>();
            
            foreach (var proc in Process.GetProcesses())
            {
                try
                {
                    var windowTitle = GetWindowTitle(proc.Handle);
                    
                    var cpuUsage = 0f;
                    try
                    {
                        var cpuCounter = new PerformanceCounter(
                            "Process",
                            "% Processor Time",
                            proc.ProcessName
                        );
                        cpuUsage = cpuCounter.NextValue();
                    }
                    catch { }

                    var memoryUsage = proc.WorkingSet64; // in bytes

                    processes.Add(new ProcessInfo
                    {
                        ProcessName = proc.ProcessName + ".exe",
                        WindowTitle = windowTitle,
                        CpuUsage = cpuUsage,
                        MemoryUsage = memoryUsage,
                        Pid = proc.Id,
                        Path = proc.MainModule?.FileName ?? ""
                    });
                }
                catch { }
            }

            return processes.OrderByDescending(p => p.MemoryUsage).ToList();
        }

        // Get window title for process
        [DllImport("user32.dll")]
        private static extern int GetWindowTextLength(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        private string GetWindowTitle(IntPtr handle)
        {
            try
            {
                int length = GetWindowTextLength(handle);
                if (length == 0) return "";

                StringBuilder sb = new StringBuilder(length + 1);
                GetWindowText(handle, sb, sb.Capacity);
                return sb.ToString();
            }
            catch { return ""; }
        }

        // Send processes to API
        private async Task SendProcessesToAPI(List<ProcessInfo> processes)
        {
            var json = new
            {
                agent_id = _agentId,
                action = "update_processes",
                applications = processes.Select(p => new
                {
                    process_name = p.ProcessName,
                    window_title = p.WindowTitle,
                    cpu_usage = p.CpuUsage,
                    memory_usage = p.MemoryUsage,
                    pid = p.Pid,
                    path = p.Path,
                    snapshot_at = DateTime.UtcNow.ToString("O")
                }).ToList()
            };

            var content = new StringContent(
                System.Text.Json.JsonSerializer.Serialize(json),
                Encoding.UTF8,
                "application/json"
            );

            var response = await _httpClient.PostAsync(
                $"{_apiUrl}/api/activity",
                content
            );

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"API error: {response.StatusCode}");
            }
        }

        public void Stop()
        {
            _isRunning = false;
        }

        private class ProcessInfo
        {
            public string ProcessName { get; set; }
            public string WindowTitle { get; set; }
            public float CpuUsage { get; set; }
            public long MemoryUsage { get; set; }
            public int Pid { get; set; }
            public string Path { get; set; }
        }
    }
}
```

---

## 📱 FEATURE #3: MEDIA SOCIAL DETECTION

### File to Create:
```
agent-csharp/Services/MediaSocialDetectionService.cs
```

### Requirements:
- Detect active media social platforms every 120 seconds
- Check: active windows, browser tabs, running processes
- Platforms: Facebook, Instagram, TikTok, Twitter, YouTube, WhatsApp, Telegram, Gmail, LinkedIn, Discord, Viber, LINE, Snapchat
- Send to `POST /api/activity` with action=detect_media_social

### Code Template:

```csharp
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;

namespace PCMonitorAgent.Services
{
    public class MediaSocialDetectionService
    {
        private readonly string _agentId;
        private readonly string _apiUrl;
        private readonly HttpClient _httpClient;
        private bool _isRunning = false;
        
        private Dictionary<string, DateTime> _previousDetections;
        
        // Platform detection keywords
        private readonly Dictionary<string, List<string>> _platformKeywords = new()
        {
            { "Facebook", new() { "facebook.com", "facebook - ", "fb", "messenger" } },
            { "Instagram", new() { "instagram.com", "instagram - ", "insta" } },
            { "TikTok", new() { "tiktok.com", "tiktok - ", "tiktok" } },
            { "Twitter", new() { "twitter.com", "twitter - ", "x.com" } },
            { "YouTube", new() { "youtube.com", "youtube - ", "youtube" } },
            { "WhatsApp", new() { "whatsapp", "whatsapp.exe" } },
            { "Telegram", new() { "telegram", "telegram.exe", "web.telegram" } },
            { "Gmail", new() { "gmail.com", "gmail" } },
            { "LinkedIn", new() { "linkedin.com", "linkedin - " } },
            { "Discord", new() { "discord.com", "discord.exe", "discord" } },
            { "Snapchat", new() { "snapchat", "snapchat.exe" } },
            { "Viber", new() { "viber", "viber.exe" } },
            { "LINE", new() { "line", "line.exe" } },
        };

        public MediaSocialDetectionService(string agentId, string apiUrl)
        {
            _agentId = agentId;
            _apiUrl = apiUrl;
            _httpClient = new HttpClient();
            _previousDetections = new Dictionary<string, DateTime>();
        }

        // Start detection service
        public async Task StartAsync()
        {
            _isRunning = true;
            
            while (_isRunning)
            {
                try
                {
                    // Detect active platforms
                    var activeWindows = GetActiveWindowTitles();
                    var runningProcesses = GetRunningProcessNames();
                    var browserTabs = GetBrowserTabs(); // If possible
                    
                    // Analyze and send
                    await AnalyzeAndSend(activeWindows, runningProcesses, browserTabs);
                    
                    // Wait 120 seconds
                    await Task.Delay(TimeSpan.FromSeconds(120));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Media social detection error: {ex.Message}");
                    await Task.Delay(TimeSpan.FromSeconds(30));
                }
            }
        }

        // Get active window titles
        private List<string> GetActiveWindowTitles()
        {
            var titles = new List<string>();
            
            foreach (var proc in Process.GetProcesses())
            {
                try
                {
                    if (proc.MainWindowTitle.Length > 0)
                    {
                        titles.Add(proc.MainWindowTitle.ToLower());
                    }
                }
                catch { }
            }

            return titles;
        }

        // Get running process names
        private List<string> GetRunningProcessNames()
        {
            return Process.GetProcesses()
                .Select(p => p.ProcessName.ToLower())
                .ToList();
        }

        // Detect browser tabs (simplified - would need browser automation)
        private List<string> GetBrowserTabs()
        {
            // This requires Selenium or browser automation
            // For now, return empty list - can be implemented later
            return new List<string>();
        }

        // Analyze activity and send to API
        private async Task AnalyzeAndSend(
            List<string> windows, 
            List<string> processes,
            List<string> tabs)
        {
            var detections = new List<object>();
            var detectedPlatforms = new Dictionary<string, (DateTime time, string type)>();

            // Check each platform
            foreach (var platform in _platformKeywords)
            {
                bool detected = false;
                string detectionType = "";

                // Check windows
                foreach (var keyword in platform.Value)
                {
                    if (windows.Any(w => w.Contains(keyword)))
                    {
                        detected = true;
                        detectionType = "window";
                        break;
                    }
                }

                // Check processes
                if (!detected)
                {
                    foreach (var keyword in platform.Value)
                    {
                        if (processes.Any(p => p.Contains(keyword)))
                        {
                            detected = true;
                            detectionType = "process";
                            break;
                        }
                    }
                }

                // Check tabs (if available)
                if (!detected && tabs.Count > 0)
                {
                    foreach (var keyword in platform.Value)
                    {
                        if (tabs.Any(t => t.Contains(keyword)))
                        {
                            detected = true;
                            detectionType = "browser";
                            break;
                        }
                    }
                }

                if (detected)
                {
                    detectedPlatforms[platform.Key] = (DateTime.UtcNow, detectionType);
                }
            }

            // Send detections to API
            if (detectedPlatforms.Count > 0)
            {
                var json = new
                {
                    agent_id = _agentId,
                    action = "detect_media_social",
                    active_windows = windows,
                    browser_tabs = tabs,
                    process_list = processes,
                    detections = detectedPlatforms.Select(d => new
                    {
                        platform = d.Key,
                        detected_at = d.Value.time.ToString("O"),
                        detection_type = d.Value.type
                    }).ToList()
                };

                var content = new StringContent(
                    System.Text.Json.JsonSerializer.Serialize(json),
                    Encoding.UTF8,
                    "application/json"
                );

                var response = await _httpClient.PostAsync(
                    $"{_apiUrl}/api/activity",
                    content
                );

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception($"API error: {response.StatusCode}");
                }
            }
        }

        public void Stop()
        {
            _isRunning = false;
        }
    }
}
```

---

## 🚫 FEATURE #4: BANDWIDTH LIMITER COMMAND HANDLER

### File to Create:
```
agent-csharp/Services/BandwidthLimiterService.cs
```

### Requirements:
- Poll `GET /api/command?type=throttle_bandwidth` every 30 seconds
- Execute bandwidth limiting via Windows API or NetLimiter
- Report status back to API

### Code Template:

```csharp
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text.Json;

namespace PCMonitorAgent.Services
{
    public class BandwidthLimiterService
    {
        private readonly string _agentId;
        private readonly string _apiUrl;
        private readonly HttpClient _httpClient;
        private bool _isRunning = false;

        public BandwidthLimiterService(string agentId, string apiUrl)
        {
            _agentId = agentId;
            _apiUrl = apiUrl;
            _httpClient = new HttpClient();
        }

        // Start polling for bandwidth commands
        public async Task StartAsync()
        {
            _isRunning = true;
            
            while (_isRunning)
            {
                try
                {
                    // Poll for commands
                    var command = await GetBandwidthCommand();
                    
                    if (command != null)
                    {
                        // Execute bandwidth limitation
                        await ExecuteBandwidthLimit(command);
                    }
                    
                    // Poll every 30 seconds
                    await Task.Delay(TimeSpan.FromSeconds(30));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Bandwidth limiter error: {ex.Message}");
                    await Task.Delay(TimeSpan.FromSeconds(10));
                }
            }
        }

        // Get pending bandwidth command from API
        private async Task<BandwidthCommand> GetBandwidthCommand()
        {
            try
            {
                var response = await _httpClient.GetAsync(
                    $"{_apiUrl}/api/command?agent_id={_agentId}&type=throttle_bandwidth"
                );

                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var doc = JsonDocument.Parse(json);
                    var root = doc.RootElement;

                    if (root.GetProperty("success").GetBoolean())
                    {
                        var cmdData = root.GetProperty("command");
                        return new BandwidthCommand
                        {
                            LimitKbps = cmdData.GetProperty("limit_kbps").GetInt32(),
                            IssuedAt = cmdData.GetProperty("issued_at").GetString()
                        };
                    }
                }
            }
            catch { }

            return null;
        }

        // Execute bandwidth limiting
        private async Task ExecuteBandwidthLimit(BandwidthCommand command)
        {
            try
            {
                // Implementation depends on OS and available APIs
                // Option 1: Use Windows QoS
                // Option 2: Use NetLimiter API
                // Option 3: Use WMI
                
                // For now, log the command
                Console.WriteLine($"Bandwidth limit command: {command.LimitKbps} Kbps");

                // TODO: Implement actual bandwidth limiting
                // This requires native Windows APIs or third-party libraries
                
                await ReportCommandStatus("success", "Bandwidth limited to " + command.LimitKbps + " Kbps");
            }
            catch (Exception ex)
            {
                await ReportCommandStatus("failed", ex.Message);
            }
        }

        // Report command execution status
        private async Task ReportCommandStatus(string status, string message)
        {
            var json = new
            {
                agent_id = _agentId,
                command_type = "throttle_bandwidth",
                status = status,
                message = message,
                executed_at = DateTime.UtcNow.ToString("O")
            };

            var content = new System.Net.Http.StringContent(
                System.Text.Json.JsonSerializer.Serialize(json),
                System.Text.Encoding.UTF8,
                "application/json"
            );

            await _httpClient.PostAsync($"{_apiUrl}/api/command/status", content);
        }

        public void Stop()
        {
            _isRunning = false;
        }

        private class BandwidthCommand
        {
            public int LimitKbps { get; set; }
            public string IssuedAt { get; set; }
        }
    }
}
```

---

## 🔌 FEATURE #5: SHUTDOWN COMMAND HANDLER

### File to Create:
```
agent-csharp/Services/ShutdownCommandService.cs
```

### Requirements:
- Poll `GET /api/command?type=shutdown` every 60 seconds
- Execute PC shutdown with optional delay
- Report status back to API

### Code Template:

```csharp
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text.Json;

namespace PCMonitorAgent.Services
{
    public class ShutdownCommandService
    {
        private readonly string _agentId;
        private readonly string _apiUrl;
        private readonly HttpClient _httpClient;
        private bool _isRunning = false;

        public ShutdownCommandService(string agentId, string apiUrl)
        {
            _agentId = agentId;
            _apiUrl = apiUrl;
            _httpClient = new HttpClient();
        }

        // Start polling for shutdown commands
        public async Task StartAsync()
        {
            _isRunning = true;
            
            while (_isRunning)
            {
                try
                {
                    // Poll for commands
                    var command = await GetShutdownCommand();
                    
                    if (command != null)
                    {
                        // Execute shutdown
                        ExecuteShutdown(command);
                    }
                    
                    // Poll every 60 seconds
                    await Task.Delay(TimeSpan.FromSeconds(60));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Shutdown command error: {ex.Message}");
                    await Task.Delay(TimeSpan.FromSeconds(10));
                }
            }
        }

        // Get pending shutdown command from API
        private async Task<ShutdownCommand> GetShutdownCommand()
        {
            try
            {
                var response = await _httpClient.GetAsync(
                    $"{_apiUrl}/api/command?agent_id={_agentId}&type=shutdown"
                );

                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var doc = JsonDocument.Parse(json);
                    var root = doc.RootElement;

                    if (root.GetProperty("success").GetBoolean())
                    {
                        var cmdData = root.GetProperty("command");
                        return new ShutdownCommand
                        {
                            DelaySeconds = cmdData.GetProperty("delay_seconds").GetInt32(),
                            Force = cmdData.GetProperty("force").GetBoolean()
                        };
                    }
                }
            }
            catch { }

            return null;
        }

        // Execute PC shutdown
        private void ExecuteShutdown(ShutdownCommand command)
        {
            try
            {
                string args = $"/s";
                
                if (command.DelaySeconds > 0)
                {
                    args += $" /t {command.DelaySeconds}";
                }

                if (command.Force)
                {
                    args += " /f";
                }

                Process.Start("shutdown.exe", args);
                Console.WriteLine($"Shutdown command executed: {args}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to execute shutdown: {ex.Message}");
            }
        }

        public void Stop()
        {
            _isRunning = false;
        }

        private class ShutdownCommand
        {
            public int DelaySeconds { get; set; }
            public bool Force { get; set; }
        }
    }
}
```

---

## 🔧 INTEGRATION IN PROGRAM.CS

Update your `Program.cs` to start all services:

```csharp
using PCMonitorAgent.Services;

// Initialize services
var screenshotService = new ScreenshotService(agentId, apiUrl);
var appsService = new RunningAppsService(agentId, apiUrl);
var mediaService = new MediaSocialDetectionService(agentId, apiUrl);
var bandwidthService = new BandwidthLimiterService(agentId, apiUrl);
var shutdownService = new ShutdownCommandService(agentId, apiUrl);

// Start all services (fire and forget)
_ = screenshotService.StartAsync();
_ = appsService.StartAsync();
_ = mediaService.StartAsync();
_ = bandwidthService.StartAsync();
_ = shutdownService.StartAsync();

// Keep application running
Console.WriteLine("PCMonitorAgent running with all services...");
await Task.Delay(Timeout.Infinite);
```

---

## 📊 DEPENDENCIES

Add to `PCMonitorAgent.csproj`:

```xml
<ItemGroup>
    <PackageReference Include="System.Drawing.Common" Version="7.0.0" />
    <PackageReference Include="System.Diagnostics.PerformanceCounter" Version="7.0.0" />
    <!-- Optional for browser tab detection -->
    <!-- <PackageReference Include="Selenium.WebDriver" Version="4.0.0" /> -->
</ItemGroup>
```

---

## ✅ TESTING CHECKLIST

- [ ] ScreenshotService: Screenshot captured and saved to /screenshots/
- [ ] RunningAppsService: App list appearing on dashboard
- [ ] MediaSocialDetectionService: Platforms detected when accessed
- [ ] BandwidthLimiterService: Commands queued and executed
- [ ] ShutdownCommandService: Shutdown command preventing test

---

## 🚀 DEPLOYMENT

Once all services are implemented:

1. Build in Release mode
2. Test locally
3. Publish to /agent-csharp/bin/Release/
4. Update PCMonitorAgent service
5. Restart service
6. Verify data flowing to API

---

**Last Updated:** 2026-03-28  
**Estimated Implementation Time:** 4-6 hours  
**Difficulty:** Intermediate

