This commit is contained in:
2026-04-17 14:55:32 -04:00
commit bc3ac1d4c9
18017 changed files with 4371742 additions and 0 deletions

View File

@@ -0,0 +1,85 @@
---
source_files:
- DataPRO/Modules/Database/DatabaseServices/Converters/DbTypeToVisibilityConverter.cs
generated_at: "2026-04-16T04:35:48.144608+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "b05fe9322ad19457"
---
# Converters
### **DbTypeToVisibilityConverter.cs Documentation**
---
#### **1. Purpose**
This module provides a WPF `IMultiValueConverter` implementation (`DbTypeToVisibilityConverter`) used to dynamically control the visibility of UI elements (e.g., menu items, buttons, or status bar controls) in the `DatabaseStatusBarView`, based on the current database configuration and connection state. It translates the combination of a `DbType` value and the current view context into a `Visibility` enum (`Visible` or `Collapsed`), enabling UI elements to be conditionally shown only when relevant to the active database mode (e.g., remote-only, local-only, or hybrid with/without remote connection).
---
#### **2. Public Interface**
- **`DbTypeToVisibilityConverter`**
- *Implements*: `System.Windows.Data.IMultiValueConverter`
- *Namespace*: `DatabaseServices.Converters`
- *Inherits*: `object`
- **`object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)`**
- **Signature**: `public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)`
- **Behavior**: Converts a two-element input array (`values`) into a `Visibility` value:
- `values[0]`: An `int` representing a `DbType` enum value (cast to `DbType`).
- `values[1]`: A `DatabaseStatusBarView` instance (used to access its `DataContext`, expected to be a `DatabaseStatusBarViewModel`).
- Returns `Visibility.Visible` if the `dbType` matches the visibility rules for the current `vm.DatabaseType` and `vm.RemoteConnected` state; otherwise returns `Visibility.Collapsed`.
- If `view.DataContext` is `null`, returns `Visibility.Collapsed`.
- Throws no exceptions explicitly, but may throw `InvalidCastException` if inputs are not of expected types.
- **`object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)`**
- **Signature**: `public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)`
- **Behavior**: Always throws `NotImplementedException`. This converter is one-way only.
---
#### **3. Invariants**
- `values` array **must** contain exactly two elements:
- Element 0: An `int` that can be safely cast to `DbType`.
- Element 1: A `DatabaseStatusBarView` instance (non-null).
- `view.DataContext` **must** be non-null and assignable to `DatabaseStatusBarViewModel`; otherwise, the converter returns `Visibility.Collapsed`.
- Visibility logic is strictly governed by the `DatabaseStatusBarViewModel.DatabaseType` and `DatabaseStatusBarViewModel.RemoteConnected` properties:
- For `RemoteOnly`: Only `DbType.RemoteOnly` is visible.
- For `LocalOnly`: Only `DbType.LocalOnly` is visible.
- For `RemoteLocalHybrid`:
- If `RemoteConnected == true`: Only `DbType.RemoteOnly` is visible.
- If `RemoteConnected == false`: Only `DbType.RemoteLocalHybrid` is visible.
- Any other `DatabaseType` value results in `Visibility.Collapsed`.
- The converter is **not** intended for two-way binding (`ConvertBack` is unimplemented).
---
#### **4. Dependencies**
- **Imports/References**:
- `System`, `System.Globalization`, `System.Windows`, `System.Windows.Data` (WPF core)
- `DTS.Common.Enums.Database` (external library/namespace) — provides `DbType` and likely `DatabaseStatusBarView`/`DatabaseStatusBarViewModel`.
- **Assumed Dependencies (from usage context)**:
- `DatabaseStatusBarView`: A WPF `UserControl` or `Window` used in the status bar.
- `DatabaseStatusBarViewModel`: View model with properties:
- `DatabaseType` (`DbType`)
- `RemoteConnected` (`bool`)
- `DbType` enum (from `DTS.Common.Enums.Database`) — expected to include at least: `RemoteOnly`, `LocalOnly`, `RemoteLocalHybrid`.
- **Depended upon by**:
- XAML bindings in `DatabaseStatusBarView` (or related views) where `MultiBinding` is used with this converter to toggle visibility based on database type and connection state.
---
#### **5. Gotchas**
- **Type safety**: Assumes `values[0]` is an `int` that maps to a valid `DbType` enum value. Passing a non-integer or out-of-range value may cause `InvalidCastException` at runtime.
- **Null safety**: Relies on `view.DataContext` being non-null; otherwise, silently returns `Collapsed`. No logging or error handling is present.
- **Hybrid mode logic is conditional**: In `RemoteLocalHybrid` mode, visibility depends on `RemoteConnected`, but the converter does **not** handle cases where `RemoteConnected` is `false` and `dbType == DbType.RemoteOnly` — such cases correctly collapse, but this may be counterintuitive if the UI expects hybrid elements to always show.
- **No support for `parameter`**: The `parameter` argument (often used to customize converter behavior in XAML) is ignored.
- **One-way only**: `ConvertBack` throws `NotImplementedException`, so this converter cannot be used in two-way bindings.
- **No validation of `DbType` values**: Unknown `DbType` values (e.g., future enum additions) fall through to `default: return Visibility.Collapsed`, which may hide UI elements unexpectedly.
None identified beyond these.

