Skip to content

Commit 7459f2f

Browse files
committed
Extract interfaces from all agent services. Replace use of static Logger.
1 parent 402d5b0 commit 7459f2f

14 files changed

+182
-106
lines changed

Agent/Program.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,12 +94,12 @@ private static void RegisterServices(IServiceCollection services)
9494
services.AddSingleton<ICpuUtilizationSampler, CpuUtilizationSampler>();
9595
services.AddSingleton<IWakeOnLanService, WakeOnLanService>();
9696
services.AddHostedService(services => services.GetRequiredService<ICpuUtilizationSampler>());
97-
services.AddScoped<ChatClientService>();
98-
services.AddTransient<PSCore>();
99-
services.AddTransient<ExternalScriptingShell>();
100-
services.AddScoped<ConfigService>();
101-
services.AddScoped<Uninstaller>();
102-
services.AddScoped<ScriptExecutor>();
97+
services.AddScoped<IChatClientService, ChatClientService>();
98+
services.AddTransient<IPSCore, PSCore>();
99+
services.AddTransient<IExternalScriptingShell, ExternalScriptingShell>();
100+
services.AddScoped<IConfigService, ConfigService>();
101+
services.AddScoped<IUninstaller, Uninstaller>();
102+
services.AddScoped<IScriptExecutor, ScriptExecutor>();
103103
services.AddScoped<IProcessInvoker, ProcessInvoker>();
104104
services.AddScoped<IUpdateDownloader, UpdateDownloader>();
105105

