using System.IO.Pipes; using System.Text; using System.Text.Json; using PrintServiceTray.Models; namespace PrintServiceTray.Services; public class ServiceClient { private readonly string _pipeName; private readonly int _timeout; public ServiceClient(string pipeName = "PrintServicePipe", int timeoutMs = 5000) { _pipeName = pipeName; _timeout = timeoutMs; } public async Task GetQueueStatusAsync() { try { using var pipe = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut); await pipe.ConnectAsync(_timeout); var request = new QueueStatusRequest(); var requestJson = JsonSerializer.Serialize(request); var requestBytes = Encoding.UTF8.GetBytes(requestJson); await pipe.WriteAsync(requestBytes); await pipe.FlushAsync(); var buffer = new byte[4096]; var bytesRead = await pipe.ReadAsync(buffer); var responseJson = Encoding.UTF8.GetString(buffer, 0, bytesRead); var response = JsonSerializer.Deserialize(responseJson); return response ?? new QueueStatusResponse { Success = false, Message = "Invalid response" }; } catch (TimeoutException) { return new QueueStatusResponse { Success = false, Message = "Service not responding" }; } catch (Exception ex) { return new QueueStatusResponse { Success = false, Message = $"Error: {ex.Message}" }; } } public async Task IsServiceRunningAsync() { try { var response = await GetQueueStatusAsync(); return response.Success; } catch { return false; } } }