View File

@@ -0,0 +1,62 @@
---
source_files:
- DataPRO/Modules/Database/DatabaseServices/Properties/Settings.Designer.cs
- DataPRO/Modules/Database/DatabaseServices/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T04:35:58.384112+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "a47b7825dcdbbbb0"
---
# Properties
## Documentation Page: `DatabaseServices.Properties.Settings`
---
### 1. **Purpose**
This module defines the auto-generated settings class `Settings` for the `DatabaseServices` assembly. It provides a strongly-typed, thread-safe accessor (`Default`) to application-level configuration settings stored in the standard .NET configuration system (e.g., `app.config` or `web.config`). Its role is to abstract access to persisted settings values, enabling type-safe retrieval without manual parsing or casting. It does *not* define any settings itself—only the infrastructure to access them—meaning actual settings keys and values must be defined elsewhere (e.g., via Visual Studios Settings designer or `app.config`).
---
### 2. **Public Interface**
The module exposes a single internal, auto-generated class:
- **`class Settings : ApplicationSettingsBase`**
- **`public static Settings Default { get; }`**
Returns the singleton instance of `Settings`, synchronized for thread safety via `ApplicationSettingsBase.Synchronized`. This is the *only* public member exposed.
> ⚠️ **Note**: The class is `internal`, so `Default` is only accessible within the `DatabaseServices` assembly. External consumers cannot directly reference this class.
---
### 3. **Invariants**
- The `Default` property always returns a non-null reference (initialized lazily and synchronized).
- The class is `sealed` and `partial`, indicating it is not designed for inheritance or manual extension.
- Thread-safety is guaranteed *only for the `Default` accessor* (via `Synchronized`), but not necessarily for individual property accesses on the returned instance (e.g., `Settings.Default.MySetting` is not inherently thread-safe beyond the initial retrieval of `Default`).
- Settings values themselves are not validated or constrained by this class—validation (if any) occurs at the configuration layer or in consuming code.
---
### 4. **Dependencies**
- **Depends on**:
- `System.Configuration` (specifically `ApplicationSettingsBase`, `CompilerGeneratedAttribute`, `GeneratedCodeAttribute`).
- `System.Runtime.CompilerServices` (for `CompilerGeneratedAttribute`).
- **Depended upon by**:
- Other classes in the `DatabaseServices` assembly (e.g., data access layers) that require configuration values (e.g., connection strings, timeouts).
- *Not* exposed to external assemblies due to `internal` visibility.
- **Assembly metadata** (from `AssemblyInfo.cs`):
- Assembly name: `DatabaseServices`
- GUID: `f1a366bc-6128-4c10-be7f-f62628895d8f`
- Version: `1.0.0.0`
- `ComVisible(false)` → not exposed to COM.
---
### 5. **Gotchas**
- **No settings defined here**: This file *only* scaffolds the settings infrastructure. Actual settings (e.g., `ConnectionString`, `CommandTimeout`) must be defined in `Settings.settings` (designer) or `app.config`. If these are missing, accessing `Settings.Default` will succeed, but property access (e.g., `Settings.Default.MyProp`) will throw a `ConfigurationErrorsException` at runtime.
- **Auto-generated**: Manual edits will be overwritten on rebuild (per the `auto-generated` header).
- **Internal visibility**: External consumers cannot use `Settings.Default` directly. They must rely on `DatabaseServices` to expose settings via its public API (e.g., a wrapper method).
- **Thread-safety nuance**: While `Default` is thread-safe, *reading/writing settings values* from multiple threads may require additional synchronization if mutable settings are used (though `ApplicationSettingsBase` typically treats settings as read-only after initialization).
- **No documentation comments**: The class lacks XML documentation, making it harder to infer intended usage without external context.
None identified beyond these.

