Skip to content

Commit

Permalink
Error handling on update
Browse files Browse the repository at this point in the history
  • Loading branch information
netquick committed Jul 18, 2024
1 parent cdf3ec9 commit fdf6c11
Show file tree
Hide file tree
Showing 11 changed files with 116 additions and 47 deletions.
9 changes: 8 additions & 1 deletion DeFRaG_Helper/Config/AppConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ public static class AppConfig
public static string? DatabasePath { get; set; }
public static string? DatabaseUrl { get; set; }
public static string? ConnectionString { get; set; }
public static bool ? UseUnsecureConnection { get; set; }
public static bool ? DownloadImagesOnUpdate { get; set; }


public delegate Task<string> RequestGameDirectoryDelegate();
public static event RequestGameDirectoryDelegate? OnRequestGameDirectory;
Expand Down Expand Up @@ -56,6 +59,8 @@ public static async Task LoadConfigurationAsync()
DatabaseUrl = config?.DatabaseUrl ?? DatabaseUrl;
MenuState = config?.MenuState ?? MenuState; // Use default if not set
ConnectionString = config?.ConnectionString ?? ConnectionString; // Use default if not set
UseUnsecureConnection = config?.UseUnsecureConnection ?? false;
DownloadImagesOnUpdate = config?.DownloadImagesOnUpdate ?? false;
await MessageHelper.LogAsync($"GameDirectoryPath: {GameDirectoryPath}");
await MessageHelper.LogAsync($"SelectedColor: {SelectedColor}");
await MessageHelper.LogAsync($"ButtonState: {ButtonState}");
Expand Down Expand Up @@ -130,7 +135,9 @@ public static async Task SaveConfigurationAsync()
DatabasePath = DatabasePath,
DatabaseUrl = DatabaseUrl,
MenuState = MenuState,
ConnectionString = ConnectionString
ConnectionString = ConnectionString,
UseUnsecureConnection = UseUnsecureConnection,
DownloadImagesOnUpdate = DownloadImagesOnUpdate

};
MessageHelper.Log($"GameDirectoryPath: {GameDirectoryPath}");
Expand Down
2 changes: 2 additions & 0 deletions DeFRaG_Helper/Config/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,7 @@ public class Configuration
public string? DatabaseUrl { get; set; }
public string? MenuState { get; set; }
public string? ConnectionString { get; set; }
public bool? UseUnsecureConnection { get; set; }
public bool? DownloadImagesOnUpdate { get; set; }
}
}
19 changes: 16 additions & 3 deletions DeFRaG_Helper/Helpers/CreateAndUpdateDB.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,15 @@ private static void ShowMessage(string message)
private static HttpClient CreateHttpClient()
{
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true; // Bypass SSL certificate validation

if (AppConfig.UseUnsecureConnection.HasValue && AppConfig.UseUnsecureConnection.Value)
{
handler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; // Bypass SSL certificate validation for unsecure connections
}

return new HttpClient(handler);
}

private static void CreateDB()
{
if (!System.IO.Directory.Exists(AppDataFolder))
Expand Down Expand Up @@ -356,6 +360,7 @@ private async static Task GetMapDetails(MapData tempMap, int mapCount)
// If there's no <span> tag, use the original propertyValue and append the .bsp extension
map.Mapname = propertyValue + ".bsp";
}
SimpleLogger.Log("Mapname: " + map.Mapname);
break;

case "Pk3 file":
Expand Down Expand Up @@ -623,6 +628,14 @@ private async static Task GetMapDetails(MapData tempMap, int mapCount)
}
}


if (map.Name == null || map.Name == "")
{
map.Name = tempMap.Name;
}



//get list of image urls
var imageUrls = ExtractImageUrls(html);
for (int i = 0; i < imageUrls.Count; i++)
Expand All @@ -638,7 +651,7 @@ private async static Task GetMapDetails(MapData tempMap, int mapCount)
var mapViewModel = await MapViewModel.GetInstanceAsync();