Agent/Services/AgentHubConnection.cs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -29,31 +29,27 @@ public interface IAgentHubConnection
2929
public class AgentHubConnection : IAgentHubConnection, IDisposable
3030
{
3131
private readonly IAppLauncher _appLauncher;
32-
33-
private readonly ChatClientService _chatService;
34-
35-
private readonly ConfigService _configService;
36-
32+
private readonly IChatClientService _chatService;
33+
private readonly IConfigService _configService;
3734
private readonly IDeviceInformationService _deviceInfoService;
3835
private readonly IHttpClientFactory _httpFactory;
3936
private readonly IWakeOnLanService _wakeOnLanService;
4037
private readonly ILogger<AgentHubConnection> _logger;
4138
private readonly ILogger _fileLogger;
42-
private readonly ScriptExecutor _scriptExecutor;
43-
44-
private readonly Uninstaller _uninstaller;
45-
39+
private readonly IScriptExecutor _scriptExecutor;
40+
private readonly IUninstaller _uninstaller;
4641
private readonly IUpdater _updater;
4742

4843
private ConnectionInfo _connectionInfo;
4944
private HubConnection _hubConnection;
5045
private Timer _heartbeatTimer;
5146
private bool _isServerVerified;
5247

53-
public AgentHubConnection(ConfigService configService,
54-
Uninstaller uninstaller,
55-
ScriptExecutor scriptExecutor,
56-
ChatClientService chatService,
48+
public AgentHubConnection(
49+
IConfigService configService,
50+
IUninstaller uninstaller,
51+
IScriptExecutor scriptExecutor,
52+
IChatClientService chatService,
5753
IAppLauncher appLauncher,
5854
IUpdater updater,
5955
IDeviceInformationService deviceInfoService,

Agent/Services/ChatClientService.cs

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using Immense.RemoteControl.Shared.Models;
22
using Microsoft.AspNetCore.SignalR.Client;
3+
using Microsoft.Extensions.Logging;
34
using Remotely.Agent.Interfaces;
45
using Remotely.Agent.Models;
56
using Remotely.Shared.Models;
@@ -15,18 +16,19 @@
1516

1617
namespace Remotely.Agent.Services
1718
{
18-
public class ChatClientService
19+
public interface IChatClientService
20+
{
21+
Task SendMessage(string senderName, string message, string orgName, string orgId, bool disconnected, string senderConnectionID, HubConnection hubConnection);
22+
}
23+
24+
public class ChatClientService : IChatClientService
1925
{
2026
private readonly IAppLauncher _appLauncher;
27+
private readonly ILogger<ChatClientService> _logger;
2128
private readonly MemoryCache _chatClients = new("ChatClients");
22-
private readonly SemaphoreSlim _messageLock = new(1,1);
23-
24-
public ChatClientService(IAppLauncher appLauncher)
25-
{
26-
_appLauncher = appLauncher;
27-
}
29+
private readonly SemaphoreSlim _messageLock = new(1, 1);
2830

29-
private CacheItemPolicy CacheItemPolicy { get; } = new()
31+
private readonly CacheItemPolicy _cacheItemPolicy = new()
3032
{
3133
SlidingExpiration = TimeSpan.FromMinutes(10),
3234
RemovedCallback = new CacheEntryRemovedCallback(args =>
@@ -48,6 +50,13 @@ public ChatClientService(IAppLauncher appLauncher)
4850
})
4951
};
5052

53+
public ChatClientService(
54+
IAppLauncher appLauncher,
55+
ILogger<ChatClientService> logger)
56+
{
57+
_appLauncher = appLauncher;
58+
_logger = logger;
59+
}
5160

5261
public async Task SendMessage(
5362
string senderName,
@@ -60,7 +69,7 @@ public async Task SendMessage(
6069
{
6170
if (!await _messageLock.WaitAsync(30000))
6271
{
63-
Logger.Write("Timed out waiting for chat message lock.", Shared.Enums.EventType.Warning);
72+
_logger.LogWarning("Timed out waiting for chat message lock.");
6473
return;
6574
}
6675

@@ -80,24 +89,24 @@ public async Task SendMessage(
8089

8190
if (procID > 0)
8291
{
83-
Logger.Write($"Chat app started. Process ID: {procID}");
92+
_logger.LogInformation("Chat app started. Process ID: {procID}", procID);
8493
}
8594
else
8695
{
87-
Logger.Write($"Chat app did not start successfully.");
96+
_logger.LogError($"Chat app did not start successfully.");
8897
return;
8998
}
9099

91100
var clientPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
92101
clientPipe.Connect(15000);
93102
if (!clientPipe.IsConnected)
94103
{
95-
Logger.Write("Failed to connect to chat host.");
104+
_logger.LogError("Failed to connect to chat host.");
96105
return;
97106
}
98107
chatSession = new ChatSession() { PipeStream = clientPipe, ProcessID = procID };
99108
_ = Task.Run(async () => { await ReadFromStream(chatSession.PipeStream, senderConnectionID, hubConnection); });
100-
_chatClients.Add(senderConnectionID, chatSession, CacheItemPolicy);
109+
_chatClients.Add(senderConnectionID, chatSession, _cacheItemPolicy);
101110
}
102111

103112
chatSession = (ChatSession)_chatClients.Get(senderConnectionID);
@@ -116,7 +125,7 @@ public async Task SendMessage(
116125
}
117126
catch (Exception ex)
118127
{
119-
Logger.Write(ex);
128+
_logger.LogError(ex, "Error while sending chat message.");
120129
}
121130
finally
122131
{

Agent/Services/ConfigService.cs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using Remotely.Shared.Models;
1+
using Microsoft.Extensions.Logging;
2+
using Remotely.Shared.Models;
23
using Remotely.Shared.Utilities;
34
using System;
45
using System.Collections.Generic;
@@ -8,11 +9,23 @@
89

910
namespace Remotely.Agent.Services
1011
{
11-
public class ConfigService
12+
public interface IConfigService
13+
{
14+
ConnectionInfo GetConnectionInfo();
15+
void SaveConnectionInfo(ConnectionInfo connectionInfo);
16+
}
17+
18+
public class ConfigService : IConfigService
1219
{
1320
private static readonly object _fileLock = new();
1421
private ConnectionInfo _connectionInfo;
1522
private readonly string _debugGuid = "f2b0a595-5ea8-471b-975f-12e70e0f3497";
23+
private readonly ILogger<ConfigService> _logger;
24+
25+
public ConfigService(ILogger<ConfigService> logger)
26+
{
27+
_logger = logger;
28+
}
1629

1730
private Dictionary<string, string> _commandLineArgs;
1831
private Dictionary<string, string> CommandLineArgs
@@ -74,7 +87,7 @@ public ConnectionInfo GetConnectionInfo()
7487
{
7588
if (!File.Exists("ConnectionInfo.json"))
7689
{
77-
Logger.Write(new Exception("No connection info available. Please create ConnectionInfo.json file with appropriate values."));
90+
_logger.LogError("No connection info available. Please create ConnectionInfo.json file with appropriate values.");
7891
return null;
7992
}
8093
_connectionInfo = JsonSerializer.Deserialize<ConnectionInfo>(File.ReadAllText("ConnectionInfo.json"));

Agent/Services/DeviceInfoGeneratorBase.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
namespace Remotely.Agent.Services
1515
{
16-
public class DeviceInfoGeneratorBase
16+
public abstract class DeviceInfoGeneratorBase
1717
{
1818
protected readonly ILogger<DeviceInfoGeneratorBase> _logger;
1919

Agent/Services/ExternalScriptingShell.cs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using Microsoft.Extensions.DependencyInjection;
2+
using Microsoft.Extensions.Logging;
23
using Remotely.Shared.Enums;
34
using Remotely.Shared.Models;
45
using Remotely.Shared.Utilities;
@@ -15,19 +16,23 @@ namespace Remotely.Agent.Services
1516
{
1617
public interface IExternalScriptingShell
1718
{
18-
19+
ScriptResult WriteInput(string input, TimeSpan timeout);
1920
}
2021

2122
public class ExternalScriptingShell : IExternalScriptingShell
2223
{
2324
private static readonly ConcurrentDictionary<string, ExternalScriptingShell> _sessions = new();
24-
private readonly ConfigService _configService;
25+
private readonly IConfigService _configService;
26+
private readonly ILogger<ExternalScriptingShell> _logger;
2527
private string _lineEnding;
2628
private ScriptingShell _shell;
2729

28-
public ExternalScriptingShell(ConfigService configService)
30+
public ExternalScriptingShell(
31+
IConfigService configService,
32+
ILogger<ExternalScriptingShell> logger)
2933
{
3034
_configService = configService;
35+
_logger = logger;
3136
}
3237

3338
private string ErrorOut { get; set; }
@@ -46,6 +51,7 @@ public ExternalScriptingShell(ConfigService configService)
4651

4752
private Stopwatch Stopwatch { get; set; }
4853

54+
// TODO: Turn into cache and factory.
4955
public static ExternalScriptingShell GetCurrent(ScriptingShell shell, string senderConnectionId)
5056
{
5157
if (_sessions.TryGetValue($"{shell}-{senderConnectionId}", out var session) &&
@@ -112,7 +118,7 @@ public ScriptResult WriteInput(string input, TimeSpan timeout)
112118
}
113119
catch (Exception ex)
114120
{
115-
Logger.Write(ex);
121+
_logger.LogError(ex, "Error while writing input to scripting shell.");
116122
ErrorOut += Environment.NewLine + ex.Message;
117123

118124
// Something's wrong. Let the next command start a new session.

Agent/Services/Linux/AppLauncherLinux.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public class AppLauncherLinux : IAppLauncher
2424
private readonly ILogger<AppLauncherLinux> _logger;
2525

2626
public AppLauncherLinux(
27-
ConfigService configService,
27+
IConfigService configService,
2828
IProcessInvoker processInvoker,
2929
ILogger<AppLauncherLinux> logger)
3030
{

Agent/Services/Linux/UpdaterLinux.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ namespace Remotely.Agent.Services.Linux
2020
public class UpdaterLinux : IUpdater
2121
{
2222
private readonly SemaphoreSlim _checkForUpdatesLock = new(1, 1);
23-
private readonly ConfigService _configService;
23+
private readonly IConfigService _configService;
2424
private readonly IUpdateDownloader _updateDownloader;
2525
private readonly IHttpClientFactory _httpClientFactory;
2626
private readonly ILogger<UpdaterLinux> _logger;
@@ -29,7 +29,7 @@ public class UpdaterLinux : IUpdater
2929
private DateTimeOffset _lastUpdateFailure;
3030

3131
public UpdaterLinux(
32-
ConfigService configService,
32+
IConfigService configService,
3333
IUpdateDownloader updateDownloader,
3434
IHttpClientFactory httpClientFactory,
3535
ILogger<UpdaterLinux> logger)

Agent/Services/MacOS/UpdaterMac.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public class UpdaterMac : IUpdater
2121
{
2222
private readonly string _achitecture = RuntimeInformation.OSArchitecture.ToString().ToLower();
2323
private readonly SemaphoreSlim _checkForUpdatesLock = new(1, 1);
24-
private readonly ConfigService _configService;
24+
private readonly IConfigService _configService;
2525
private readonly IHttpClientFactory _httpClientFactory;
2626
private readonly IUpdateDownloader _updateDownloader;
2727
private readonly ILogger<UpdaterMac> _logger;
@@ -30,7 +30,7 @@ public class UpdaterMac : IUpdater
3030
private readonly System.Timers.Timer _updateTimer = new(TimeSpan.FromHours(6).TotalMilliseconds);
3131

3232
public UpdaterMac(
33-
ConfigService configService,
33+
IConfigService configService,
3434
IUpdateDownloader updateDownloader,
3535
IHttpClientFactory httpClientFactory,
3636
ILogger<UpdaterMac> logger)

0 commit comments

Comments
 (0)