View File

@@ -0,0 +1,52 @@
---
source_files:
- DataPRO/Modules/Database/DatabaseServices/Resources/TranslateExtension.cs
- DataPRO/Modules/Database/DatabaseServices/Resources/StringResources.Designer.cs
generated_at: "2026-04-16T04:35:33.501804+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "79b93425a9c97e71"
---
# Resources
## Documentation: `TranslateExtension` Markup Extension
### 1. Purpose
The `TranslateExtension` class is a WPF `MarkupExtension` that enables declarative localization of UI text directly in XAML. It resolves string resources by key at runtime using the `StringResources` strongly-typed resource class, returning localized strings or a standardized fallback for missing keys. This module exists to support multi-language UIs in the DatabaseServices module by abstracting resource lookup into a XAML-friendly syntax (e.g., `{local:Translate KeyName}`), decoupling UI text from code and enabling runtime culture switching.
### 2. Public Interface
- **`TranslateExtension(string key)`**
Constructor. Accepts a resource key (e.g., `"ClearingLocalDb"`) to look up. Throws no exceptions on invalid input—invalid keys are handled at lookup time.
- **`override object ProvideValue(IServiceProvider serviceProvider)`**
WPF framework method invoked during XAML parsing. Returns the localized string corresponding to `_key`, or a fallback value if the key is missing/empty.
- If `_key` is `null` or empty: returns `"#stringnotfound#"`.
- If `StringResources.ResourceManager.GetString(_key)` returns `null`: returns `"#stringnotfound# " + _key`.
- Otherwise: returns the localized string.
### 3. Invariants
- `_key` is immutable after construction (stored in a `readonly` field).
- The returned value is always a `string` (per `[MarkupExtensionReturnType(typeof(string))]`).
- No exceptions are thrown during `ProvideValue`—all error cases return a fallback string.
- Resource lookup uses the current UI culture (via `StringResources.Culture`), which may be set externally (e.g., by WPFs `FrameworkElement.Language` or manual assignment).
- The `StringResources` class is auto-generated and must be kept in sync with `.resx` files; changes to `.resx` require regeneration.
### 4. Dependencies
- **Depends on**:
- `System.Windows.Markup` (for `MarkupExtension` and `MarkupExtensionReturnType`).
- `DatabaseServices.Resources.StringResources` (strongly-typed resource class).
- `System.Resources.ResourceManager` (via `StringResources.ResourceManager`).
- **Used by**:
- XAML files in the `DatabaseServices` module (e.g., `Window.xaml`, `UserControl.xaml`) to bind localized text to UI elements.
- No direct programmatic callers in the provided source—usage is exclusively via XAML markup.
### 5. Gotchas
- **Hardcoded fallback prefix**: The `"#stringnotfound#"` string is hardcoded; changing it requires updating both `TranslateExtension` and any tests/scripts expecting this pattern.
- **No caching of lookups**: `ResourceManager.GetString(_key)` is called on every `ProvideValue` invocation. While `ResourceManager` caches internally, repeated lookups for the same key in high-frequency UI scenarios (e.g., data-bound lists) may incur overhead.
- **Silent failure on missing keys**: Missing keys produce visible text like `"#stringnotfound# ClearingLocalDb"` in the UI, which may confuse end users. No logging or telemetry is performed.
- **No null-safety for `serviceProvider`**: The `serviceProvider` parameter is unused, but if future changes require it (e.g., for service resolution), this could break.
- **Auto-generated resource class**: `StringResources.Designer.cs` is auto-generated—manual edits are unsafe and will be overwritten. Resource keys must match exactly (case-sensitive) with entries in the `.resx` file.
- **No support for pluralization/formatting**: The extension only supports simple key→string lookups; composite strings (e.g., `"Connected to: {0}"`) require manual formatting in code-behind or XAML.
None identified beyond these.