//if (map.Name == null || map.Name == "")
// {
//{
// map.Name = Path.GetFileNameWithoutExtension(tempMap.Name);
//}

Expand Down
8 changes: 6 additions & 2 deletions DeFRaG_Helper/Helpers/DbActions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public async Task AddMap(Map map)


newMapId = Convert.ToInt32(await command.ExecuteScalarAsync());
await command.ExecuteNonQueryAsync();
//await command.ExecuteNonQueryAsync();
}
});
await Task.CompletedTask;
Expand Down Expand Up @@ -411,7 +411,11 @@ public async Task UpdateMap(Map map)
{
insertCommand.Parameters.AddWithValue("@MapId", map.Id); // Ensure you have the map's ID available
insertCommand.Parameters.AddWithValue("@FunctionId", functionId);
await insertCommand.ExecuteNonQueryAsync();
try
{
await insertCommand.ExecuteNonQueryAsync();
}
catch (Exception e) { MessageHelper.Log(e.Message); }
}
}
});
Expand Down
16 changes: 13 additions & 3 deletions DeFRaG_Helper/Helpers/DbQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ public void Enqueue(Func<SqliteConnection, Task> operation, [CallerMemberName] s

private async Task ProcessQueue(string callerMemberName)
{
List<Exception> exceptions = new List<Exception>();

while (_operations.TryDequeue(out var operation))
{
try
Expand All @@ -59,8 +61,7 @@ private async Task ProcessQueue(string callerMemberName)
{
Console.WriteLine($"DbQueue operation failed: {ex.Message} - Called by {callerMemberName}");
MessageHelper.Log($"DbQueue operation failed: {ex.Message}, {ex.StackTrace}- Called by {callerMemberName}");
_tcs.SetException(ex); // Consider setting the exception to signal failure
return; // Exit on failure
exceptions.Add(ex); // Accumulate exceptions instead of stopping
}
}

Expand All @@ -74,11 +75,20 @@ private async Task ProcessQueue(string callerMemberName)
}
_isProcessing = false;
}
_tcs.SetResult(true); // Signal completion

if (exceptions.Any())
{
_tcs.SetException(new AggregateException(exceptions)); // Set all accumulated exceptions
}
else
{
_tcs.SetResult(true); // Signal completion only if there were no exceptions
}
}




public Task WhenAllCompleted() => _tcs.Task;
}
}
67 changes: 40 additions & 27 deletions DeFRaG_Helper/Helpers/Downloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,47 +12,60 @@ namespace DeFRaG_Helper
{
public static class Downloader
{

private static readonly HttpClient httpClient = CreateHttpClient();

private static HttpClient CreateHttpClient()
{
var handler = new HttpClientHandler();

if (AppConfig.UseUnsecureConnection.HasValue && AppConfig.UseUnsecureConnection.Value)
{
handler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; // Bypass SSL certificate validation for unsecure connections
}

return new HttpClient(handler);
}



public static async Task DownloadFileAsync(string url, string destinationPath, IProgress<double> progress)
{
using (var httpClient = new HttpClient())
var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
using (var fileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None))
{
var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
using (var fileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None))
using (var downloadStream = await response.Content.ReadAsStreamAsync())
{
using (var downloadStream = await response.Content.ReadAsStreamAsync())
{
var totalRead = 0L;
var buffer = new byte[8192];
var isMoreToRead = true;
var totalRead = 0L;
var buffer = new byte[8192];
var isMoreToRead = true;

do
do
{
var read = await downloadStream.ReadAsync(buffer, 0, buffer.Length);
if (read == 0)
{
var read = await downloadStream.ReadAsync(buffer, 0, buffer.Length);
if (read == 0)
{
isMoreToRead = false;
}
else
{
await fileStream.WriteAsync(buffer, 0, read);

totalRead += read;
var totalReadInPercent = (double)totalRead / (double)response.Content.Headers.ContentLength.Value * 100;
if (progress != null)
{
MainWindow.Instance.Dispatcher.Invoke(() => MainWindow.Instance.UpdateProgressBar(totalReadInPercent));
isMoreToRead = false;
}
else
{
await fileStream.WriteAsync(buffer, 0, read);

}
//MainWindow.Instance.Dispatcher.Invoke(() => MainWindow.Instance.UpdateProgressBar(totalReadInPercent));
totalRead += read;
var totalReadInPercent = (double)totalRead / (double)response.Content.Headers.ContentLength.Value * 100;
if (progress != null)
{
MainWindow.Instance.Dispatcher.Invoke(() => MainWindow.Instance.UpdateProgressBar(totalReadInPercent));
}
} while (isMoreToRead);
}
}
} while (isMoreToRead);
}
}
}




