Skip to content

Commit

Permalink
Added appsettings.json and AppSettings class instead of GlobalOptions. (
Browse files Browse the repository at this point in the history
#10)

***Update MainViewModel and MauiProgram to use configuration***
***Update DownloadAndInstallPageViewModel to use AppSettings
  • Loading branch information
Andronovo-bit authored Feb 26, 2024
1 parent 04bcb9a commit ed2c48a
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 34 deletions.
5 changes: 5 additions & 0 deletions src/HuaweiHMSInstaller.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@
<PackageReference Include="CommunityToolkit.Maui" Version="7.0.1" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageReference Include="Microsoft.Maui.Controls" Version="$(MauiVersion)" />
<PackageReference Include="Microsoft.Maui.Controls.Compatibility" Version="$(MauiVersion)" />
Expand All @@ -136,6 +138,9 @@
</Compile>
</ItemGroup>

<ItemGroup>
<EmbeddedResource Include="appsettings.json" />
</ItemGroup>

<ItemGroup>
<EmbeddedResource Update="Resources\Languages\AppResources.resx">
Expand Down
25 changes: 25 additions & 0 deletions src/MauiProgram.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using HuaweiHMSInstaller.Services;
using HuaweiHMSInstaller.ViewModels;
using LocalizationResourceManager.Maui;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Syncfusion.Maui.Core.Hosting;

Expand Down Expand Up @@ -62,6 +63,7 @@ public static MauiApp CreateMauiApp()
builder.Services.ConfigureServices();
// builder.Services.RegisterAnalyticsObservers(); // 👈 this is where we register the observers
builder.RegisterViews();
builder.RegisterConfiguration();

var app = builder.Build();
// app.Services.ConfigureAnalyticsSubject(); // 👈 this is where we configure the subject
Expand Down Expand Up @@ -126,4 +128,27 @@ private static void RegisterAnalyticsObservers(this IServiceCollection services)
services.AddSingleton(typeof(IAnalyticsObserver), type);
}
}
private static void RegisterConfiguration(this MauiAppBuilder appBuilder)
{
const string resourceName = "HuaweiHMSInstaller.appsettings.json";

var assembly = Assembly.GetExecutingAssembly();
using var stream = assembly.GetManifestResourceStream(resourceName);

if (stream != null)
{
var configuration = new ConfigurationBuilder()
.AddJsonStream(stream)
.Build();

configuration["Settings:ProjectOperationPath"] = Path.Combine(Path.GetTempPath(), "HuaweiHMSInstaller"); //add data to configuration

appBuilder.Configuration.AddConfiguration(configuration);

}
else
{
throw new FileNotFoundException($"Resource {resourceName} not found.");
}
}
}
16 changes: 16 additions & 0 deletions src/Models/AppSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HuaweiHMSInstaller.Models
{
public class AppSettings
{
public string ProjectOperationPath { get; set; }
public string VersionNumber { get; set; }
public string SponsorGameAppId { get; set; } = "C106234721"; //C104193349
public string YoutuberChanneName { get; set; }
}
}
23 changes: 13 additions & 10 deletions src/Pages/DownloadandInstallPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using HuaweiHMSInstaller.Services;
using HuaweiHMSInstaller.ViewModels;
using LocalizationResourceManager.Maui;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using System.Diagnostics;
using System.Text;
Expand Down Expand Up @@ -51,23 +52,25 @@ public partial class DownloadandInstallPage : ContentPage, IQueryAttributable

private readonly IAdbOperationService _adbOperationService;
private readonly IAppGalleryService _appGalleryService;
private readonly GlobalOptions _options;
private readonly AppSettings _settings;
private readonly ILocalizationResourceManager _localizationResourceManager;
private readonly IHttpClientFactory _httpClient;
private readonly DownloadAndInstallPageViewModel _viewModel;
private readonly AnalyticsSubject _analyticsSubject;


public DownloadandInstallPage(DownloadAndInstallPageViewModel viewModel, AnalyticsSubject analyticsSubject)