View File

@@ -0,0 +1,52 @@
---
source_files:
- DataPRO/Modules/Database/DatabaseServices/View/DatabaseStatusBarView.xaml.cs
- DataPRO/Modules/Database/DatabaseServices/View/DatabaseCopyView.xaml.cs
- DataPRO/Modules/Database/DatabaseServices/View/DatabaseSwitchView.xaml.cs
generated_at: "2026-04-16T04:36:08.419533+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "0a8da82e58412ddf"
---
# View
## Documentation: Database UI Views Module
### 1. Purpose
This module contains WPF view classes that implement the user interface layer for database-related operations—specifically, displaying status information, copying databases, and switching between local and remote database contexts. It serves as the presentation layer for database service functionality, adhering to the MVVM pattern by delegating business logic to corresponding view models (`IDatabaseCopyViewModel`, `IDatabaseSwitchViewModel`, `IDatabaseStatusBarView`). The views are thin wrappers that wire UI events (e.g., button clicks) to view model methods, and they rely on WPFs data binding and command infrastructure.
### 2. Public Interface
| Type | Signature | Behavior |
|------|-----------|----------|
| `DatabaseStatusBarView` | `public partial class DatabaseStatusBarView : IDatabaseStatusBarView` | WPF `UserControl` (inferred from `InitializeComponent()`) implementing `IDatabaseStatusBarView`. Provides UI for displaying database status (e.g., connection state, server info). No additional logic beyond initialization. |
| `DatabaseCopyView` | `public partial class DatabaseCopyView : IDatabaseCopyView` | WPF `UserControl` implementing `IDatabaseCopyView`. Contains a copy operation button. On click, casts `DataContext` to `IDatabaseCopyViewModel` and invokes `CopyDatabase()`. |
| `DatabaseSwitchView` | `public partial class DatabaseSwitchView : IDatabaseSwitchView` | WPF `UserControl` implementing `IDatabaseSwitchView`. Contains two buttons: `SwitchToLocal` and `SwitchToRemote`. On click, casts `DataContext` to `IDatabaseSwitchViewModel` and invokes `SwitchLocal()` or `SwitchRemote()` respectively. |
> **Note**: All classes are `partial`, indicating they are tied to corresponding `.xaml` files (e.g., `DatabaseStatusBarView.xaml`). Constructor calls `InitializeComponent()` to load XAML and wire UI elements.
### 3. Invariants
- **View-ViewModel Contract**: Each view expects its `DataContext` to be an instance of the corresponding view model interface (`IDatabaseStatusBarView` has no explicit contract beyond inheritance; `DatabaseCopyView` and `DatabaseSwitchView` require `IDatabaseCopyViewModel` and `IDatabaseSwitchViewModel` respectively).
- **UI Thread Execution**: Event handlers (`Copy_Click`, `SwitchToLocal_Click`, `SwitchToRemote_Click`) assume execution on the UI thread (standard for WPF event handlers), and view model methods (`CopyDatabase`, `SwitchLocal`, `SwitchRemote`) are invoked synchronously on this thread.
- **Null Safety**: No null checks are present in handlers; assumes `sender` is always a `Control` and `DataContext` is always the expected view model type. Failure to satisfy this will cause runtime exceptions (e.g., `InvalidCastException`, `NullReferenceException`).
### 4. Dependencies
- **External Interfaces**:
- `DTS.Common.Interface.Database.IDatabaseStatusBarView`
- `DTS.Common.Interface.Database.IDatabaseCopyView`
- `DTS.Common.Interface.Database.IDatabaseSwitchView`
- `DTS.Common.Interface.Database.IDatabaseCopyViewModel` (used in `DatabaseCopyView`)
- `DTS.Common.Interface.Database.IDatabaseSwitchViewModel` (used in `DatabaseSwitchView`)
- **WPF Framework**: `System.Windows`, `System.Windows.Controls`, `System.Windows.RoutedEventArgs`.
- **Dependents**: Likely consumed by a module or shell that registers these views with a DI container or view locator (e.g., Caliburn.Micro, Prism), though this is not explicit in the source.
- **No internal dependencies**: No references to other modules beyond the `DTS.Common.Interface.Database` interface layer.
### 5. Gotchas
- **No Error Handling**: Event handlers perform direct casts without validation. If `DataContext` is misconfigured (e.g., wrong view model type or `null`), a runtime exception will occur.
- **Tight Coupling to View Models**: Views assume specific method names (`CopyDatabase`, `SwitchLocal`, `SwitchRemote`) exist on the view model interface. Changes to these interfaces require synchronized updates.
- **No Command Binding**: Uses event handlers instead of `ICommand` bindings (e.g., `Button.Command`), which is less idiomatic in MVVM and reduces testability (e.g., cannot easily unit test button logic without UI interaction).
- **Namespace Quirk**: `// ReSharper disable CheckNamespace` suggests the namespace is intentionally `DatabaseServices` (not nested under `DataPRO.Modules.Database...`), possibly for legacy or build-system reasons.
- **Missing Implementation Details**: Source provides no insight into what `IDatabaseStatusBarView` actually exposes (e.g., properties, events), as the interface is only inherited—not implemented or used directly in logic.
None identified beyond the above.

