الملفات
pingerino/Services/ConfigurationService.cs

118 أسطر
3.7 KiB
C#

using System;
using System.Drawing;
using Pingerino.Services.Interfaces;
namespace Pingerino.Services
{
public class ConfigurationService : IConfigurationService
{
private readonly ILoggingService _logger;
public ConfigurationService(ILoggingService logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
Load();
}
public T GetValue<T>(string key, T defaultValue = default)
{
try
{
var property = Properties.Settings.Default.GetType().GetProperty(key);
if (property != null)
{
var value = property.GetValue(Properties.Settings.Default);
if (value != null && value is T)
{
return (T)value;
}
}
return defaultValue;
}
catch (Exception ex)
{
_logger.LogError($"Error getting configuration value for key: {key}", ex);
return defaultValue;
}
}
public void SetValue<T>(string key, T value)
{
try
{
var property = Properties.Settings.Default.GetType().GetProperty(key);
if (property != null && property.CanWrite)
{
property.SetValue(Properties.Settings.Default, value);
}
}
catch (Exception ex)
{
_logger.LogError($"Error setting configuration value for key: {key}", ex);
}
}
public void Save()
{
try
{
Properties.Settings.Default.Save();
_logger.LogInformation("Configuration saved successfully");
}
catch (Exception ex)
{
_logger.LogError("Error saving configuration", ex);
}
}
public void Load()
{
try
{
Properties.Settings.Default.Reload();
_logger.LogInformation("Configuration loaded successfully");
}
catch (Exception ex)
{
_logger.LogError("Error loading configuration", ex);
}
}
public string LastUsedIpAddress
{
get => GetValue(nameof(Properties.Settings.Default.LastUsedIpAddress), "8.8.8.8");
set => SetValue(nameof(Properties.Settings.Default.LastUsedIpAddress), value);
}
public int PingInterval
{
get => GetValue("PingInterval", 300);
set => SetValue("PingInterval", value);
}
public bool AutoPingEnabled
{
get => GetValue(nameof(Properties.Settings.Default.AutoPingEnabled), false);
set => SetValue(nameof(Properties.Settings.Default.AutoPingEnabled), value);
}
public Point FormPosition
{
get => GetValue(nameof(Properties.Settings.Default.FormPosition), Point.Empty);
set => SetValue(nameof(Properties.Settings.Default.FormPosition), value);
}
public string IpAddressValue
{
get => GetValue(nameof(Properties.Settings.Default.IpAddressValue), "8.8.8.8");
set => SetValue(nameof(Properties.Settings.Default.IpAddressValue), value);
}
public string TextBoxIntervalValue
{
get => GetValue(nameof(Properties.Settings.Default.TextBoxIntervalValue), "300");
set => SetValue(nameof(Properties.Settings.Default.TextBoxIntervalValue), value);
}
}
}