Skip to content

Commit

Permalink
added config verification at startup
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexanderSharykin committed Jun 19, 2017
1 parent 9b43396 commit 838e572
Show file tree
Hide file tree
Showing 9 changed files with 182 additions and 22 deletions.
Binary file modified Screenshots/Library Commander.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
119 changes: 108 additions & 11 deletions Src/LibraryCommander/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Data.SQLite;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using BusinessLogic;
using BusinessLogic.Fs;
using DataAccess;
Expand All @@ -32,8 +35,55 @@ public partial class App : Application

private void App_OnStartup(object sender, StartupEventArgs e)
{
DispatcherUnhandledException += LogUnhandledDispatcherException;
AppDomain.CurrentDomain.UnhandledException += LogUnhandledDomainException;
TaskScheduler.UnobservedTaskException += LogTaskSchedulerUnobservedTaskException;

LocalizationProvider.CurrentCulture = Thread.CurrentThread.CurrentUICulture;
BusinessLogic.Localization.Instance = new LocalizationModel();
Injector.Localization = new LocalizationVm();

// Db verification
AppSettings settings;
try
{
// trying to get app setting from db
settings = new EntityRepository<AppSettings>().Query().FirstOrDefault();
}
catch (Exception ex)
{
var m = new MessageVm { Text = Injector.Localization.DbConnectionError };

// cannot get data from SQLite db
if (ex is SQLiteException || ex.InnerException is SQLiteException)
m.Text += Environment.NewLine + Injector.Localization.SQLiteError;

ShowMessage(m);
Application.Current.Shutdown();
return;
}

// restore last localization from settings
if (settings != null && String.IsNullOrWhiteSpace(settings.Culture) == false)
LocalizationProvider.CurrentCulture = new CultureInfo(settings.Culture);

string library = ConfigurationManager.AppSettings["library"];

// Storage verification
if (false == Directory.Exists(library))
{
var m = new MessageVm
{
Text = Injector.Localization.FolderNotFound + Environment.NewLine +
library + Environment.NewLine +
Injector.Localization.StorageError
};

ShowMessage(m);
Application.Current.Shutdown();
return;
}

var args = Environment.GetCommandLineArgs();
Resources.MergedDictionaries.Clear();
// apply a skin
Expand Down Expand Up @@ -65,23 +115,13 @@ private void App_OnStartup(object sender, StartupEventArgs e)
c.Register(() => new FileFormatManager { Repository = new FileFormatRepository() });
c.Register(() => new BookManager { Repository = new BookRepository() });

c.Register(() => new SearchNavigator(library) { Repository = new BookRepository() });
c.Register(() => new SearchNavigator(library) { Repository = new BookRepository() });
c.Register(() => new VirtualFsNavigator(library)
{
BookRepository = new BookRepository(),
CategoryRepository = new CategoryRepository()
});
Injector.Container = c;

var settings = new EntityRepository<AppSettings>().Query().FirstOrDefault();

// configurate localization
if (settings != null && String.IsNullOrWhiteSpace(settings.Culture) == false)
LocalizationProvider.CurrentCulture = new CultureInfo(settings.Culture);
else
LocalizationProvider.CurrentCulture = Thread.CurrentThread.CurrentUICulture;
BusinessLogic.Localization.Instance = new LocalizationModel();
Injector.Localization = new LocalizationVm();

StorageManager.StoragePath = library;
UsageValidator.Repository = new BookRepository();
Expand All @@ -107,6 +147,10 @@ private void App_OnStartup(object sender, StartupEventArgs e)

private void App_OnExit(object sender, ExitEventArgs e)
{
// app initialization was not completed. quit without changing settings
if (_commander == null)
return;

// save app setting on Exit
var rep = new EntityRepository<AppSettings>();
var settings = rep.Query().FirstOrDefault() ?? new AppSettings();
Expand All @@ -124,5 +168,58 @@ private void App_OnExit(object sender, ExitEventArgs e)

rep.SaveOrUpdate(settings);
}

private void ShowMessage(MessageVm m)
{
new WpfMessageBox().ShowDialog(m);
}

private void ShowExceptionMessage(Exception ex, string source)
{
var m = new MessageVm
{
Text = ex.Message + Environment.NewLine + Injector.Localization.LogRequest,
Yes = true,
No = true,
};

// request to create log file
new WpfMessageBox().ShowDialog(m);

if (m.DialogResult.ToString() != "Yes")
return;

try
{
File.WriteAllLines("Log " + DateTime.Now.ToString("dd-mm-yy hh-MM-ss") + ".txt",
new[]
{
source,
ex.GetType().FullName,
ex.Message,
ex.StackTrace
});
}
catch
{
// log write failed
}
}

private void LogTaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs arg)
{
ShowExceptionMessage(arg.Exception, "TaskScheduler.UnobservedTaskException");
}