View File

@@ -0,0 +1,206 @@
---
source_files:
- DataPRO/Modules/Database/DatabaseServices/ViewModel/DatabaseStatusBarViewModel.cs
- DataPRO/Modules/Database/DatabaseServices/ViewModel/DatabaseSwitchViewModel.cs
- DataPRO/Modules/Database/DatabaseServices/ViewModel/DatabaseCopyViewModel.cs
generated_at: "2026-04-16T04:35:56.029845+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "f187d4b018ffae25"
---
# Database Services ViewModels Documentation
## 1. Purpose
This module provides UI-facing view models (`DatabaseStatusBarViewModel`, `DatabaseSwitchViewModel`, and `DatabaseCopyViewModel`) that manage database connection state, user interaction for database switching/copying, and status reporting in the DataPRO application. These view models coordinate database operations (local vs. remote), handle UI state (busy indicators, progress bars, notifications), and integrate with Prisms event aggregation and Unity DI container for decoupled communication with other system components. They serve as the bridge between low-level database operations (e.g., `DbOperations`, `DatabaseServices`) and the WPF UI layer.
---
## 2. Public Interface
### `DatabaseStatusBarViewModel`
- **`string ActiveDbName { get; }`**
Returns a string representing the active database: `"Local"` for `DbType.LocalOnly`, `ServerName` for `DbType.RemoteOnly`, or `ServerName`/`"Local"` conditionally for `DbType.RemoteLocalHybrid`.
- **`Brush BackgroundBrush { get; }`**
Returns `Brushes.Red` when `DatabaseType == DbType.RemoteLocalHybrid` and `RemoteConnected == false`; otherwise `Brushes.Transparent`.
- **`bool RemoteConnected { get; }`**
Returns the value of `DbOperations._usingCentralizedDB`.
- **`string ServerName { get; private set; }`**
Holds the remote server name; updated via `InitializeValues` or `OnDbEvent`.
- **`void InitializeValues(DbType dbType, string serverName, bool remoteConnected)`**
Sets `DatabaseType`, `ServerName`, and triggers property change notifications for `ActiveDbName` and `BackgroundBrush`.
- **`void OnDbEvent(DbStatusArg args)`**
Internal event handler for `DbStatusEvent`; updates `ServerName` and notifies changes to `ActiveDbName`/`BackgroundBrush` when `args.Status == LegacyStatus`.
- **`bool IsBusy { get; set; }`**
Binds to UI busy indicator; updated via `OnBusyIndicatorNotification`.
- **`bool IsMenuIncluded`, `bool IsNavigationIncluded`**
UI state flags for menu/navigation visibility; support INotifyPropertyChanged.
- **`InteractionRequest<Notification> NotificationRequest { get; }`**
Prism interaction request used to show notification popups.
- **`InteractionRequest<Confirmation> ConfirmationRequest { get; }`**
Prism interaction request used to show confirmation dialogs.
- **`IDatabaseStatusBarView View { get; set; }`**
Reference to the associated view; `View.DataContext` is set to `this` in constructor.
- **Constructors**
- `DatabaseStatusBarViewModel(IDatabaseStatusBarView view, IRegionManager regionManager, IEventAggregator eventAggregator, IUnityContainer unityContainer)`
Registers event subscriptions for `RaiseNotification`, `BusyIndicatorChangeNotification`, and `DbStatusEvent`.
- `DatabaseStatusBarViewModel()`
Parameterless constructor (used for design-time or manual instantiation).
- **Lifecycle methods (no-op)**
`Unset()`, `Cleanup()`, `CleanupAsync()`, `Initialize()`, `Initialize(object)`, `Initialize(object, object)`, `InitializeAsync()`, `InitializeAsync(object)`, `Activated()` — all currently empty.
### `DatabaseSwitchViewModel`
- **`bool RemoteIsActive { get; }`**
Returns `DbOperations._usingCentralizedDB`.
- **`void SwitchRemote()`**
Attempts to switch to remote database:
1. Publishes `AppStatusArg.Busy`.
2. Calls `DatabaseServices.SetupForRemoteDb(...)` with stored credentials.
3. Validates connection via `SimpleDbTest()`.
4. On failure: publishes `DbStatusEvent` with `FailedToConnectToRemote`, calls `SwitchLocal()`, logs exception.
5. On success: publishes `DbStatusEvent.LegacyStatus`, `AppStatusArg.Available`, and `LogoutUserEvent` (reason: `DatabaseSwitch`).
- **`void SwitchLocal()`**
Switches to local database:
1. Checks local DB files exist via `CheckLocalDatabaseFilesExist(...)`.
2. Publishes `AppStatusArg.Busy`.
3. Calls `DatabaseServices.SetupLocal(...)`.
4. Publishes `DbStatusEvent.LegacyStatus`, `AppStatusArg.Available`, and `LogoutUserEvent`.
- **`void InitializeDbSettings(string defaultDbName, string dbHost, bool ntlmAuthentication, string dbUser, string dbPassword)`**
Stores connection settings for later use in `SwitchRemote()`.
- **Properties**: `DefaultDbName`, `DbHost`, `NTLMAuthentication`, `DbUser`, `DbPassword` (all `private set`).
- **`bool IsBusy`, `IsMenuIncluded`, `IsNavigationIncluded`**
Same semantics as `DatabaseStatusBarViewModel`.
- **Constructors & Lifecycle methods**
Same as `DatabaseStatusBarViewModel`; constructor subscribes to `RaiseNotification` and `BusyIndicatorChangeNotification`.
### `DatabaseCopyViewModel`
- **`bool CopyEnabled { get; }`**
Returns `true` only if `DatabaseType == DbType.RemoteLocalHybrid` and `DbOperations._usingCentralizedDB == true`.
- **`void CopyDatabase()`**
Triggers `CopyFunc()` on a background task (`Task.Run`). Publishes `AppStatusArg.Busy` before and `AppStatusArg.Available` after.
- **`void InitializeState(DbType dbType, string dbName)`**
Sets `DatabaseType` and `DbName`, publishes initial `ProgressBarEvent` for both progress bars (collapsed), and notifies `CopyEnabled`.
- **`string DbName { get; private set; }`**
Name of the database being copied.
- **`bool IsCopyVisible { get; set; }`**
Controls visibility of the copy UI section.
- **`IStatusAndProgressBarView OverallProgressBarView`, `IStatusAndProgressBarView CurrentTaskProgressBarView`**
References to progress bar views resolved during `InitializeAsync()`.
- **`Task InitializeAsync()`**
Resolves and configures two `IStatusAndProgressBarView` instances:
- One for `OverallTaskBar` (named `"OverallStatus"`).
- One for `CurrentTaskBar` (named `"CurrentTaskStatus"`).
Each is bound to a shared `IStatusAndProgressBarViewModel` instance.
- **`void OnRaiseNotification(NotificationContentEventArgs)`**
Wraps event args into `Notification` and raises `NotificationRequest`.
- **`void OnBusyIndicatorNotification(bool)`**
Sets `IsBusy`.
- **`bool IsBusy`, `IsMenuIncluded`, `IsNavigationIncluded`, `IsDirty`**
Same semantics as above.
- **Internal helper methods (private)**
- `CopyFunc()`: Main copy logic:
1. Backs up local DB.
2. Disables constraints.
3. Copies all tables in `_allDBTables` via `CopyRemoteTable(...)`.
4. Fixes `Channels.DASId = 0 → NULL`.
5. Re-enables constraints.
6. Restores local DB on failure.
7. Publishes progress via `ProgressBarEvent`.
- `CopyRemoteTable(string tableName, bool bIndentityTable)`: Fetches all rows from remote DB, stores in memory.
- `InsertIntoLocalTable(...)`: Inserts rows in batches (max 20 rows/batch to avoid SQL parameter limit), handles `IDENTITY_INSERT` for tables in `_tablesWithIdentities`.
- `SetStatus(string bar, double percentage, string text)`: Publishes `ProgressBarEvent`.
- **Constants & Data**
- `MAX_BATCH_SIZE = 20`
- `_allDBTables`: List of 72 table names (includes duplicates like `"tblDataPRODbVersion"` and `"DataPRODbVersion"`).
- `_tablesWithIdentities`: HashSet of 58 table names requiring `IDENTITY_INSERT ON/OFF`.
---
## 3. Invariants
- **`RemoteConnected` is derived solely from `DbOperations._usingCentralizedDB`** — no local state overrides it.
- **`ActiveDbName` and `BackgroundBrush` depend on `DatabaseType` and `RemoteConnected`** — their values are recalculated only when `DatabaseType` or `ServerName` changes (via `InitializeValues` or `OnDbEvent`).
- **Progress bars are always reset to collapsed/zero on completion/failure** — `CopyFunc()` publishes `ProgressBarEvent` with `Visibility.Collapsed` in `finally`.
- **`CopyDatabase()` runs asynchronously** — `Task.Run` is used explicitly; no `async/await` is used internally.
- **`DatabaseCopyViewModel` requires `InitializeAsync()` to be called before `CopyDatabase()`** — otherwise `OverallProgressBarView`/`CurrentTaskProgressBarView` remain `null`.
- **`DatabaseSwitchViewModel.SwitchRemote()` and `SwitchLocal()` always trigger `LogoutUserEvent`** — user session is invalidated after any database switch.
- **`DatabaseStatusBarViewModel.OnDbEvent(...)` only handles `LegacyStatus`** — other `DbStatusArg.EventTypes` are ignored.
---
## 4. Dependencies
### Internal Dependencies (from source):
- **`DTS.Common.*`**:
- `DTS.Common.Enums.Database.DbType`
- `DTS.Common.Events.*` (`RaiseNotification`, `BusyIndicatorChangeNotification`, `DbStatusEvent`, `AppStatusEvent`, `PageErrorEvent`, `LogoutUserEvent`)
- `DTS.Common.Storage.DatabaseServices` (`SetupForRemoteDb`, `SimpleDbTest`, `SetupLocal`, `BackupLocalDatabase`, `RestoreLocalDatabase`, `LOCAL_DB_FOLDER`)
- `DTS.Common.Storage.DatabaseServices` (via `DbOperations`, `LocalOnlyOperations`)
- `DTS.Common.Interface.Database.*` (e.g., `IDatabaseStatusBarView`, `IDatabaseCopyViewModel`)
- `DTS.Common.Interface.*` (e.g., `IStatusAndProgressBarView`)
- `DTS.Common.Utilities.Logging.APILogger`
- `DTS.Common.Interactivity.*` (`InteractionRequest`, `Notification`, `Confirmation`)
- **Prism Framework**:
- `Prism.Events.IEventAggregator`, `Prism.Regions.IRegionManager`
- `Prism.Commands`, `Prism.Interactivity.InteractionRequest`
- **Unity DI Container** (`IUnityContainer`)
- **WPF** (`System.Windows.Media.Brush`, `System.Windows.Visibility`)
### External Dependencies:
- **SQL Server** (via `System.Data.SqlClient`, `DbOperations.Connection`, `LocalOnlyOperations`)
- **`Resources.StringResources`** (localized strings: `"Local"`, `"CopyingTable"`, `"ClearingLocalDb"`, `"EnablingConstraints"`, `"SwitchFileNotFound"`)
### Inferred Consumers:
- Views (`IDatabaseStatusBarView`, `IDatabaseSwitchView`, `IDatabaseCopyView`) bind to these view models.
- Event publishers (`RaiseNotification`, `DbStatusEvent`, `AppStatusEvent`, etc.) drive view model state changes.
- `DatabaseServices` layer (`DbOperations`, `LocalOnlyOperations`) is called directly by these view models.
---
## 5. Gotchas
- **`DatabaseStatusBarViewModel` has two constructors** — the parameterless one does not subscribe to events, so `OnDbEvent`, `OnBusyIndicatorNotification`, and `OnRaiseNotification` will not be triggered if used. This is likely a design flaw or legacy artifact.
- **`DatabaseStatusBarViewModel.OnDbEvent` only handles `LegacyStatus`** — other status types (e.g., `FailedToConnectToRemote`) are silently ignored.
- **`DatabaseCopyViewModel.CopyFunc()` loads entire remote tables into memory** — `CopyRemoteTable` fetches all rows via `QueryDataSet` before copying. This may cause OOM for large tables.
- **`DatabaseCopyViewModel` uses hardcoded table list (`_allDBTables`)** — not dynamically fetched from DB schema. Duplicates exist (`"DataPRODbVersion"` and `"tblDataPRODbVersion"`), and missing tables will cause copy failures.
- **Batch size (`MAX_BATCH_SIZE = 20`) is arbitrary** — comment notes it was tuned empirically to avoid SQL parameter limits (2100), but no validation ensures column count × rows ≤ 2100.
- **`DatabaseSwitchViewModel.SwitchRemote()` calls `SwitchLocal()` on failure** — this may cause cascading failures or confusing UI state if local DB is also unavailable.
- **`DatabaseStatusBarViewModel.ServerName` is updated only in `OnDbEvent` for `LegacyStatus`** — if `InitializeValues` is not called first, `ServerName` remains `null`/empty, leading to incorrect `ActiveDbName`.
- **`DatabaseCopyViewModel.InitializeAsync()` resolves views/models twice** — two separate `Resolve` calls for `IStatusAndProgressBarView`/`IStatusAndProgressBarViewModel` per progress bar, potentially creating duplicate view model instances.
- **No cancellation support** — `CopyDatabase()` and `SwitchRemote()`/`SwitchLocal()` lack cancellation tokens or progress callbacks for user-initiated aborts.
- **`DbOperations._usingCentralizedDB` is a static field** — shared across the app domain; changes in one view model affect others unexpectedly.
- **`DatabaseStatusBarViewModel.ActiveDbName` returns `""` for unhandled `DbType`** — no fallback or exception on unknown types.
- **`DatabaseCopyViewModel` uses `sp_msforeachtable`** — undocumented, unsupported SQL Server stored procedure; may break on future SQL Server versions or non-standard DB configurations.