Fixed several errors and errorhandling

This commit is contained in:
Domi 2024-01-30 23:06:07 +01:00
parent b71af71035
commit 8f6433f16a
2 changed files with 212 additions and 32 deletions

View File

@ -5,7 +5,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:OfficeConverter" xmlns:local="clr-namespace:OfficeConverter"
mc:Ignorable="d" mc:Ignorable="d"
Title="OfficeConverter 1.0" Height="715" Width="1045" Background="#FF1A1A1A"> Title="OfficeConverter 1.0" Height="715" Width="1460" Background="#FF1A1A1A">
<Grid Background="#FF424242"> <Grid Background="#FF424242">
<Grid Margin="0,70,0,0" Background="#FF1A1A1A" Grid.ColumnSpan="2"> <Grid Margin="0,70,0,0" Background="#FF1A1A1A" Grid.ColumnSpan="2">
@ -29,7 +29,7 @@
<Button x:Name="btnDestFolder" Content="btnDest" Margin="545,171,0,0" VerticalAlignment="Top" Click="btnDestFolder_Click"/> <Button x:Name="btnDestFolder" Content="btnDest" Margin="545,171,0,0" VerticalAlignment="Top" Click="btnDestFolder_Click"/>
</Grid> </Grid>
</GroupBox> </GroupBox>
<GroupBox x:Name="grpFiles" Header="grpFiles" Margin="709,10,0,0" Height="243" VerticalAlignment="Top" HorizontalAlignment="Left" Width="300"> <GroupBox x:Name="grpFiles" Header="grpFiles" Margin="709,10,0,0" Height="276" VerticalAlignment="Top" HorizontalAlignment="Left" Width="300">
<Grid> <Grid>
<CheckBox x:Name="chkWord" Content="Word .doc" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top"/> <CheckBox x:Name="chkWord" Content="Word .doc" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top"/>
<CheckBox x:Name="chkExcel" Content="Excel .xls" HorizontalAlignment="Left" Margin="0,45,0,0" VerticalAlignment="Top"/> <CheckBox x:Name="chkExcel" Content="Excel .xls" HorizontalAlignment="Left" Margin="0,45,0,0" VerticalAlignment="Top"/>
@ -49,12 +49,23 @@
</Grid> </Grid>
</GroupBox> </GroupBox>
<Button x:Name="btnConvert" Content="Button" HorizontalAlignment="Left" Margin="10,555,0,0" VerticalAlignment="Top" Width="174" Height="42" Click="btnConvert_Click"/> <Button x:Name="btnConvert" Content="Button" HorizontalAlignment="Left" Margin="10,555,0,0" VerticalAlignment="Top" Width="174" Height="42" Click="btnConvert_Click"/>
<Label x:Name="lblState" Content="lblState" HorizontalAlignment="Left" Margin="709,258,0,0" VerticalAlignment="Top" Width="300" Height="28"/>
<Button x:Name="btnExport" Content="btnExport" HorizontalAlignment="Left" Height="33" Margin="915,555,0,0" VerticalAlignment="Top" Width="94" Click="btnExport_Click"/> <Button x:Name="btnExport" Content="btnExport" HorizontalAlignment="Left" Height="33" Margin="915,555,0,0" VerticalAlignment="Top" Width="94" Click="btnExport_Click"/>
<Button x:Name="btnDelete" Content="btnDelete" HorizontalAlignment="Left" Margin="793,555,0,0" VerticalAlignment="Top" Width="117" Height="33" Click="btnDelete_Click"/> <Button x:Name="btnDelete" Content="btnDelete" HorizontalAlignment="Left" Margin="793,555,0,0" VerticalAlignment="Top" Width="117" Height="33" Click="btnDelete_Click"/>
<GroupBox HorizontalAlignment="Left" Height="540" Header="Log" Margin="1028,10,0,0" VerticalAlignment="Top" Width="360">
<Grid>
<ListBox x:Name="lstLog" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" ScrollViewer.HorizontalScrollBarVisibility="Auto">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" TextAlignment="Left"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</GroupBox>
<Button x:Name="btnExportLog" Content="btnExportLog" HorizontalAlignment="Left" Height="33" Margin="1294,555,0,0" VerticalAlignment="Top" Width="94" Click="btnExport_Click"/>
</Grid> </Grid>
<Label Content="Office Document Converter" HorizontalAlignment="Left" Margin="10,16,0,0" VerticalAlignment="Top" Width="277" FontSize="20"/> <Label Content="Office Document Converter" HorizontalAlignment="Left" Margin="10,16,0,0" VerticalAlignment="Top" Width="277" FontSize="20"/>
<ComboBox x:Name="cmbLang" HorizontalAlignment="Left" Margin="887,33,0,0" VerticalAlignment="Top" Width="120" SelectionChanged="cmbLang_SelectionChanged"/> <ComboBox x:Name="cmbLang" HorizontalAlignment="Left" Margin="1267,33,0,0" VerticalAlignment="Top" Width="120" SelectionChanged="cmbLang_SelectionChanged"/>
</Grid> </Grid>
</Window> </Window>