public DownloadandInstallPage(
DownloadAndInstallPageViewModel viewModel,
AnalyticsSubject analyticsSubject,
IConfiguration configuration)
{
Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;

InitializeComponent();
_adbOperationService = ServiceProvider.GetService<IAdbOperationService>();
_appGalleryService = ServiceProvider.GetService<IAppGalleryService>();
_localizationResourceManager = ServiceProvider.GetService<ILocalizationResourceManager>();
_options = ServiceProvider.GetService<IOptions<GlobalOptions>>().Value;
_httpClient = ServiceProvider.GetService<IHttpClientFactory>();
_settings = configuration.GetSection("Settings").Get<AppSettings>();
_analyticsSubject = analyticsSubject;
_viewModel = viewModel;
this.NavigatedTo += (s, e) => Initialize();
Expand Down Expand Up @@ -208,7 +211,7 @@ private async Task ResettingDownloadApkOperationAsync()
this.timerReconnect.IsVisible = false;
var totalApp = AdbProgressMessages.Where(x => x.Value).ToDictionary(x => x.Key, x => x.Value).Keys.Count; //7

var files = Directory.GetFiles(_options.ProjectOperationPath);
var files = Directory.GetFiles(_settings.ProjectOperationPath);

foreach (var record in apkRecords)
{
Expand Down Expand Up @@ -386,7 +389,7 @@ private void CheckInternetAccess(object sender, bool result)
///TODO If lost internet connection when download apk, try again connecting it automaticaLly one time but can't connect show an error popup.
private async ValueTask<bool> DownloadHMSAppsAsync()
{
Directory.CreateDirectory(_options.ProjectOperationPath);
Directory.CreateDirectory(_settings.ProjectOperationPath);
apkRecords = new List<InstallApkModel>
{
new($"{nameof(HmsCore)}.apk", HmsCore, AdbMessagesConst.DownloadingHMSCore),
Expand Down Expand Up @@ -432,7 +435,7 @@ await Parallel.ForEachAsync(apkRecords, parallelOptions, async (model, i) =>
}
private async Task CheckApkFileSizeAsync(InstallApkModel model)
{
var filePath = Path.Combine(_options.ProjectOperationPath, model.Name);
var filePath = Path.Combine(_settings.ProjectOperationPath, model.Name);
var exist = File.Exists(filePath);
if (exist)
{
Expand All @@ -451,7 +454,7 @@ private async Task CheckApkFileSizeAsync(InstallApkModel model)
}
private void CheckApkFileExist(InstallApkModel model)
{
var filePath = Path.Combine(_options.ProjectOperationPath, model.Name);
var filePath = Path.Combine(_settings.ProjectOperationPath, model.Name);
var exist = File.Exists(filePath);
if (exist)
{
Expand Down Expand Up @@ -510,7 +513,7 @@ private async Task InstallHmsAppsAsync(DeviceData device)
UpdateHMSInfoLabel();
};
//var p = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), apkPaths[i]);
apkPaths[i] = Path.Combine(_options.ProjectOperationPath, apkPaths[i]);
apkPaths[i] = Path.Combine(_settings.ProjectOperationPath, apkPaths[i]);
await InstallApkToDeviceAsync(apkPaths[i], progressHMSApps, device);
}

Expand Down
13 changes: 7 additions & 6 deletions src/Pages/MainPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using HuaweiHMSInstaller.Services;
using HuaweiHMSInstaller.ViewModels;
using LocalizationResourceManager.Maui;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Maui.Controls.Shapes;
using Syncfusion.Maui.Popup;
Expand All @@ -23,7 +24,7 @@ public partial class MainPage : ContentPage
private SearchListItem SelectedItem { get; set; }
private Frame SearchListFrame;
private readonly ILocalizationResourceManager _localizationResourceManager;
private readonly GlobalOptions _options;
private readonly AppSettings _settings;
private readonly MainViewModel _mainViewModel;
private readonly AnalyticsSubject _analyticsSubject;

Expand All @@ -33,14 +34,14 @@ public MainPage(
IAppGalleryService appGalleryService,
ILocalizationResourceManager localizationResourceManager,
AnalyticsSubject analyticsSubject,
IOptions<GlobalOptions> options)
IConfiguration configuration)
{
Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;

InitializeComponent();
_appGalleryService = appGalleryService;
_localizationResourceManager = localizationResourceManager;
_options = options.Value;
_settings = configuration.GetSection("Settings").Get<AppSettings>();
_mainViewModel = mainViewModel;
_analyticsSubject = analyticsSubject;
Init();
Expand All @@ -50,7 +51,7 @@ private void Init()
this.langPicker.SelectedItem = _localizationResourceManager.CurrentCulture.TwoLetterISOLanguageName.ToUpper();
this.searchBar.BackgroundColor = Color.FromRgba(255, 255, 255, 0.1);
this.SearchListFrameGrid.BackgroundColor = Color.FromRgba(255, 255, 255, 0.05);
this.VersionNum.Text = $"{_localizationResourceManager.GetValue("version")}: {_options.VersionNumber}";
this.VersionNum.Text = $"{_localizationResourceManager.GetValue("version")}: {_settings.VersionNumber}";

_mainViewModel.Init(CheckInternetConnectionAction);
_mainViewModel.AfterEventInternetAndHuaweiServiceCheck = AfterEventInternetAndHuaweiServiceCheck;
Expand Down Expand Up @@ -134,7 +135,7 @@ private void Button_Retry_Clicked(object sender, EventArgs e)

private async Task GetSponsorGameInfo()
{
var gameAppId = _options.SponsorGameAppId;
var gameAppId = _settings.SponsorGameAppId;
if (gameAppId != null)
{
this.selectedGameFrame.IsVisible = true;
Expand Down Expand Up @@ -663,7 +664,7 @@ private void langPicker_SelectedIndexChanged(object sender, EventArgs e)

_localizationResourceManager.CurrentCulture = new CultureInfo(picker.SelectedItem.ToString());

this.VersionNum.Text = $"{_localizationResourceManager.GetValue("version")}: {_options.VersionNumber}";
this.VersionNum.Text = $"{_localizationResourceManager.GetValue("version")}: {_settings.VersionNumber}";

this.sponsorGameStackLayout.IsVisible = false;
this.sponsorGameNotInternetorHuaweiService.IsVisible = false;
Expand Down
21 changes: 11 additions & 10 deletions src/Services/AdbOperationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using AdvancedSharpAdbClient.Exceptions;
using HuaweiHMSInstaller.Helper;
using HuaweiHMSInstaller.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using static AdvancedSharpAdbClient.DeviceCommands.PackageManager;

Expand All @@ -25,16 +26,16 @@ public class AdbOperationService : IAdbOperationService
// Dependency injection to create HttpClient, AdbClient, Options instances
private readonly IHttpClientFactory _httpClient;
private AdbClient _adbClient;
private readonly GlobalOptions _options;
private readonly AppSettings _settings;

public AdbOperationService(
IHttpClientFactory httpClient,
IOptions<GlobalOptions> options)
IHttpClientFactory httpClient,
IConfiguration configuration)
{
_options = options.Value;
_settings = configuration.GetSection("AppSettings").Get<AppSettings>();
_httpClient = httpClient;
NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
adbPath = Path.Combine(_options.ProjectOperationPath, AdbFolder, "platform-tools", "adb.exe");
adbPath = Path.Combine(_settings.ProjectOperationPath, AdbFolder, "platform-tools", "adb.exe");
}
public async Task CreateAdbClient()
{
Expand Down Expand Up @@ -85,19 +86,19 @@ public async Task DownloadAdbFromInternetAsync(IProgress<float> progress = null)
string fileName = Path.GetFileName(AdbUrl);

//if folder not exist create folder
Directory.CreateDirectory(_options.ProjectOperationPath);
Directory.CreateDirectory(_settings.ProjectOperationPath);

// Create a file stream to store the downloaded data
using (var file = new FileStream(Path.Combine(_options.ProjectOperationPath, fileName), FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
using (var file = new FileStream(Path.Combine(_settings.ProjectOperationPath, fileName), FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
// Download the file using the custom extension method
await _httpClient.DownloadAsync(AdbUrl, file, progress);
}

// Extract the file to the destination folder
ZipFile.ExtractToDirectory(Path.Combine(_options.ProjectOperationPath, fileName), Path.Combine(_options.ProjectOperationPath, AdbFolder),true);
ZipFile.ExtractToDirectory(Path.Combine(_settings.ProjectOperationPath, fileName), Path.Combine(_settings.ProjectOperationPath, AdbFolder),true);
// Delete the file
File.Delete(Path.Combine(_options.ProjectOperationPath, fileName));
File.Delete(Path.Combine(_settings.ProjectOperationPath, fileName));
}
public async Task<List<DeviceData>> GetDevices()
{
Expand All @@ -112,7 +113,7 @@ public async Task DownloadApkFromInternetAsync(string apkUrl, string apkName, IP
try
{
// Create a file stream to store the downloaded data
using (var file = new FileStream(Path.Combine(_options.ProjectOperationPath, apkName), FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
using (var file = new FileStream(Path.Combine(_settings.ProjectOperationPath, apkName), FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
// Add try-catch block to handle NetworkErrorException
try
Expand Down
13 changes: 7 additions & 6 deletions src/ViewModels/DownloadAndInstallPageViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using HuaweiHMSInstaller.Models;
using HuaweiHMSInstaller.Pages;
using HuaweiHMSInstaller.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using System.Diagnostics;
using System.Text;
Expand All @@ -14,7 +15,7 @@ namespace HuaweiHMSInstaller.ViewModels
public sealed partial class DownloadAndInstallPageViewModel : BaseViewModel, IQueryAttributable
{
private readonly IAdbOperationService _adbOperationService;
private readonly GlobalOptions _options;
private readonly AppSettings _settings;
private readonly AnalyticsSubject _analyticsSubject;
private readonly IHttpClientFactory _httpClient;

Expand All @@ -40,14 +41,14 @@ public sealed partial class DownloadAndInstallPageViewModel : BaseViewModel, IQu
public DownloadAndInstallPageViewModel(
INavigationService navigationService,
IAdbOperationService adbOperationService,
IOptions<GlobalOptions> options,
AnalyticsSubject analyticsSubject,
IHttpClientFactory httpClient)
IHttpClientFactory httpClient,
IConfiguration configuration)
: base(navigationService)
{
Debug.WriteLine($"**** {this.GetType().Name}.{nameof(DownloadAndInstallPageViewModel)}: ctor");
_adbOperationService = adbOperationService;
_options = options.Value;
_settings = configuration.GetSection("Settings").Get<AppSettings>();
_httpClient = httpClient;
_analyticsSubject = analyticsSubject;
_analyticsSubject.Notify("Download and Install Page Loaded");
Expand All @@ -71,8 +72,8 @@ public void ApplyQueryAttributes(IDictionary<string, object> query)
private void Init()
{
AdbProgressMessages = AdbMessagesConst.InitializeMessages();
adbPath = Path.Combine(_options.ProjectOperationPath, AdbFolder, "platform-tools", "adb.exe");
adbFolderPath = Path.Combine(_options.ProjectOperationPath, AdbFolder);
adbPath = Path.Combine(_settings.ProjectOperationPath, AdbFolder, "platform-tools", "adb.exe");
adbFolderPath = Path.Combine(_settings.ProjectOperationPath, AdbFolder);
}

public async void NavigateToThanksPage()
Expand Down
2 changes: 0 additions & 2 deletions src/ViewModels/MainViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
using HuaweiHMSInstaller.Models;
using HuaweiHMSInstaller.Pages;
using HuaweiHMSInstaller.Services;
using System.Text;

namespace HuaweiHMSInstaller.ViewModels
{
public class MainViewModel : BaseViewModel
{
private readonly AnalyticsSubject _analyticsSubject;
private readonly IAppGalleryService _appGalleryService;

public SearchListItem SearchListItem { get; set; }
public Worker<bool>.WorkCompletedEventHandler AfterEventInternetAndHuaweiServiceCheck { get; set; }

Expand Down
7 changes: 7 additions & 0 deletions src/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"Settings": {
"VersionNumber": "0.0.0.1",
"SponsorGameAppId": "C106234721",
"YoutuberChanneName": "Huawei"
}
}

0 comments on commit ed2c48a

Please sign in to comment.