Skip to content

Commit

Permalink
various refactoring (#215)
Browse files Browse the repository at this point in the history
* replace LangProvider calls with the Lang object across app

Replaced all instances of LangProvider.GetLang with direct Lang object properties to simplify code and enhance readability. Also made IfNotAdminRestartAsAdmin method private and added Localizable attribute to several classes.

* Add Localizable attribute and improve encapsulation

Added the `[Localizable(false)]` attribute to various classes to exclude them from localization. Improved encapsulation by modifying access modifiers for properties and fields, ensuring private or protected access where appropriate. These changes help in better resource management and code maintainability.
  • Loading branch information
DineshSolanki authored Jul 29, 2024
1 parent 38b85d7 commit d5ab47d
Show file tree
Hide file tree
Showing 43 changed files with 191 additions and 158 deletions.
1 change: 1 addition & 0 deletions FoliCon/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace FoliCon;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
[Localizable(false)]
public partial class App
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
Expand Down
2 changes: 1 addition & 1 deletion FoliCon/Models/Constants/GlobalVariables.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static IconOverlay IconOverlayType()
};
}

public static readonly string MediaInfoFile = "info.folicon";
public const string MediaInfoFile = "info.folicon";

private static string IconOverlayTypeString =>
Services.Tracker.Store.GetData("PosterIconConfigViewModel")["p.IconOverlay"].ToString();
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Models/Data/PosterIcon.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FoliCon.Models.Data;