View File

@ -1,8 +1,10 @@
using System; using Microsoft.VisualBasic;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -28,6 +30,8 @@ namespace OfficeConverter
List<string> combinedFiles = new List<string>(); List<string> combinedFiles = new List<string>();
List<string> convertedFiles = new List<string>(); List<string> convertedFiles = new List<string>();
private List<string> logEntries = new List<string>();
//Globalvariables //Globalvariables
bool doSubfolders = false; bool doSubfolders = false;
bool doReplace = false; bool doReplace = false;
@ -40,7 +44,10 @@ namespace OfficeConverter
public MainWindow() public MainWindow()
{ {
InitializeComponent(); InitializeComponent();
System.Diagnostics.PresentationTraceSources.SetTraceLevel(lstSourceFiles.ItemContainerGenerator, System.Diagnostics.PresentationTraceLevel.High);
setLangEN(); setLangEN();
chkWord.IsChecked = true; chkWord.IsChecked = true;
chkExcel.IsChecked = true; chkExcel.IsChecked = true;
@ -55,23 +62,39 @@ namespace OfficeConverter
backgroundWorker.DoWork += BackgroundWorker_DoWork; backgroundWorker.DoWork += BackgroundWorker_DoWork;
backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged; backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted; backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
lblState.Content = "Ready"; //lblState.Content = "Ready";
cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource = new CancellationTokenSource();
} }
private void UpdateLog(string logEntry)
{
// Use Dispatcher.Invoke to update UI elements from the UI thread
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
logEntries.Add(logEntry);
// Update the ListBox with log entries
lstLog.ItemsSource = logEntries;
lstLog.Items.Refresh();
lstLog.ScrollIntoView(logEntry);
lstLog.HorizontalContentAlignment = HorizontalAlignment.Right;
});
}
//Konvertier-Button //Konvertier-Button
private void btnConvert_Click(object sender, RoutedEventArgs e) private void btnConvert_Click(object sender, RoutedEventArgs e)
{ {
string folderPath = txtSourceFolder.Text; string folderPath = txtSourceFolder.Text;
if (cmbLang.SelectedIndex == 0) //if (cmbLang.SelectedIndex == 0)
{ //{
lblState.Content = "Conversion in progress"; // lblState.Content = "Conversion in progress";
} //}
if (cmbLang.SelectedIndex == 1) //if (cmbLang.SelectedIndex == 1)
{ //{
lblState.Content = "Konvertierung läuft"; // lblState.Content = "Konvertierung läuft";
} //}
doSubfolders = (bool)chkSubfolders.IsChecked; doSubfolders = (bool)chkSubfolders.IsChecked;
doReplace = (bool)chkReplace.IsChecked; doReplace = (bool)chkReplace.IsChecked;
@ -80,6 +103,8 @@ namespace OfficeConverter
doPPoint = (bool)chkPowerpoint.IsChecked; doPPoint = (bool)chkPowerpoint.IsChecked;
doWordTmpl = (bool)chkWordTmpl.IsChecked; doWordTmpl = (bool)chkWordTmpl.IsChecked;
doExcelTmpl = (bool)chkExcelTmpl.IsChecked; doExcelTmpl = (bool)chkExcelTmpl.IsChecked;
logEntries.Clear();
lstLog.Items.Refresh();
// Check if the background worker is not already running // Check if the background worker is not already running
if (!backgroundWorker.IsBusy) if (!backgroundWorker.IsBusy)
@ -144,6 +169,8 @@ namespace OfficeConverter
combinedFiles.ForEach(file => lstSourceFiles.Items.Add(file)); combinedFiles.ForEach(file => lstSourceFiles.Items.Add(file));
// Enable buttons after conversion completion // Enable buttons after conversion completion
UpdateButtonStates(true); UpdateButtonStates(true);
grpSourceFiles.Header = "Queue";
MessageBox.Show("Done");
}); });
} }
} }
@ -159,6 +186,8 @@ namespace OfficeConverter
} }
// Iterate over currentFolderFiles and start the conversion asynchronously
private async Task SearchAndConvertDocs(string folderPath, CancellationToken cancellationToken) private async Task SearchAndConvertDocs(string folderPath, CancellationToken cancellationToken)
{ {
string[] docFiles = null; string[] docFiles = null;
@ -167,32 +196,48 @@ namespace OfficeConverter
string[] dotFiles = null; string[] dotFiles = null;
string[] xltFiles = null; string[] xltFiles = null;
int wordFilesCount = 0;
int excelFilesCount = 0;
int powerpointFilesCount = 0;
int wordTemplateFilesCount = 0;
int excelTemplateFilesCount = 0;
if (doWord) if (doWord)
{ {
docFiles = Directory.GetFiles(folderPath, "*.doc"); docFiles = Directory.GetFiles(folderPath, "*.doc");
wordFilesCount = docFiles.Length;
UpdateLog($"Found {wordFilesCount} Word files (*.doc) in folder {folderPath}");
} }
if (doExcel) if (doExcel)
{ {
xlsFiles = Directory.GetFiles(folderPath, "*.xls"); xlsFiles = Directory.GetFiles(folderPath, "*.xls");
excelFilesCount = xlsFiles.Length;
UpdateLog($"Found {excelFilesCount} Excel files (*.xls) in folder {folderPath}");
} }
if (doPPoint) if (doPPoint)
{ {
pptFiles = Directory.GetFiles(folderPath, "*.ppt"); pptFiles = Directory.GetFiles(folderPath, "*.ppt");
powerpointFilesCount = pptFiles.Length;
UpdateLog($"Found {powerpointFilesCount} PowerPoint files (*.ppt) in folder {folderPath}");
} }
if (doWordTmpl) if (doWordTmpl)
{ {
dotFiles = Directory.GetFiles(folderPath, "*.dot"); dotFiles = Directory.GetFiles(folderPath, "*.dot");
wordTemplateFilesCount = dotFiles.Length;
UpdateLog($"Found {wordTemplateFilesCount} Word template files (*.dot) in folder {folderPath}");
} }
if (doExcelTmpl) if (doExcelTmpl)
{ {
dotFiles = Directory.GetFiles(folderPath, "*.dot"); xltFiles = Directory.GetFiles(folderPath, "*.xlt");
excelTemplateFilesCount = xltFiles.Length;
UpdateLog($"Found {excelTemplateFilesCount} Excel template files (*.xlt) in folder {folderPath}");
} }
// Check for null before adding to combinedFiles // Check for null before adding to combinedFiles
if (docFiles != null) if (docFiles != null)
{ {
combinedFiles.AddRange(docFiles); combinedFiles.AddRange(docFiles);
} }
if (xlsFiles != null) if (xlsFiles != null)
{ {
@ -210,7 +255,9 @@ namespace OfficeConverter
{ {
combinedFiles.AddRange(xltFiles); combinedFiles.AddRange(xltFiles);
} }
Console.WriteLine($"Processing files in folder: {folderPath}"); Console.WriteLine($"Processing files in folder: {folderPath}");
UpdateLog($"Processing files in folder: {folderPath}");
/// Create a copy of the collection to avoid modification during iteration /// Create a copy of the collection to avoid modification during iteration
List<string> snapshot = new List<string>(combinedFiles); List<string> snapshot = new List<string>(combinedFiles);
@ -253,6 +300,7 @@ namespace OfficeConverter
{ {
combinedFiles.Clear(); combinedFiles.Clear();
} }
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
@ -266,6 +314,12 @@ namespace OfficeConverter
foreach (var subfolder in subfolders) foreach (var subfolder in subfolders)
{ {
// Pass the cancellation token to the recursive call // Pass the cancellation token to the recursive call
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
string headerName = Path.GetFileName(subfolder);
grpSourceFiles.Header = headerName;
});
await SearchAndConvertDocs(subfolder, cancellationToken); await SearchAndConvertDocs(subfolder, cancellationToken);
// Check for cancellation after processing each subfolder // Check for cancellation after processing each subfolder
@ -276,14 +330,16 @@ namespace OfficeConverter
} }
} }
} }
// Use Dispatcher.Invoke to update UI elements from the UI thread
//System.Windows.Application.Current.Dispatcher.Invoke(() =>
//{
// lblState.Content = "Background work completed!";
//});
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
lblState.Content = "Background work completed!";
});
DisplayCombinedFiles(); DisplayCombinedFiles();
} }
private async Task ConvertFileToNewFormatAsync(string filePath) private async Task ConvertFileToNewFormatAsync(string filePath)
{ {
await Task.Run(() => await Task.Run(() =>
@ -318,23 +374,36 @@ namespace OfficeConverter
// Handle other file types or show an error message // Handle other file types or show an error message
Console.WriteLine($"Unsupported file type: {filePath}"); Console.WriteLine($"Unsupported file type: {filePath}");
break; break;
} }
string logEntry = $"Converted file: {filePath}";
Console.WriteLine(logEntry);
UpdateLog(logEntry);
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
combinedFiles.Remove(filePath);
if (!convertedFiles.Contains(filePath))
{
convertedFiles.Add(filePath);
DisplayCombinedFiles();
}
DisplayCombinedFiles();
});
} }
catch (Exception ex) catch (Exception ex)
{ {
// Handle exceptions during conversion // Handle exceptions during conversion
Console.WriteLine($"Error converting {filePath}: {ex.Message}"); string logEntry = $"Error converting {filePath}: {ex.Message}";
Console.WriteLine(logEntry);
UpdateLog(logEntry);
} }
}); });
// Update UI on the main thread // Update UI on the main thread
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
combinedFiles.Remove(filePath);
convertedFiles.Add(filePath);
DisplayCombinedFiles();
});
} }
private void ConvertXlsToXlsx(string xlsFile, bool doSubfolders, bool doReplace) private void ConvertXlsToXlsx(string xlsFile, bool doSubfolders, bool doReplace)
{ {
@ -364,6 +433,20 @@ namespace OfficeConverter
workbook.SaveAs(newXlsxPath, Excel.XlFileFormat.xlOpenXMLWorkbook); workbook.SaveAs(newXlsxPath, Excel.XlFileFormat.xlOpenXMLWorkbook);
workbook.Close(); workbook.Close();
} }
catch (Exception ex)
{
// Handle or log the exception
Console.WriteLine($"Error converting {xlsFile} to .dotx: {ex.Message}");
string logEntry = $"Error converting {xlsFile} to .dotx: {ex.Message}";
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
logEntries.Add(logEntry);
// Update the ListBox with log entries
lstLog.ItemsSource = logEntries;
lstLog.Items.Refresh();
lstLog.ScrollIntoView(logEntry);
});
}
finally finally
{ {
// Quit Excel and release resources // Quit Excel and release resources
@ -404,6 +487,20 @@ namespace OfficeConverter
workbook.SaveAs(newXltxPath, Excel.XlFileFormat.xlOpenXMLTemplate); workbook.SaveAs(newXltxPath, Excel.XlFileFormat.xlOpenXMLTemplate);
workbook.Close(); workbook.Close();
} }
catch (Exception ex)
{
// Handle or log the exception
Console.WriteLine($"Error converting {xltFile} to .dotx: {ex.Message}");
string logEntry = $"Error converting {xltFile} to .dotx: {ex.Message}";
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
logEntries.Add(logEntry);
// Update the ListBox with log entries
lstLog.ItemsSource = logEntries;
lstLog.Items.Refresh();
lstLog.ScrollIntoView(logEntry);
});
}
finally finally
{ {
// Quit Excel and release resources // Quit Excel and release resources
@ -462,6 +559,20 @@ namespace OfficeConverter
presentation.SaveAs(newPptxPath, PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation); presentation.SaveAs(newPptxPath, PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation);
presentation.Close(); presentation.Close();
} }
catch (Exception ex)
{
// Handle or log the exception
Console.WriteLine($"Error converting {pptFile} to .dotx: {ex.Message}");
string logEntry = $"Error converting {pptFile} to .dotx: {ex.Message}";
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
logEntries.Add(logEntry);
// Update the ListBox with log entries
lstLog.ItemsSource = logEntries;
lstLog.Items.Refresh();
lstLog.ScrollIntoView(logEntry);
});
}
finally finally
{ {
// Set PowerPoint application visibility back to true before quitting // Set PowerPoint application visibility back to true before quitting
@ -499,6 +610,20 @@ namespace OfficeConverter
doc.SaveAs2(newDocxPath, Word.WdSaveFormat.wdFormatXMLDocument); doc.SaveAs2(newDocxPath, Word.WdSaveFormat.wdFormatXMLDocument);
doc.Close(); doc.Close();
} }
catch (Exception ex)
{
// Handle or log the exception
Console.WriteLine($"Error converting {docFile} to .dotx: {ex.Message}");
string logEntry = $"Error converting {docFile} to .dotx: {ex.Message}";
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
logEntries.Add(logEntry);
// Update the ListBox with log entries
lstLog.ItemsSource = logEntries;
lstLog.Items.Refresh();
lstLog.ScrollIntoView(logEntry);
});
}
finally finally
{ {
// Quit Word and release resources // Quit Word and release resources
@ -537,6 +662,20 @@ namespace OfficeConverter
doc.SaveAs2(newDotxPath, Word.WdSaveFormat.wdFormatXMLTemplate); doc.SaveAs2(newDotxPath, Word.WdSaveFormat.wdFormatXMLTemplate);
doc.Close(); doc.Close();
} }
catch (Exception ex)
{
// Handle or log the exception
Console.WriteLine($"Error converting {dotFile} to .dotx: {ex.Message}");
string logEntry = $"Error converting {dotFile} to .dotx: {ex.Message}";
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
logEntries.Add(logEntry);
// Update the ListBox with log entries
lstLog.ItemsSource = logEntries;
lstLog.Items.Refresh();
lstLog.ScrollIntoView(logEntry);
});
}
finally finally
{ {
// Quit Word and release resources // Quit Word and release resources
@ -591,10 +730,10 @@ namespace OfficeConverter
string sourceFolderName = Path.GetFileName(originalFolderPath); string sourceFolderName = Path.GetFileName(originalFolderPath);
// Remove the source folder name from the target path // Remove the source folder name from the target path
targetFolder = targetFolder.Replace(sourceFolderName, "").TrimEnd('\\'); targetFolder = targetFolder.TrimEnd('\\');
// Replace the original folder path with the destination folder path // Replace the original folder path with the destination folder path
targetFolder = targetFolder.Replace(originalFolderPath, txtDestFolder.Text.TrimEnd('\\')); //targetFolder = targetFolder.Replace(originalFolderPath, txtDestFolder.Text.TrimEnd('\\'));
} }
} }
@ -634,6 +773,7 @@ namespace OfficeConverter
btnDelete.Content = "Delete Files"; btnDelete.Content = "Delete Files";
btnExport.Content = "Export list"; btnExport.Content = "Export list";
errorFolderEmpty = "Destination folder is required when 'Replace files' is not selected."; errorFolderEmpty = "Destination folder is required when 'Replace files' is not selected.";
btnExportLog.Content = "Save Log";
} }
private void setLangDE() private void setLangDE()
{ {
@ -651,6 +791,7 @@ namespace OfficeConverter
btnDelete.Content = "Dateien löschen"; btnDelete.Content = "Dateien löschen";
btnExport.Content = "Liste exportieren"; btnExport.Content = "Liste exportieren";
errorFolderEmpty = "Zielordner darf nicht leer sein, wenn 'Ersetze Dateien' nicht gewählt wurde."; errorFolderEmpty = "Zielordner darf nicht leer sein, wenn 'Ersetze Dateien' nicht gewählt wurde.";
btnExportLog.Content = "Log sichern";
} }
private void btnDestFolder_Click(object sender, RoutedEventArgs e) private void btnDestFolder_Click(object sender, RoutedEventArgs e)
{ {
@ -748,6 +889,20 @@ namespace OfficeConverter
System.Windows.MessageBox.Show($"Error exporting converted files: {ex.Message}"); System.Windows.MessageBox.Show($"Error exporting converted files: {ex.Message}");
} }
} }
private void ExportConvertedLogFilesToFile(string filePath)
{
try
{
// Write the contents of the convertedFiles list to a text file
File.WriteAllLines(filePath, logEntries);
System.Windows.MessageBox.Show($"Export successful. File saved at: {filePath}");
}
catch (Exception ex)
{
System.Windows.MessageBox.Show($"Error exporting converted files: {ex.Message}");
}
}
private void btnExport_Click(object sender, RoutedEventArgs e) private void btnExport_Click(object sender, RoutedEventArgs e)
{ {
@ -764,7 +919,21 @@ namespace OfficeConverter
ExportConvertedFilesToFile(saveFileDialog.FileName); ExportConvertedFilesToFile(saveFileDialog.FileName);
} }
} }
private void btnExportLog_Click(object sender, RoutedEventArgs e)
{
// Use a SaveFileDialog to let the user choose the export file location
var saveFileDialog = new Microsoft.Win32.SaveFileDialog
{
Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*",
DefaultExt = "txt"
};
if (saveFileDialog.ShowDialog() == true)
{
// Call the ExportConvertedFilesToFile method with the selected file path
ExportConvertedLogFilesToFile(saveFileDialog.FileName);
}
}
private async void DeleteConvertedFilesAsync() private async void DeleteConvertedFilesAsync()
{ {
// Show a confirmation dialog // Show a confirmation dialog