From c373125b2f09003f7a461cec303dc8f2f80bd9f6 Mon Sep 17 00:00:00 2001 From: dtaylor-530 Date: Sun, 17 May 2020 11:29:06 +0100 Subject: [PATCH 1/3] Updated to LiteDB version 5. - LiteFileInfo now generic - JsonSerializer parameters have been limited - AsString method no longer works on ObjectId - LiteDatabase now missing Engine property and Shrink method - LiteFileInfo missing AsDocument property References to version 4 converted to 5 via new Config property, 'Version' --- .../LiteDbExplorer.Core.csproj | 2 +- .../Store/CollectionReference.cs | 4 ++-- .../Store/DocumentReference.cs | 8 +++---- .../Store/DocumentReferenceAggregator.cs | 8 +++---- .../Store/FileDocumentReference.cs | 2 +- .../Store/JsonSerializerExtension.cs | 4 ++-- .../Store/LiteDbReferenceExtensions.cs | 2 +- .../LiteDbExplorer.Core/Store/QueryResult.cs | 14 +++++------ .../Types/IJsonSerializerProvider.cs | 4 ++-- source/LiteDbExplorer/App.config | 1 + source/LiteDbExplorer/App.xaml.cs | 4 ++-- source/LiteDbExplorer/Application/Config.cs | 2 ++ .../Controls/BsonValueEditor.cs | 2 +- .../Controls/CollectionListView.xaml.cs | 2 +- .../LiteDbExplorer/Controls/FileView.xaml.cs | 24 ++++++++----------- source/LiteDbExplorer/LiteDbExplorer.csproj | 2 +- .../DbDocument/DocumentPreviewViewModel.cs | 2 +- .../Modules/StartPage/StartPage.xaml | 22 ++++++++++------- 18 files changed, 57 insertions(+), 52 deletions(-) diff --git a/source/LiteDbExplorer.Core/LiteDbExplorer.Core.csproj b/source/LiteDbExplorer.Core/LiteDbExplorer.Core.csproj index d47e411..c6368df 100644 --- a/source/LiteDbExplorer.Core/LiteDbExplorer.Core.csproj +++ b/source/LiteDbExplorer.Core/LiteDbExplorer.Core.csproj @@ -13,7 +13,7 @@ - + diff --git a/source/LiteDbExplorer.Core/Store/CollectionReference.cs b/source/LiteDbExplorer.Core/Store/CollectionReference.cs index a9091a5..387fe3c 100644 --- a/source/LiteDbExplorer.Core/Store/CollectionReference.cs +++ b/source/LiteDbExplorer.Core/Store/CollectionReference.cs @@ -23,7 +23,7 @@ public CollectionReference(string name, DatabaseReference database) [AlsoNotifyFor(nameof(LiteCollection))] public DatabaseReference Database { get; set; } - public LiteCollection LiteCollection => Database.LiteDatabase.GetCollection(Name); + public ILiteCollection LiteCollection => Database.LiteDatabase.GetCollection(Name); public ObservableCollection Items { @@ -120,7 +120,7 @@ public IReadOnlyList GetDistinctKeys(FieldSortOrder sortOrder = FieldSor return Items.SelectAllDistinctKeys(sortOrder).ToList(); } - protected virtual IEnumerable GetAllItem(LiteCollection liteCollection) + protected virtual IEnumerable GetAllItem(ILiteCollection liteCollection) { /*if (IsFilesOrChunks) { diff --git a/source/LiteDbExplorer.Core/Store/DocumentReference.cs b/source/LiteDbExplorer.Core/Store/DocumentReference.cs index f4b0c7d..132a080 100644 --- a/source/LiteDbExplorer.Core/Store/DocumentReference.cs +++ b/source/LiteDbExplorer.Core/Store/DocumentReference.cs @@ -67,14 +67,14 @@ protected override void Dispose(bool disposing) Collection = null; } - public string Serialize(bool pretty = false, bool decoded = true) + public string Serialize(bool decoded = true) { - return decoded ? LiteDocument.SerializeDecoded(true) : JsonSerializer.Serialize(LiteDocument, pretty, false); + return decoded ? LiteDocument.SerializeDecoded() : JsonSerializer.Serialize(LiteDocument); } - public void Serialize(TextWriter writer, bool pretty = false) + public void Serialize(TextWriter writer) { - JsonSerializer.Serialize(LiteDocument, writer, pretty, false); + JsonSerializer.Serialize(LiteDocument, writer); } } } \ No newline at end of file diff --git a/source/LiteDbExplorer.Core/Store/DocumentReferenceAggregator.cs b/source/LiteDbExplorer.Core/Store/DocumentReferenceAggregator.cs index 5225d6e..9aa7fc4 100644 --- a/source/LiteDbExplorer.Core/Store/DocumentReferenceAggregator.cs +++ b/source/LiteDbExplorer.Core/Store/DocumentReferenceAggregator.cs @@ -27,14 +27,14 @@ public BsonArray Value } } - public string Serialize(bool pretty = false, bool writeBinary = true) + public string Serialize() { - return JsonSerializer.Serialize(Value, pretty, writeBinary); + return JsonSerializer.Serialize(Value); } - public void Serialize(TextWriter writer, bool pretty = false, bool writeBinary = true) + public void Serialize(TextWriter writer) { - JsonSerializer.Serialize(Value, writer, pretty, writeBinary); + JsonSerializer.Serialize(Value, writer); } } } \ No newline at end of file diff --git a/source/LiteDbExplorer.Core/Store/FileDocumentReference.cs b/source/LiteDbExplorer.Core/Store/FileDocumentReference.cs index f892d89..61b26fe 100644 --- a/source/LiteDbExplorer.Core/Store/FileDocumentReference.cs +++ b/source/LiteDbExplorer.Core/Store/FileDocumentReference.cs @@ -24,7 +24,7 @@ public void SaveFile(string path) file.SaveAs(path); } - public LiteFileInfo GetFileObject() + public LiteFileInfo GetFileObject() { return Collection.Database.LiteDatabase.FileStorage.FindById(LiteDocument["_id"]); } diff --git a/source/LiteDbExplorer.Core/Store/JsonSerializerExtension.cs b/source/LiteDbExplorer.Core/Store/JsonSerializerExtension.cs index 23d8767..505406e 100644 --- a/source/LiteDbExplorer.Core/Store/JsonSerializerExtension.cs +++ b/source/LiteDbExplorer.Core/Store/JsonSerializerExtension.cs @@ -5,9 +5,9 @@ namespace LiteDbExplorer.Core public static class JsonSerializerExtension { - public static string SerializeDecoded(this BsonValue bsonValue, bool pretty = false) + public static string SerializeDecoded(this BsonValue bsonValue) { - var json = JsonSerializer.Serialize(bsonValue, pretty, false); + var json = JsonSerializer.Serialize(bsonValue); return EncodingExtensions.DecodeEncodedNonAsciiCharacters(json); } diff --git a/source/LiteDbExplorer.Core/Store/LiteDbReferenceExtensions.cs b/source/LiteDbExplorer.Core/Store/LiteDbReferenceExtensions.cs index 8696903..9e94d2c 100644 --- a/source/LiteDbExplorer.Core/Store/LiteDbReferenceExtensions.cs +++ b/source/LiteDbExplorer.Core/Store/LiteDbReferenceExtensions.cs @@ -96,7 +96,7 @@ public static string ToDisplayName(this DocumentReference documentReference) return string.Empty; } - return string.Join(" - ", documentReference.Collection?.Name, documentReference.LiteDocument["_id"].AsString); + return string.Join(" - ", documentReference.Collection?.Name, documentReference.LiteDocument["_id"].RawValue.ToString()); } public static string ToDisplayValue(this BsonValue bsonValue, int? maxLength = null, ICultureFormat cultureFormat = null) diff --git a/source/LiteDbExplorer.Core/Store/QueryResult.cs b/source/LiteDbExplorer.Core/Store/QueryResult.cs index 11e9dfe..6680627 100644 --- a/source/LiteDbExplorer.Core/Store/QueryResult.cs +++ b/source/LiteDbExplorer.Core/Store/QueryResult.cs @@ -38,31 +38,31 @@ public QueryResult(IEnumerable bsonValues, ICultureFormat cultureForm public DataTable DataTable => Source.ToDataTable(_cultureFormat); - public string Serialize(bool pretty = false, bool decoded = true) + public string Serialize(bool decoded = true) { var json = string.Empty; - + if (IsArray) { - json = JsonSerializer.Serialize(AsArray, pretty, false); + json = JsonSerializer.Serialize(AsArray); } else if (IsDocument) { - json = JsonSerializer.Serialize(AsDocument, pretty, false); + json = JsonSerializer.Serialize(AsDocument); } return decoded ? EncodingExtensions.DecodeEncodedNonAsciiCharacters(json) : json; } - public void Serialize(TextWriter writer, bool pretty = false) + public void Serialize(TextWriter writer) { if (IsArray) { - JsonSerializer.Serialize(AsArray, writer, pretty, false); + JsonSerializer.Serialize(AsArray, writer); } else if (IsDocument) { - JsonSerializer.Serialize(AsDocument, writer, pretty, false); + JsonSerializer.Serialize(AsDocument, writer); } } diff --git a/source/LiteDbExplorer.Core/Types/IJsonSerializerProvider.cs b/source/LiteDbExplorer.Core/Types/IJsonSerializerProvider.cs index 25948dc..488ef51 100644 --- a/source/LiteDbExplorer.Core/Types/IJsonSerializerProvider.cs +++ b/source/LiteDbExplorer.Core/Types/IJsonSerializerProvider.cs @@ -4,7 +4,7 @@ namespace LiteDbExplorer.Core { public interface IJsonSerializerProvider { - string Serialize(bool pretty = false, bool decoded = true); - void Serialize(TextWriter writer, bool pretty = false); + string Serialize(bool decoded); + void Serialize(TextWriter writer); } } \ No newline at end of file diff --git a/source/LiteDbExplorer/App.config b/source/LiteDbExplorer/App.config index 1e488f1..a3a689d 100644 --- a/source/LiteDbExplorer/App.config +++ b/source/LiteDbExplorer/App.config @@ -14,6 +14,7 @@ + diff --git a/source/LiteDbExplorer/App.xaml.cs b/source/LiteDbExplorer/App.xaml.cs index d083758..f1c99e5 100644 --- a/source/LiteDbExplorer/App.xaml.cs +++ b/source/LiteDbExplorer/App.xaml.cs @@ -124,7 +124,7 @@ private void CreateJumpList() var openDatabaseTask = new JumpTask { Title = "Open database", - Description = "Open LiteDB v4 database file", + Description = $"Open LiteDB database file, version {Config.Version}", ApplicationPath = applicationPath, Arguments = @"open" }; @@ -133,7 +133,7 @@ private void CreateJumpList() var newDatabaseTask = new JumpTask { Title = "New database", - Description = "Create and open new LiteDB v4 database", + Description = $"Create and open new LiteDB database, version {Config.Version}", ApplicationPath = applicationPath, Arguments = @"new" }; diff --git a/source/LiteDbExplorer/Application/Config.cs b/source/LiteDbExplorer/Application/Config.cs index 721e2db..dfd1f8c 100644 --- a/source/LiteDbExplorer/Application/Config.cs +++ b/source/LiteDbExplorer/Application/Config.cs @@ -19,6 +19,8 @@ public static class Config public static string PipeEndpoint => ConfigurationManager.AppSettings["PipeEndpoint"]; + public static string Version => ConfigurationManager.AppSettings["Version"]; + public static bool IsPortable => !File.Exists(Paths.UninstallerPath); public static void ConfigureLogger() diff --git a/source/LiteDbExplorer/Controls/BsonValueEditor.cs b/source/LiteDbExplorer/Controls/BsonValueEditor.cs index e46253d..39a059e 100644 --- a/source/LiteDbExplorer/Controls/BsonValueEditor.cs +++ b/source/LiteDbExplorer/Controls/BsonValueEditor.cs @@ -358,7 +358,7 @@ void AddValueChangedListener(FrameworkElement associatedObject, DependencyProper { var text = new TextBox { - Text = editorContext.BindingValue.AsString, + Text = editorContext.BindingValue.ToDisplayValue(), IsReadOnly = true, VerticalAlignment = VerticalAlignment.Center, }; diff --git a/source/LiteDbExplorer/Controls/CollectionListView.xaml.cs b/source/LiteDbExplorer/Controls/CollectionListView.xaml.cs index 8c43451..9c6f838 100644 --- a/source/LiteDbExplorer/Controls/CollectionListView.xaml.cs +++ b/source/LiteDbExplorer/Controls/CollectionListView.xaml.cs @@ -331,7 +331,7 @@ public void FindClear() private bool ItemMatchesSearch(string matchTerm, DocumentReference document, bool matchCase) { - var stringData = document.Serialize(false, false); + var stringData = document.Serialize(false); if (matchCase) { diff --git a/source/LiteDbExplorer/Controls/FileView.xaml.cs b/source/LiteDbExplorer/Controls/FileView.xaml.cs index 5fa6a2f..aad91b3 100644 --- a/source/LiteDbExplorer/Controls/FileView.xaml.cs +++ b/source/LiteDbExplorer/Controls/FileView.xaml.cs @@ -2,11 +2,9 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; -using System.Windows.Controls.Primitives; using System.Windows.Media; using System.Windows.Media.Imaging; using HL.Manager; @@ -14,9 +12,7 @@ using Humanizer.Bytes; using LiteDbExplorer.Wpf.Framework.Win32; using ICSharpCode.AvalonEdit; -using LiteDbExplorer.Core; using LiteDbExplorer.Presentation; -using ZoomAndPan; namespace LiteDbExplorer.Controls { @@ -54,7 +50,7 @@ private void ThemeManagerOnCurrentThemeChanged(object sender, EventArgs e) private static void OnFileSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var fileView = d as FileView; - if (e.NewValue is LiteFileInfo liteFileInfo) + if (e.NewValue is LiteFileInfo liteFileInfo) { fileView?.LoadFile(liteFileInfo); } @@ -92,7 +88,7 @@ public object FooterContent public string FileExtension { get; private set; } - public void LoadFile(LiteFileInfo file) + public void LoadFile(LiteFileInfo file) { Reset(); @@ -153,7 +149,7 @@ protected void ResetNoContentPreview() NoFilePreviewText.Text = string.Empty; } - protected void SetNoContentPreview(LiteFileInfo file, string prependMessage = null) + protected void SetNoContentPreview(LiteFileInfo file, string prependMessage = null) { var message = $"No preview for \"{file.MimeType}\"."; if (!string.IsNullOrEmpty(prependMessage)) @@ -177,7 +173,7 @@ public void Reset() ResetNoContentPreview(); } - protected void SetFileInfoContent(LiteFileInfo file) + protected void SetFileInfoContent(LiteFileInfo file) { var fileInfo = new Dictionary { @@ -245,20 +241,20 @@ protected static double PointsToPixels(double points) public abstract class FilePreviewHandler { public abstract bool CanContentScroll { get; } - public abstract bool CanHandle(LiteFileInfo file); - public abstract FrameworkElement GetPreview(LiteFileInfo file); + public abstract bool CanHandle(LiteFileInfo file); + public abstract FrameworkElement GetPreview(LiteFileInfo file); } public class ImageFilePreviewHandler : FilePreviewHandler { public override bool CanContentScroll => false; - public override bool CanHandle(LiteFileInfo file) + public override bool CanHandle(LiteFileInfo file) { return file.MimeType.StartsWith("image"); } - public override FrameworkElement GetPreview(LiteFileInfo file) + public override FrameworkElement GetPreview(LiteFileInfo file) { using (var fStream = file.OpenRead()) { @@ -308,13 +304,13 @@ public TextFilePreviewHandler() } } - public override bool CanHandle(LiteFileInfo file) + public override bool CanHandle(LiteFileInfo file) { var fileExtension = Path.GetExtension(file.Filename); return TextRegex.IsMatch(file.MimeType) || _allHandledTextExtension.Contains(fileExtension); } - public override FrameworkElement GetPreview(LiteFileInfo file) + public override FrameworkElement GetPreview(LiteFileInfo file) { var fileExtension = Path.GetExtension(file.Filename); using (var fileStream = file.OpenRead()) diff --git a/source/LiteDbExplorer/LiteDbExplorer.csproj b/source/LiteDbExplorer/LiteDbExplorer.csproj index 43eba75..142cc72 100644 --- a/source/LiteDbExplorer/LiteDbExplorer.csproj +++ b/source/LiteDbExplorer/LiteDbExplorer.csproj @@ -598,7 +598,7 @@ 2019.1.3 - 4.1.4 + 5.0.8 0.18.0 diff --git a/source/LiteDbExplorer/Modules/DbDocument/DocumentPreviewViewModel.cs b/source/LiteDbExplorer/Modules/DbDocument/DocumentPreviewViewModel.cs index a6c125d..7375684 100644 --- a/source/LiteDbExplorer/Modules/DbDocument/DocumentPreviewViewModel.cs +++ b/source/LiteDbExplorer/Modules/DbDocument/DocumentPreviewViewModel.cs @@ -56,7 +56,7 @@ private set } } - public LiteFileInfo FileInfo { get; private set; } + public LiteFileInfo FileInfo { get; private set; } public bool IsDocumentView { get; private set; } diff --git a/source/LiteDbExplorer/Modules/StartPage/StartPage.xaml b/source/LiteDbExplorer/Modules/StartPage/StartPage.xaml index f60aa38..82e5ade 100644 --- a/source/LiteDbExplorer/Modules/StartPage/StartPage.xaml +++ b/source/LiteDbExplorer/Modules/StartPage/StartPage.xaml @@ -114,7 +114,7 @@ - + - + - + @@ -250,7 +250,7 @@ - + @@ -338,9 +338,12 @@ TextTrimming="CharacterEllipsis" Style="{StaticResource MaterialDesignSubheadingTextBlock}" /> + Style="{StaticResource MaterialDesignCaptionTextBlock}" > + Open new LiteDB database, version + + @@ -361,9 +364,12 @@ TextTrimming="CharacterEllipsis" Style="{StaticResource MaterialDesignSubheadingTextBlock}" /> + Style="{StaticResource MaterialDesignCaptionTextBlock}" > + Create and open new LiteDB database, version + + From 80ac42e9cb5848a13fd991fa6621b32fd1a1e8d3 Mon Sep 17 00:00:00 2001 From: dtaylor-530 Date: Sun, 17 May 2020 11:32:42 +0100 Subject: [PATCH 2/3] Updated to LiteDB version 5 (code where updates could not be applied commented out) - LiteException.DATABASE_WRONG_PASSWORD no longer exists - LiteDatabase no longer takes logger in its constructor. - DatabaseReference no longer has method RunCommand --- .../Store/DatabaseReference.cs | 85 ++++++++----------- .../Store/FileCollectionReference.cs | 6 +- .../Database/DatabasePropertiesViewModel.cs | 9 +- .../Modules/DatabaseInteractions.cs | 68 ++++++++------- .../DbQuery/ShellCommandQueryViewHandler.cs | 12 +-- 5 files changed, 86 insertions(+), 94 deletions(-) diff --git a/source/LiteDbExplorer.Core/Store/DatabaseReference.cs b/source/LiteDbExplorer.Core/Store/DatabaseReference.cs index f91ecea..4a180dc 100644 --- a/source/LiteDbExplorer.Core/Store/DatabaseReference.cs +++ b/source/LiteDbExplorer.Core/Store/DatabaseReference.cs @@ -33,7 +33,7 @@ public DatabaseReference([NotNull] DatabaseConnectionOptions options) var connectionString = options.GetConnectionString(); - LiteDatabase = new LiteDatabase(connectionString, log: GetLogger()); + LiteDatabase = new LiteDatabase(connectionString); UpdateCollections(); @@ -50,8 +50,8 @@ public DatabaseReference([NotNull] DatabaseConnectionOptions options) public int UserVersion { - get => LiteDatabase.Engine.UserVersion; - set => LiteDatabase.Engine.UserVersion = (ushort) value; + get => LiteDatabase.UserVersion; + set => LiteDatabase.UserVersion = (ushort) value; } public ObservableCollection CollectionsLookup { get; private set; } @@ -157,24 +157,24 @@ public bool ContainsCollection(string name) return Collections.Any(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); } - public long ShrinkDatabase() - { - return LiteDatabase.Shrink(); - } + //public long ShrinkDatabase() + //{ + // return LiteDatabase.Shrink(); + //} - public long ShrinkDatabase(string password) - { - return LiteDatabase.Shrink(password); - } + //public long ShrinkDatabase(string password) + //{ + // return LiteDatabase.Shrink(password); + //} - public IList RunCommand(string command) - { - return LiteDatabase.Engine.Run(command); - } + //public IList RunCommand(string command) + //{ + // return LiteDatabase.Engine.Run(command); + //} - public BsonDocument InternalDatabaseInfo() + public BsonValue InternalDatabaseInfo() { - return LiteDatabase.Engine.Info(); + return LiteDatabase.Mapper.ToDocument(typeof(object), new { LiteDatabase.Timeout, LiteDatabase.UserVersion, LiteDatabase.UtcDate, LiteDatabase.LimitSize, LiteDatabase.CheckpointSize }); } public void BeforeDispose() @@ -188,27 +188,26 @@ public void BeforeDispose() BroadcastChanges(ReferenceNodeChangeAction.Dispose, this); } - - public static bool IsDbPasswordProtected(string path) - { - using (var db = new LiteDatabase(path)) - { - try - { - db.GetCollectionNames(); - return false; - } - catch (LiteException e) - { - if (e.ErrorCode == LiteException.DATABASE_WRONG_PASSWORD || e.Message.Contains("password")) - { - return true; - } - - throw; - } - } - } + //public static bool IsDbPasswordProtected(string path) + //{ + // using (var db = new LiteDatabase(path)) + // { + // try + // { + // db.GetCollectionNames(); + // return false; + // } + // catch (LiteException e) + // { + // if (e.ErrorCode == LiteException.DATABASE_WRONG_PASSWORD || e.Message.Contains("password")) + // { + // return true; + // } + + // throw; + // } + // } + //} protected override void Dispose(bool disposing) { @@ -271,16 +270,6 @@ private void BroadcastChanges(ReferenceNodeChangeAction action, IEnumerable { Log.ForContext("DatabaseName", Name).Information(log); }); - } - - return null; - } - private void UpdateCollections() { // TODO: Bind database tree and lazy load CollectionReference diff --git a/source/LiteDbExplorer.Core/Store/FileCollectionReference.cs b/source/LiteDbExplorer.Core/Store/FileCollectionReference.cs index eb34ae6..7993a67 100644 --- a/source/LiteDbExplorer.Core/Store/FileCollectionReference.cs +++ b/source/LiteDbExplorer.Core/Store/FileCollectionReference.cs @@ -10,7 +10,7 @@ public FileCollectionReference(string name, DatabaseReference database) : base(n { } - protected override IEnumerable GetAllItem(LiteCollection liteCollection) + protected override IEnumerable GetAllItem(ILiteCollection liteCollection) { return LiteCollection.FindAll().Select(bsonDocument => new FileDocumentReference(bsonDocument, this)); } @@ -24,7 +24,7 @@ public override void RemoveDocument(DocumentReference document) public DocumentReference AddFile(string id, string path) { var file = Database.LiteDatabase.FileStorage.Upload(id, path); - var newDoc = new DocumentReference(file.AsDocument, this); + var newDoc = new DocumentReference(Database.LiteDatabase.Mapper.ToDocument(file), this); Items.Add(newDoc); return newDoc; } @@ -35,7 +35,7 @@ public void SaveFile(DocumentReference document, string path) file.SaveAs(path); } - public LiteFileInfo GetFileObject(DocumentReference document) + public LiteFileInfo GetFileObject(DocumentReference document) { return Database.LiteDatabase.FileStorage.FindById(document.LiteDocument["_id"]); } diff --git a/source/LiteDbExplorer/Modules/Database/DatabasePropertiesViewModel.cs b/source/LiteDbExplorer/Modules/Database/DatabasePropertiesViewModel.cs index f9e1de1..76fd526 100644 --- a/source/LiteDbExplorer/Modules/Database/DatabasePropertiesViewModel.cs +++ b/source/LiteDbExplorer/Modules/Database/DatabasePropertiesViewModel.cs @@ -11,7 +11,6 @@ using JetBrains.Annotations; using LiteDbExplorer.Windows; using LiteDbExplorer.Core; -using JsonSerializer = LiteDB.JsonSerializer; namespace LiteDbExplorer.Modules.Database { @@ -117,9 +116,9 @@ private void SetDatabaseInfo() var databaseInfo = new List { new DisplayInfo("Collections:", _databaseReference.Collections.Count), - new DisplayInfo("Encrypted:", engineInfoDocument["encrypted"].AsBoolean), - new DisplayInfo("Change ID:", engineInfoDocument["changeID"].RawValue), - new DisplayInfo("Last page ID:", engineInfoDocument["lastPageID"].RawValue) + //new DisplayInfo("Encrypted:", engineInfoDocument["encrypted"].AsBoolean), + //new DisplayInfo("Change ID:", engineInfoDocument["changeID"].RawValue), + //new DisplayInfo("Last page ID:", engineInfoDocument["lastPageID"].RawValue) }; DatabaseInfo = databaseInfo; @@ -137,7 +136,7 @@ private void SetDatabaseInfo() DatabaseFileInfo = databaseFileInfo; - MetadataJson = JsonSerializer.Serialize(engineInfoDocument, true, false); + MetadataJson = LiteDB.JsonSerializer.Serialize(engineInfoDocument); } } diff --git a/source/LiteDbExplorer/Modules/DatabaseInteractions.cs b/source/LiteDbExplorer/Modules/DatabaseInteractions.cs index e73bc68..166ae0a 100644 --- a/source/LiteDbExplorer/Modules/DatabaseInteractions.cs +++ b/source/LiteDbExplorer/Modules/DatabaseInteractions.cs @@ -84,7 +84,7 @@ public async Task CreateAndOpenDatabase() using (var stream = new FileStream(maybeFileName.Value, System.IO.FileMode.Create)) { - LiteEngine.CreateDatabase(stream); + new LiteDatabase(stream); } await OpenDatabase(maybeFileName.Value).ConfigureAwait(false); @@ -138,23 +138,23 @@ public async Task OpenDatabase(string path, string password = "") try { var rememberMe = false; - if (DatabaseReference.IsDbPasswordProtected(path)) - { - if (string.IsNullOrWhiteSpace(password) && _recentDatabaseFilesProvider.TryGetPassword(path, out var storedPassword)) - { - password = storedPassword; - rememberMe = true; - } - - var maybePasswordInput = await _applicationInteraction.ShowPasswordInputDialog("Database is password protected, enter password:", "Database password.", password, rememberMe); - if (maybePasswordInput.HasNoValue) - { - return; - } - - password = maybePasswordInput.Value.Password; - rememberMe = maybePasswordInput.Value.RememberMe; - } + //if (DatabaseReference.IsDbPasswordProtected(path)) + //{ + // if (string.IsNullOrWhiteSpace(password) && _recentDatabaseFilesProvider.TryGetPassword(path, out var storedPassword)) + // { + // password = storedPassword; + // rememberMe = true; + // } + + // var maybePasswordInput = await _applicationInteraction.ShowPasswordInputDialog("Database is password protected, enter password:", "Database password.", password, rememberMe); + // if (maybePasswordInput.HasNoValue) + // { + // return; + // } + + // password = maybePasswordInput.Value.Password; + // rememberMe = maybePasswordInput.Value.RememberMe; + //} var connectionOptions = new DatabaseConnectionOptions(path, password) { @@ -191,15 +191,19 @@ public async Task OpenDatabase(string path, string password = "") protected virtual async Task OpenDatabaseExceptionHandler(LiteException liteException, string path, string password = "") { - if (liteException.ErrorCode == LiteException.DATABASE_WRONG_PASSWORD) - { - if (!string.IsNullOrEmpty(password)) - { - _applicationInteraction.ShowAlert("Failed to open database [LiteException]:" + Environment.NewLine + liteException.Message, null, UINotificationType.Error); - } + //if (liteException.ErrorCode == LiteException.DATABASE_WRONG_PASSWORD) + //{ + // if (!string.IsNullOrEmpty(password)) + // { + // _applicationInteraction.ShowAlert("Failed to open database [LiteException]:" + Environment.NewLine + liteException.Message, null, UINotificationType.Error); + // } - await OpenDatabase(path, password).ConfigureAwait(false); - } + // await OpenDatabase(path, password).ConfigureAwait(false); + //} + //else + //{ + _applicationInteraction.ShowError(liteException.StackTrace, liteException.Message + ". Is this a version 5 file?"); + //} } public Task CloseDatabase(DatabaseReference database) @@ -213,7 +217,7 @@ public async Task ShrinkDatabase(DatabaseReference database) { await Task.Factory.StartNew(() => { - database.ShrinkDatabase(); + //database.ShrinkDatabase(); }); } @@ -221,7 +225,7 @@ public async Task ResetPassword(DatabaseReference database, string password) { await Task.Factory.StartNew(() => { - database.ShrinkDatabase(string.IsNullOrEmpty(password) ? null : password); + //database.ShrinkDatabase(string.IsNullOrEmpty(password) ? null : password); }); _recentDatabaseFilesProvider.ResetPassword(database.Location, password, true); @@ -524,7 +528,7 @@ public Task CopyDocuments(IEnumerable documents) { var documentAggregator = new DocumentReferenceAggregator(documents); - Clipboard.SetData(DataFormats.Text, documentAggregator.Serialize(true, false)); + Clipboard.SetData(DataFormats.Text, documentAggregator.Serialize()); return Task.FromResult(Result.Ok()); } @@ -618,7 +622,7 @@ private async Task> ExportToJson(ICollection do { using (var writer = new StreamWriter(maybeJsonFileName.Value)) { - documents.First().Serialize(writer, true); + documents.First().Serialize(writer); } } else @@ -626,7 +630,7 @@ private async Task> ExportToJson(ICollection do var documentAggregator = new DocumentReferenceAggregator(documents); using (var writer = new StreamWriter(maybeJsonFileName.Value)) { - documentAggregator.Serialize(writer, true, false); + documentAggregator.Serialize(writer); } } } @@ -890,7 +894,7 @@ private async Task> ExportToJson(IJsonSerializerProvider provider, { using (var writer = new StreamWriter(maybeFileName.Value)) { - provider.Serialize(writer, true); + provider.Serialize(writer); } } diff --git a/source/LiteDbExplorer/Modules/DbQuery/ShellCommandQueryViewHandler.cs b/source/LiteDbExplorer/Modules/DbQuery/ShellCommandQueryViewHandler.cs index a1bfb34..aab4ba8 100644 --- a/source/LiteDbExplorer/Modules/DbQuery/ShellCommandQueryViewHandler.cs +++ b/source/LiteDbExplorer/Modules/DbQuery/ShellCommandQueryViewHandler.cs @@ -41,14 +41,14 @@ public Task> RunQuery(DatabaseReference databaseReference, IQuery IList results; using (resultViewModel.StartTime()) { - results = databaseReference.RunCommand(rawQuery); + //results = databaseReference.RunCommand(rawQuery); } - resultViewModel.SetResult( - $"Result {resultCount}", - rawQuery, - new QueryResult(results, UserDefinedCultureFormat.Default)); + //resultViewModel.SetResult( + // $"Result {resultCount}", + // rawQuery, + // new QueryResult(results, UserDefinedCultureFormat.Default)); - result.Add(resultViewModel); + //result.Add(resultViewModel); } catch (Exception e) { From c6679c2acf0ee61ee45d6b99fd4dca944fb9aae1 Mon Sep 17 00:00:00 2001 From: dtaylor-530 Date: Thu, 21 May 2020 17:16:17 +0100 Subject: [PATCH 3/3] Fixed remaining issues updating code to LiteDB version 5. --- .../Store/DatabaseReference.cs | 69 +++++----- .../Database/DatabasePropertiesViewModel.cs | 7 +- .../Modules/DatabaseInteractions.cs | 124 +++++++++--------- .../DbQuery/ShellCommandQueryViewHandler.cs | 12 +- 4 files changed, 107 insertions(+), 105 deletions(-) diff --git a/source/LiteDbExplorer.Core/Store/DatabaseReference.cs b/source/LiteDbExplorer.Core/Store/DatabaseReference.cs index 4a180dc..a915c59 100644 --- a/source/LiteDbExplorer.Core/Store/DatabaseReference.cs +++ b/source/LiteDbExplorer.Core/Store/DatabaseReference.cs @@ -17,6 +17,12 @@ public sealed class DatabaseReference : ReferenceNode private ObservableCollection _collections; private bool _isDisposing; + public enum PasswordStatus + { + NotSet = 0, + Set = 1 + } + public DatabaseReference([NotNull] DatabaseConnectionOptions options) { if (options == null) @@ -51,7 +57,7 @@ public DatabaseReference([NotNull] DatabaseConnectionOptions options) public int UserVersion { get => LiteDatabase.UserVersion; - set => LiteDatabase.UserVersion = (ushort) value; + set => LiteDatabase.UserVersion = (ushort)value; } public ObservableCollection CollectionsLookup { get; private set; } @@ -157,22 +163,22 @@ public bool ContainsCollection(string name) return Collections.Any(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); } - //public long ShrinkDatabase() - //{ - // return LiteDatabase.Shrink(); - //} + public long RebuildDatabase() + { + return LiteDatabase.Rebuild(); + } - //public long ShrinkDatabase(string password) - //{ - // return LiteDatabase.Shrink(password); - //} + public long RebuildDatabase(string password) + { + return LiteDatabase.Rebuild(new LiteDB.Engine.RebuildOptions { Password = password }); + } - //public IList RunCommand(string command) - //{ - // return LiteDatabase.Engine.Run(command); - //} + public IList RunCommand(string command) + { + return LiteDatabase.Execute(command).ToList(); + } - public BsonValue InternalDatabaseInfo() + public BsonDocument InternalDatabaseInfo() { return LiteDatabase.Mapper.ToDocument(typeof(object), new { LiteDatabase.Timeout, LiteDatabase.UserVersion, LiteDatabase.UtcDate, LiteDatabase.LimitSize, LiteDatabase.CheckpointSize }); } @@ -188,26 +194,21 @@ public void BeforeDispose() BroadcastChanges(ReferenceNodeChangeAction.Dispose, this); } - //public static bool IsDbPasswordProtected(string path) - //{ - // using (var db = new LiteDatabase(path)) - // { - // try - // { - // db.GetCollectionNames(); - // return false; - // } - // catch (LiteException e) - // { - // if (e.ErrorCode == LiteException.DATABASE_WRONG_PASSWORD || e.Message.Contains("password")) - // { - // return true; - // } - - // throw; - // } - // } - //} + + /// + /// + /// + /// + /// + public static bool IsDbPasswordProtected(string path) + { + + using (FileStream fs = File.OpenRead(path)) + { + var ss= fs.ReadByte() ; + return ss != (byte)PasswordStatus.NotSet; + } + } protected override void Dispose(bool disposing) { diff --git a/source/LiteDbExplorer/Modules/Database/DatabasePropertiesViewModel.cs b/source/LiteDbExplorer/Modules/Database/DatabasePropertiesViewModel.cs index 76fd526..d6a5744 100644 --- a/source/LiteDbExplorer/Modules/Database/DatabasePropertiesViewModel.cs +++ b/source/LiteDbExplorer/Modules/Database/DatabasePropertiesViewModel.cs @@ -116,9 +116,10 @@ private void SetDatabaseInfo() var databaseInfo = new List { new DisplayInfo("Collections:", _databaseReference.Collections.Count), - //new DisplayInfo("Encrypted:", engineInfoDocument["encrypted"].AsBoolean), - //new DisplayInfo("Change ID:", engineInfoDocument["changeID"].RawValue), - //new DisplayInfo("Last page ID:", engineInfoDocument["lastPageID"].RawValue) + new DisplayInfo("TimeOut:", engineInfoDocument["TimeOut"].AsInt64), + new DisplayInfo("UtcDate:", engineInfoDocument["UtcDate"].RawValue), + new DisplayInfo("LimitSize:", engineInfoDocument["LimitSize"].AsInt64), + new DisplayInfo("CheckpointSize:", engineInfoDocument["CheckpointSize"].RawValue) }; DatabaseInfo = databaseInfo; diff --git a/source/LiteDbExplorer/Modules/DatabaseInteractions.cs b/source/LiteDbExplorer/Modules/DatabaseInteractions.cs index 166ae0a..1aad697 100644 --- a/source/LiteDbExplorer/Modules/DatabaseInteractions.cs +++ b/source/LiteDbExplorer/Modules/DatabaseInteractions.cs @@ -34,7 +34,7 @@ public interface IDatabaseInteractions Task> SaveDatabaseCopyAs(DatabaseReference database); Task> AddFileToDatabase(IScreen context, DatabaseReference database, string filePath = null); - + Task> CreateDocument(IScreen context, CollectionReference collection); Task RemoveDocuments(IEnumerable documents); Task CopyDocuments(IEnumerable documents); @@ -43,7 +43,7 @@ public interface IDatabaseInteractions Task> AddCollection(IScreen context, DatabaseReference database); Task RenameCollection(CollectionReference collection); Task> DropCollection(CollectionReference collection); - + Task> ExportAs(IScreen context, CollectionReference collectionReference, IList selectedDocuments = null); Task> ExportAs(IScreen context, QueryResult queryResult, string name = ""); @@ -60,7 +60,7 @@ public interface IDatabaseInteractions } [Export(typeof(IDatabaseInteractions))] - [PartCreationPolicy (CreationPolicy.Shared)] + [PartCreationPolicy(CreationPolicy.Shared)] public class DatabaseInteractions : IDatabaseInteractions { private static readonly ILogger Logger = Log.ForContext(); @@ -105,7 +105,7 @@ public async Task OpenDatabase() catch (Exception exc) { Logger.Error(exc, "Failed to open database: "); - _applicationInteraction.ShowError(exc,"Failed to open database: " + exc.Message); + _applicationInteraction.ShowError(exc, "Failed to open database: " + exc.Message); } } @@ -134,27 +134,27 @@ public async Task OpenDatabase(string path, string password = "") { _applicationInteraction.ShowAlert("Maintaining connection to network files is not guaranteed!", "Network file", UINotificationType.Info); } - + try { var rememberMe = false; - //if (DatabaseReference.IsDbPasswordProtected(path)) - //{ - // if (string.IsNullOrWhiteSpace(password) && _recentDatabaseFilesProvider.TryGetPassword(path, out var storedPassword)) - // { - // password = storedPassword; - // rememberMe = true; - // } - - // var maybePasswordInput = await _applicationInteraction.ShowPasswordInputDialog("Database is password protected, enter password:", "Database password.", password, rememberMe); - // if (maybePasswordInput.HasNoValue) - // { - // return; - // } - - // password = maybePasswordInput.Value.Password; - // rememberMe = maybePasswordInput.Value.RememberMe; - //} + if (DatabaseReference.IsDbPasswordProtected(path)) + { + if (string.IsNullOrWhiteSpace(password) && _recentDatabaseFilesProvider.TryGetPassword(path, out var storedPassword)) + { + password = storedPassword; + rememberMe = true; + } + + var maybePasswordInput = await _applicationInteraction.ShowPasswordInputDialog("Database is password protected, enter password:", "Database password.", password, rememberMe); + if (maybePasswordInput.HasNoValue) + { + return; + } + + password = maybePasswordInput.Value.Password; + rememberMe = maybePasswordInput.Value.RememberMe; + } var connectionOptions = new DatabaseConnectionOptions(path, password) { @@ -171,7 +171,7 @@ public async Task OpenDatabase(string path, string password = "") } else { - _recentDatabaseFilesProvider.InsertRecentFile(databaseReference.DatabaseVersion, path); + _recentDatabaseFilesProvider.InsertRecentFile(databaseReference.DatabaseVersion, path); } } catch (LiteException liteException) @@ -180,32 +180,32 @@ public async Task OpenDatabase(string path, string password = "") } catch (NotSupportedException notSupportedException) { - _applicationInteraction.ShowError(notSupportedException,"Failed to open database [NotSupportedException]:" + Environment.NewLine + notSupportedException.Message); + _applicationInteraction.ShowError(notSupportedException, "Failed to open database [NotSupportedException]:" + Environment.NewLine + notSupportedException.Message); } catch (Exception e) { Logger.Error(e, "Failed to open database: "); - _applicationInteraction.ShowError(e,"Failed to open database [Exception]:" + Environment.NewLine + e.Message); + _applicationInteraction.ShowError(e, "Failed to open database [Exception]:" + Environment.NewLine + e.Message); } } protected virtual async Task OpenDatabaseExceptionHandler(LiteException liteException, string path, string password = "") { - //if (liteException.ErrorCode == LiteException.DATABASE_WRONG_PASSWORD) - //{ - // if (!string.IsNullOrEmpty(password)) - // { - // _applicationInteraction.ShowAlert("Failed to open database [LiteException]:" + Environment.NewLine + liteException.Message, null, UINotificationType.Error); - // } - - // await OpenDatabase(path, password).ConfigureAwait(false); - //} - //else - //{ - _applicationInteraction.ShowError(liteException.StackTrace, liteException.Message + ". Is this a version 5 file?"); - //} + _applicationInteraction.ShowError(liteException.StackTrace, liteException.Message + ". Is this a version 5 file?"); + if (liteException.Message == "Invalid password") + { + if (!string.IsNullOrEmpty(password)) + { + _applicationInteraction.ShowAlert("Failed to open database [LiteException]:" + Environment.NewLine + liteException.Message, null, UINotificationType.Error); + } + await OpenDatabase(path, password).ConfigureAwait(false); + } + else + { + _applicationInteraction.ShowError(liteException.StackTrace, liteException.Message + ". Is this possibly a version 5 file?"); + } } - + public Task CloseDatabase(DatabaseReference database) { Store.Current.CloseDatabase(database); @@ -217,7 +217,7 @@ public async Task ShrinkDatabase(DatabaseReference database) { await Task.Factory.StartNew(() => { - //database.ShrinkDatabase(); + database.RebuildDatabase(); }); } @@ -225,7 +225,7 @@ public async Task ResetPassword(DatabaseReference database, string password) { await Task.Factory.StartNew(() => { - //database.ShrinkDatabase(string.IsNullOrEmpty(password) ? null : password); + database.RebuildDatabase(string.IsNullOrEmpty(password) ? null : password); }); _recentDatabaseFilesProvider.ResetPassword(database.Location, password, true); @@ -281,7 +281,7 @@ public async Task> AddFileToDatabase(I if (!string.IsNullOrEmpty(fileId)) { var file = database.AddFile(fileId, maybeFileName.Value); - var documentsCreated = new CollectionDocumentChangeEventArgs(ReferenceNodeChangeAction.Add, new [] {file}, file.Collection); + var documentsCreated = new CollectionDocumentChangeEventArgs(ReferenceNodeChangeAction.Add, new[] { file }, file.Collection); return Result.Ok(documentsCreated); } } @@ -305,7 +305,7 @@ public Task RemoveDocuments(IEnumerable documents) { document.RemoveSelf(); } - + return Task.FromResult(Result.Ok()); } @@ -406,8 +406,8 @@ public Task> DropCollection(CollectionReference coll } public async Task> ExportAs( - IScreen context, - CollectionReference collectionReference, + IScreen context, + CollectionReference collectionReference, IList selectedDocuments = null) { if (collectionReference == null) @@ -470,7 +470,7 @@ public async Task> ExportAs( public async Task> ExportAs( - IScreen context, + IScreen context, QueryResult queryResult, string name = "") { @@ -527,18 +527,18 @@ public async Task> ExportAs( public Task CopyDocuments(IEnumerable documents) { var documentAggregator = new DocumentReferenceAggregator(documents); - + Clipboard.SetData(DataFormats.Text, documentAggregator.Serialize()); return Task.FromResult(Result.Ok()); } - + public Task> OpenEditDocument(DocumentReference document) { var result = _applicationInteraction.OpenEditDocument(document); - return Task.FromResult(Maybe.From(result ? document: null)); + return Task.FromResult(Maybe.From(result ? document : null)); } - + public Task> ImportDataFromText(CollectionReference collection, string textData) { try @@ -579,7 +579,7 @@ public Task> ImportDataFromText(Collec return Task.FromResult(Result.Failure(message)); } } - + public async Task> CreateDocument(IScreen context, CollectionReference collection) { if (collection is FileCollectionReference) @@ -603,7 +603,7 @@ public async Task> CreateDocument(IScr }; var documentReference = collection.AddDocument(newDoc); - + var documentsCreated = new CollectionDocumentChangeEventArgs(ReferenceNodeChangeAction.Add, documentReference, collection) { PostAction = (optionsResult.Model.EditAfterCreate || optionsResult.Action is AddDocumentOptions.ACTION_OK_AND_EDIT) ? "edit" : null @@ -682,7 +682,7 @@ private async Task> ExportToExcel(ICollection d } else { - cellValue = bsonValue.RawValue; + cellValue = bsonValue.RawValue; } var cell = ws.Cells[currentRow, currentColl]; @@ -692,20 +692,20 @@ private async Task> ExportToExcel(ICollection d cell.Style.Numberformat.Format = format(bsonValue); } } - + currentColl++; } currentColl = 1; currentRow++; } - + var tableRange = ws.Cells[1, 1, documents.Count + 1, keys.Length]; var resultsTable = ws.Tables.Add(tableRange, $"{Regex.Replace(name, @"\s", "_")}_table"); resultsTable.ShowFilter = true; resultsTable.ShowHeader = true; - + // AutoFit ws.Cells[ws.Dimension.Address].AutoFitColumns(); @@ -728,12 +728,12 @@ private async Task> ExportToExcel(DataTable dataTable, string name var ws = excelPackage.Workbook.Worksheets.Add(name); ws.Cells[@"A1"].LoadFromDataTable(dataTable, true); - + var resultsTable = ws.Tables.Add(ws.Dimension, $"{Regex.Replace(name, @"\s", "_")}_table"); resultsTable.ShowFilter = true; resultsTable.ShowHeader = true; - + // AutoFit ws.Cells[ws.Dimension.Address].AutoFitColumns(); @@ -824,7 +824,7 @@ string NormalizeValue(object field) var value = Convert.ToString(field, CultureInfo.InvariantCulture); if (value != null && value.IndexOfAny(reservedTokens) >= 0) { - value = "\"" + value.Replace("\"", "\"\"") + "\""; + value = "\"" + value.Replace("\"", "\"\"") + "\""; } return value; } @@ -870,12 +870,12 @@ private async Task> ExportStoredFiles(ICollection> RunQuery(DatabaseReference databaseReference, IQuery IList results; using (resultViewModel.StartTime()) { - //results = databaseReference.RunCommand(rawQuery); + results = databaseReference.RunCommand(rawQuery); } - //resultViewModel.SetResult( - // $"Result {resultCount}", - // rawQuery, - // new QueryResult(results, UserDefinedCultureFormat.Default)); + resultViewModel.SetResult( + $"Result {resultCount}", + rawQuery, + new QueryResult(results, UserDefinedCultureFormat.Default)); - //result.Add(resultViewModel); + result.Add(resultViewModel); } catch (Exception e) {