public static async Task UnpackFile(string filename, string destinationFolder, IProgress<double> progress)
{
if (filename.EndsWith(".zip"))
Expand Down
2 changes: 1 addition & 1 deletion DeFRaG_Helper/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@
<Thumb Height="5" Cursor="SizeNS" DragDelta="OnTopDragDelta" Opacity="0" VerticalAlignment="Top" Style="{StaticResource ResizeGripStyle}"/>
<Thumb Height="5" Cursor="SizeNS" DragDelta="OnBottomDragDelta" Opacity="0" VerticalAlignment="Bottom" Style="{StaticResource ResizeGripStyle}"/>
<Thumb Width="10" Height="10" Cursor="SizeNWSE" DragDelta="OnBottomRightDragDelta" Opacity="0" HorizontalAlignment="Right" VerticalAlignment="Bottom" Style="{StaticResource ResizeGripStyle}"/>
<StackPanel x:Name="MessageHost" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,10,10" MaxHeight="200"/>
<StackPanel x:Name="MessageHost" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,10,10" MaxHeight="180"/>

</Grid>

Expand Down
2 changes: 1 addition & 1 deletion DeFRaG_Helper/UserControls/MapCard.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" x:Name="Mapname" Text="{Binding Name}" FontSize="14" Foreground="White" Margin="10, 0, 10, 0" FontFamily="Segoe UI"/>
<TextBlock Grid.Row="0" Grid.Column="0" x:Name="Mapname" Text="{Binding Mapname}" FontSize="14" Foreground="White" Margin="10, 0, 10, 0" FontFamily="Segoe UI"/>
<TextBlock Grid.Row="1" Grid.Column="0" x:Name="Filename" Text="{Binding Filename}" FontSize="14" Foreground="White" Margin="10, 0, 0, 10" FontFamily="Segoe UI"/>
<TextBlock Grid.Row="0" Grid.Column="1" x:Name="Author" Text="{Binding Author}" FontSize="14" Foreground="White" Margin="10, 0, 0, 0" FontFamily="Segoe UI"/>
<TextBlock Grid.Row="1" Grid.Column="1" x:Name="Date" Text="{Binding Releasedate}" FontSize="14" Foreground="White" Margin="10, 0, 0, 10" FontFamily="Segoe UI"/>
Expand Down
4 changes: 0 additions & 4 deletions DeFRaG_Helper/ViewModels/MapViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -259,10 +259,6 @@ GROUP BY

};

if (map.Name == null || map.Name == "")
{
map.Name = Path.GetFileNameWithoutExtension(map.Mapname);
}


// Since we're on a background thread, ensure UI updates are dispatched on the UI thread
Expand Down
12 changes: 7 additions & 5 deletions DeFRaG_Helper/Views/Settings.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,14 @@