private void LogUnhandledDomainException(object sender, UnhandledExceptionEventArgs arg)
{
ShowExceptionMessage(arg.ExceptionObject as Exception, "AppDomain.CurrentDomain.UnhandledException: " + String.Format("IsTerminating = {0}", arg.IsTerminating));
}

private void LogUnhandledDispatcherException(object sender, DispatcherUnhandledExceptionEventArgs arg)
{
ShowExceptionMessage(arg.Exception, "DispatcherUnhandledException");
arg.Handled = true;
}
}
}
5 changes: 5 additions & 0 deletions Src/LibraryCommander/Localization/LocalizationVm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,10 @@ public class LocalizationVm: LocalizationProvider, ILocalizationVm

public string FileNotFound { get { return GetResource(); } }
public string FolderNotFound { get { return GetResource(); } }

public string DbConnectionError { get { return GetResource(); } }
public string SQLiteError { get { return GetResource(); } }
public string StorageError { get { return GetResource(); } }
public string LogRequest { get { return GetResource(); } }
}
}
11 changes: 2 additions & 9 deletions Src/LibraryCommander/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -200,15 +200,8 @@
<!--<Setter Property="Background" Value="Transparent"/>-->
<!--<Setter Property="IsHitTestVisible" Value="False"/>-->
<Setter Property="local:Attached.IsFocused" Value="{Binding Path=IsSelected, RelativeSource={RelativeSource Self}, Mode=OneWay}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
<Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
</Style.Triggers>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
</Style>
</DataGrid.CellStyle>

Expand Down
4 changes: 2 additions & 2 deletions Src/LibraryCommander/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,5 @@
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
36 changes: 36 additions & 0 deletions Src/LibraryCommander/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions Src/LibraryCommander/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -247,4 +247,16 @@
<data name="LanguageUsageWarning" xml:space="preserve">
<value>Library contains book(s) in language [{0}]</value>
</data>
<data name="DbConnectionError" xml:space="preserve">
<value>Cannot connect to database.</value>
</data>
<data name="LogRequest" xml:space="preserve">
<value>Create log file?</value>
</data>
<data name="SQLiteError" xml:space="preserve">
<value>If app was launched with default settings, file Books.db is possibly missing.</value>
</data>
<data name="StorageError" xml:space="preserve">
<value>Change "library" value in application .CONFIG file (should be full path of an existing folder)</value>
</data>
</root>
12 changes: 12 additions & 0 deletions Src/LibraryCommander/Properties/Resources.ru-Ru.resx
Original file line number Diff line number Diff line change
Expand Up @@ -313,4 +313,16 @@
<data name="LanguageUsageWarning" xml:space="preserve">
<value>В библиотеке есть книги на языке [{0}]</value>
</data>
<data name="DbConnectionError" xml:space="preserve">
<value>Не удалось подключиться к базе данных.</value>
</data>
<data name="LogRequest" xml:space="preserve">
<value>Создать файл с информацией об ошибке?</value>
</data>
<data name="SQLiteError" xml:space="preserve">
<value>Возможно отсутствует файл Books.db, если приложение было запущено с настройками по умолчанию.</value>
</data>
<data name="StorageError" xml:space="preserve">
<value>Заполните значение поля "library" в конфигурационном файле приложения (расширение .CONFIG). Укажите полный путь к существующему каталогу, который будет использоваться для хранения документов.</value>
</data>
</root>
5 changes: 5 additions & 0 deletions Src/ViewModels/ILocalizationVm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,10 @@ public interface ILocalizationVm
string Library { get; }
string FileNotFound { get; }
string FolderNotFound { get; }

string DbConnectionError { get; }
string SQLiteError { get; }
string StorageError { get; }
string LogRequest { get; }
}
}

0 comments on commit 838e572

Please sign in to comment.