[Localizable(false)]
public class PosterIcon: BindableBase
{
public ImageSource FolderJpg { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion FoliCon/Models/Data/StatusBarData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class StatusBarData : BindableBase

public void ResetData()
{
AppStatus = LangProvider.GetLang("Idle");
AppStatus = Lang.Idle;
AppStatusAdditional = "";
ProcessedFolder = 0;
TotalFolders = 0;
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/Configuration/AppConfig.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FoliCon.Modules.Configuration;

[Localizable(false)]
public class AppConfig : GlobalDataHelper
{
public string DevClientId { get; set; }
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/Configuration/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FoliCon.Modules.Configuration;

[Localizable(false)]
internal static class AssemblyInfo
{
public static string GetVersion()
Expand Down
3 changes: 2 additions & 1 deletion FoliCon/Modules/Convertor/BoolToPermissionTextConvertor.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
namespace FoliCon.Modules.Convertor;

[Localizable(false)]
public class BoolToPermissionTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool hasWritePermission)
{
return hasWritePermission ? LangProvider.GetLang("WritePermissionAllowed") : LangProvider.GetLang("WritePermissionNotAllowed");
return hasWritePermission ? Lang.WritePermissionAllowed : Lang.WritePermissionNotAllowed;
}

throw new InvalidOperationException("Must be a boolean value.");
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/Convertor/ImageCacheConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
/// Converts an image path to a BitmapImage with caching to improve performance and thread safety.
/// CREDIT: https://stackoverflow.com/a/37652158/8076598
/// </summary>
[Localizable(false)]
public class ImageCacheConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
Expand Down
15 changes: 8 additions & 7 deletions FoliCon/Modules/DeviantArt/DArt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,30 @@

namespace FoliCon.Modules.DeviantArt;

[Localizable(false)]
public class DArt : BindableBase
{
private string _clientAccessToken;
private string _clientSecret;
private string _clientId;
private readonly string _clientId;

private readonly MemoryCache _cache = new(new MemoryCacheOptions());

private static readonly JsonSerializerSettings SerializerSettings = new() { NullValueHandling = NullValueHandling.Ignore };
public string ClientId

private string ClientId
{
get => _clientId;
set => SetProperty(ref _clientId, value);
init => SetProperty(ref _clientId, value);
}

public string ClientSecret
private string ClientSecret
{
get => _clientSecret;
set => SetProperty(ref _clientSecret, value);
init => SetProperty(ref _clientSecret, value);
}

public string ClientAccessToken
private string ClientAccessToken
{
get => _clientAccessToken;
set => SetProperty(ref _clientAccessToken, value);
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/Extension/BindingPathExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace FoliCon.Modules.Extension;

[Localizable(false)]
public static class BindingPathExtensions
{
private static readonly ImageCacheConverter ImageCacheConverter = new ();
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/Extension/DialogServiceExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FoliCon.Modules.Extension;

[Localizable(false)]
public static class DialogServiceExtensions
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/Extension/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FoliCon.Modules.Extension;

[Localizable(false)]
public static class Extensions
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/Extension/StreamExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

namespace FoliCon.Modules.Extension;

[Localizable(false)]
public static class StreamExtensions
{
private static readonly ReaderOptions ReaderOptions = new() { ArchiveEncoding =
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/IGDB/IgdbDataTransformer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FoliCon.Modules.IGDB;

[Localizable(false)]
public class IgdbDataTransformer(ref List<PickedListItem> listDataTable, ref List<ImageToDownload> imgDownloadList)
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
Expand Down
3 changes: 2 additions & 1 deletion FoliCon/Modules/IGDB/IgdbService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FoliCon.Modules.IGDB;

[Localizable(false)]
public class IgdbService(ref IGDBClient serviceClient)
{
private const string ServiceClientIsNotInitialized = "Service Client is not initialized.";
Expand All @@ -19,7 +20,7 @@ public async Task<ResultResponse> SearchGameAsync(string query)
}

var r = await _serviceClient.QueryAsync<Game>(IGDBClient.Endpoints.Games,
$"search \"{query}\"; fields artworks.image_id, name,first_release_date,total_rating,summary,cover.*;");
$"""search "{query}"; fields artworks.image_id, name,first_release_date,total_rating,summary,cover.*;""");

return new ResultResponse
{
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/LangProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace FoliCon.Properties.Langs;

[Localizable(false)]
public class LangProvider : INotifyPropertyChanged
{
private static string _cultureInfoStr;
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/Media/PngToIcoService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FoliCon.Modules.Media;

[Localizable(false)]
public static class PngToIcoService
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
Expand Down
5 changes: 3 additions & 2 deletions FoliCon/Modules/TMDB/TMDBService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace FoliCon.Modules.TMDB;

[Localizable(false)]
internal class TmdbService
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
Expand Down Expand Up @@ -114,8 +115,8 @@ public async Task<ResultResponse> SearchWithParamsAsync(ParsedTitle parsedTitle,
{
Logger.Debug("Searching for {ParsedTitle} in {SearchMode}", parsedTitle, searchMode);

var mediaType = "";
object? searchResult = null;
string mediaType;
object? searchResult;

switch (searchMode)
{
Expand Down
11 changes: 6 additions & 5 deletions FoliCon/Modules/UI/CustomMessageBox.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FoliCon.Modules.UI;

[Localizable(false)]
internal static class CustomMessageBox
{
public static MessageBoxInfo Ask(string messageBoxText, string caption)
Expand All @@ -11,8 +12,8 @@ public static MessageBoxInfo Ask(string messageBoxText, string caption)
Button = MessageBoxButton.YesNo,
IconBrushKey = ResourceToken.AccentBrush,
IconKey = ResourceToken.AskGeometry,
YesContent = LangProvider.GetLang("Confirm"),
NoContent = LangProvider.GetLang("Cancel")
YesContent = Lang.Confirm,
NoContent = Lang.Cancel
};
}
public static MessageBoxInfo Error(string messageBoxText, string caption)
Expand All @@ -24,7 +25,7 @@ public static MessageBoxInfo Error(string messageBoxText, string caption)
Button = MessageBoxButton.OK,
IconBrushKey = ResourceToken.AccentBrush,
IconKey = ResourceToken.ErrorGeometry,
ConfirmContent = LangProvider.GetLang("OK")
ConfirmContent = Lang.OK
};
}
public static MessageBoxInfo Warning(string messageBoxText, string caption)
Expand All @@ -36,7 +37,7 @@ public static MessageBoxInfo Warning(string messageBoxText, string caption)
Button = MessageBoxButton.OK,
IconBrushKey = ResourceToken.AccentBrush,
IconKey = ResourceToken.WarningGeometry,
ConfirmContent = LangProvider.GetLang("OK")
ConfirmContent = Lang.OK
};
}
public static MessageBoxInfo Info(string messageBoxText, string caption)
Expand All @@ -48,7 +49,7 @@ public static MessageBoxInfo Info(string messageBoxText, string caption)
Button = MessageBoxButton.OK,
IconBrushKey = ResourceToken.AccentBrush,
IconKey = ResourceToken.InfoGeometry,
ConfirmContent = LangProvider.GetLang("OK")
ConfirmContent = Lang.OK
};
}
}
2 changes: 1 addition & 1 deletion FoliCon/Modules/UI/FolderDragDropHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ private static void Control_DragOver(object sender, DragEventArgs e)
var dt = e.Data.GetData(DataFormats.FileDrop);
var data = (dt as Array)?.GetValue(0)?.ToString();

Logger.Trace("Control_DragOver: Data: {Data}", data ?? "null");
Logger.Trace("Control_DragOver: Data: {Data}", data);

e.Effects = Directory.Exists(data) ? DragDropEffects.Link : DragDropEffects.None;
e.Handled = true;
Expand Down
1 change: 1 addition & 0 deletions FoliCon/Modules/UI/HandyWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace FoliCon.Modules.UI;

[Localizable(false)]
public class HandyWindow : Window, IDialogWindow
{
static HandyWindow()
Expand Down
2 changes: 1 addition & 1 deletion FoliCon/Modules/UI/ListViewClickSortBehavior.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ private void OnClick(object sender, RoutedEventArgs e)
? Application.Current.Resources["HeaderTemplateArrowUp"] as DataTemplate
: Application.Current.Resources["HeaderTemplateArrowDown"] as DataTemplate;

// Remove arrow from previously sorted header
// Remove arrow from the previously sorted header
if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
{
_lastHeaderClicked.Column.HeaderTemplate = null;
Expand Down
25 changes: 13 additions & 12 deletions FoliCon/Modules/utils/CultureUtils.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
namespace FoliCon.Modules.utils;

[Localizable(false)]
public static class CultureUtils
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

private static readonly Dictionary<Languages, string> LanguageCodes = new()
{
{ Languages.English, "en-US" },
{ Languages.Spanish, "es-MX" },
{ Languages.Arabic, "ar-SA" },
{ Languages.Russian, "ru-RU" },
{ Languages.Hindi, "hi-IN" },
{ Languages.Portuguese, "pt-PT" }
};

public static CultureInfo GetCultureInfoByLanguage(Languages language)
{
Logger.Debug("Getting CultureInfo by Language: {Language}", language);

var languageCodes = new Dictionary<Languages, string>
{
{ Languages.English, "en-US" },
{ Languages.Spanish, "es-MX" },
{ Languages.Arabic, "ar-SA" },
{ Languages.Russian, "ru-RU" },
{ Languages.Hindi, "hi-IN" },
{ Languages.Portuguese, "pt-PT" }
};

var langCode = languageCodes.GetValueOrDefault(language, "en-US");

var langCode = LanguageCodes.GetValueOrDefault(language, "en-US");
ConfigHelper.Instance.SetLang(langCode.Split("-")[0]);

return new CultureInfo(langCode);
Expand Down
5 changes: 3 additions & 2 deletions FoliCon/Modules/utils/DataUtils.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FoliCon.Modules.utils;

[Localizable(false)]
public static class DataUtils
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
Expand All @@ -24,10 +25,10 @@ public static int GetResultCount(bool isPickedById, dynamic result, string searc
/// <returns>Formatted Rating value.</returns>
public static string FormatRating(double ratingInput)
{
Logger.Debug("Start FormatRatingString() - Input received : {RatingInput}", ratingInput);
Logger.Trace("Start FormatRatingString() - Input received : {RatingInput}", ratingInput);
var decimalPart = ratingInput % 1;
var formattedRatingValue = decimalPart > 0 ? ratingInput.ToString("0.##") : ratingInput.ToString("0");
Logger.Debug("End FormatRatingString() - Formatted Rating : {FormattedRatingValue}", formattedRatingValue);
Logger.Trace("End FormatRatingString() - Formatted Rating : {FormattedRatingValue}", formattedRatingValue);
return formattedRatingValue;
}

Expand Down
11 changes: 4 additions & 7 deletions FoliCon/Modules/utils/DialogUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ public static void ShowGrowlInfo(string message)

public static void ConfirmUpdate(ReleaseInfo ver)
{
var message = LangProvider.GetLang("NewVersionFound")
var message = Lang.NewVersionFound
.Format(ver.TagName, ver.Changelog.Replace("\\n", Environment.NewLine));
var confirmMessage = LangProvider.GetLang("UpdateNow");
var cancelMessage = LangProvider.GetLang("Ignore");
var confirmMessage = Lang.UpdateNow;
var cancelMessage = Lang.Ignore;

var info = new GrowlInfo
{
Expand Down Expand Up @@ -54,10 +54,7 @@ public static VistaFolderBrowserDialog NewFolderBrowserDialog(string description
};
return folderBrowser;
}
public static VistaOpenFileDialog NewOpenFileDialog(string description)
{
return NewOpenFileDialog(description, "All files (*.*)|*.*");
}

public static VistaOpenFileDialog NewOpenFileDialog(string description, string filter)
{
Logger.Debug("Creating New Open File Dialog");
Expand Down
14 changes: 7 additions & 7 deletions FoliCon/Modules/utils/FileUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -229,14 +229,14 @@ public static void SaveMediaInfo(int id, string mediaType, string folderPath)
mediaType, filePath).Log();
MessageBox.Show(CustomMessageBox.Error(
e.Message.Contains("The process cannot access the file")
? LangProvider.GetLang("FileIsInUse")
: LangProvider.GetLang("FailedToSaveMediaInfoAt").Format(filePath), LangProvider.GetLang("UnauthorizedAccess")));
? Lang.FileIsInUse
: Lang.FailedToSaveMediaInfoAt.Format(filePath), Lang.UnauthorizedAccess));
}
catch (Exception e)
{
Logger.ForExceptionEvent(e, LogLevel.Error).Message("Error Occurred while Saving Media Info, ID: {Id}, Media Type: {MediaType}, Folder Path: {FolderPath}", id,
mediaType, folderPath).Log();
CustomMessageBox.Error(e.Message, LangProvider.GetLang("ExceptionOccurred"));
CustomMessageBox.Error(e.Message, Lang.ExceptionOccurred);
}
}

Expand Down Expand Up @@ -337,7 +337,7 @@ public static async Task CheckForUpdate(bool onlyShowIfUpdateAvailable)

if (!ApplicationHelper.IsConnectedToInternet())
{
DialogUtils.ShowGrowlError(LangProvider.GetLang("NetworkNotAvailable"));
DialogUtils.ShowGrowlError(Lang.NetworkNotAvailable);
return;
}

Expand All @@ -349,7 +349,7 @@ public static async Task CheckForUpdate(bool onlyShowIfUpdateAvailable)

if (!onlyShowIfUpdateAvailable)
{
DialogUtils.ShowGrowlInfo(LangProvider.GetLang("ThisIsLatestVersion"));
DialogUtils.ShowGrowlInfo(Lang.ThisIsLatestVersion);
}

return;
Expand All @@ -363,8 +363,8 @@ public static void HandleUnauthorizedAccessException(UnauthorizedAccessException
{
MessageBox.Show(CustomMessageBox.Error(
ex.Message.Contains("The process cannot access the file")
? LangProvider.GetLang("FileIsInUse")
: LangProvider.GetLang("FailedFileAccessAt").Format(path), LangProvider.GetLang("ExceptionOccurred")));
? Lang.FileIsInUse
: Lang.FailedFileAccessAt.Format(path), Lang.ExceptionOccurred));
}

/// <summary>
Expand Down
Loading

0 comments on commit d5ab47d

Please sign in to comment.