</ComboBox>
<TextBox Name="txtGamePath" HorizontalAlignment="Left" FontFamily="Segoe UI" FontSize="20" Height="32" Margin="10,159,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="433" LostFocus="txtGamePath_LostFocus"/>
<TextBox Name="txtGamePath" HorizontalAlignment="Left" FontFamily="Segoe UI" FontSize="20" Height="32" Margin="10,118,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="433" LostFocus="txtGamePath_LostFocus"/>
<Label Content="Theme Color" FontFamily="Segoe UI" FontSize="14" Foreground="White" HorizontalAlignment="Left" Height="29" Margin="10,10,0,0" VerticalAlignment="Top" Width="180"/>
<Label Content="Game Path" FontFamily="Segoe UI" FontSize="14" Foreground="White" HorizontalAlignment="Left" Height="29" Margin="10,125,0,0" VerticalAlignment="Top" Width="180"/>
<Button Content="set" Name="btnSet" HorizontalAlignment="Left" Height="32" Margin="448,159,0,0" VerticalAlignment="Top" Width="56" RenderTransformOrigin="4.143,-2.414" Click="btnSet_Click"/>
<CheckBox Content="CheckBox" Style="{StaticResource DarkModeToggleSwitchStyle}" HorizontalAlignment="Left" Margin="10,225,0,0" VerticalAlignment="Top"/>
<Label Content="Download Images on Map update" FontFamily="Segoe UI" FontSize="12" Foreground="White" HorizontalAlignment="Left" Height="25" Margin="65,225,0,0" VerticalAlignment="Top" Width="208"/>
<Label Content="Game Path" FontFamily="Segoe UI" FontSize="14" Foreground="White" HorizontalAlignment="Left" Height="29" Margin="10,84,0,0" VerticalAlignment="Top" Width="180"/>
<Button Content="set" Name="btnSet" HorizontalAlignment="Left" Height="32" Margin="448,118,0,0" VerticalAlignment="Top" Width="56" RenderTransformOrigin="4.143,-2.414" Click="btnSet_Click"/>
<CheckBox Name="chkDlImages" Content="CheckBox" Style="{StaticResource DarkModeToggleSwitchStyle}" HorizontalAlignment="Left" Margin="10,164,0,0" VerticalAlignment="Top" Checked="DownloadImg_Changed" Unchecked="DownloadImg_Changed"/>
<Label Content="Download Images on Map update" FontFamily="Segoe UI" FontSize="12" Foreground="White" HorizontalAlignment="Left" Height="25" Margin="65,164,0,0" VerticalAlignment="Top" Width="208"/>
<CheckBox Name="chkUnsecure" Content="CheckBox" Style="{StaticResource DarkModeToggleSwitchStyle}" HorizontalAlignment="Left" Margin="10,200,0,0" VerticalAlignment="Top" Checked="DlUnsecure_Changed" Unchecked="DlUnsecure_Changed"/>
<Label Content="Allow unsecure connection" FontFamily="Segoe UI" FontSize="12" Foreground="White" HorizontalAlignment="Left" Height="25" Margin="65,200,0,0" VerticalAlignment="Top" Width="208"/>



Expand Down
22 changes: 22 additions & 0 deletions DeFRaG_Helper/Views/Settings.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,30 @@ private void Page_Loaded(object sender, RoutedEventArgs e)
ColorComboBox.SelectedItem = selectedItem;
}
txtGamePath.Text = AppConfig.GameDirectoryPath;

chkDlImages.IsChecked = AppConfig.DownloadImagesOnUpdate;
chkUnsecure.IsChecked = AppConfig.UseUnsecureConnection;


}

private async void DownloadImg_Changed(object sender, RoutedEventArgs e)
{
// Update the DownloadImagesOnUpdate setting in AppConfig
AppConfig.DownloadImagesOnUpdate = chkDlImages.IsChecked;

// Optionally, save the configuration to persist the change
await AppConfig.SaveConfigurationAsync();
}

private async void DlUnsecure_Changed(object sender, RoutedEventArgs e)
{
// Update the UseUnsecureConnection setting in AppConfig
AppConfig.UseUnsecureConnection = chkUnsecure.IsChecked;

// Optionally, save the configuration to persist the change
await AppConfig.SaveConfigurationAsync();
}

private void btnUpdate_Click(object sender, RoutedEventArgs e)
{
Expand Down

0 comments on commit fdf6c11

Please sign in to comment.