12 KiB
source_files, generated_at, model, schema_version, sha256
| source_files | generated_at | model | schema_version | sha256 | |||
|---|---|---|---|---|---|---|---|
|
2026-04-16T04:35:56.029845+00:00 | Qwen/Qwen3-Coder-Next-FP8 | 1 | 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 Prism’s 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"forDbType.LocalOnly,ServerNameforDbType.RemoteOnly, orServerName/"Local"conditionally forDbType.RemoteLocalHybrid. -
Brush BackgroundBrush { get; }
ReturnsBrushes.RedwhenDatabaseType == DbType.RemoteLocalHybridandRemoteConnected == false; otherwiseBrushes.Transparent. -
bool RemoteConnected { get; }
Returns the value ofDbOperations._usingCentralizedDB. -
string ServerName { get; private set; }
Holds the remote server name; updated viaInitializeValuesorOnDbEvent. -
void InitializeValues(DbType dbType, string serverName, bool remoteConnected)
SetsDatabaseType,ServerName, and triggers property change notifications forActiveDbNameandBackgroundBrush. -
void OnDbEvent(DbStatusArg args)
Internal event handler forDbStatusEvent; updatesServerNameand notifies changes toActiveDbName/BackgroundBrushwhenargs.Status == LegacyStatus. -
bool IsBusy { get; set; }
Binds to UI busy indicator; updated viaOnBusyIndicatorNotification. -
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.DataContextis set tothisin constructor. -
Constructors
DatabaseStatusBarViewModel(IDatabaseStatusBarView view, IRegionManager regionManager, IEventAggregator eventAggregator, IUnityContainer unityContainer)
Registers event subscriptions forRaiseNotification,BusyIndicatorChangeNotification, andDbStatusEvent.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; }
ReturnsDbOperations._usingCentralizedDB. -
void SwitchRemote()
Attempts to switch to remote database:- Publishes
AppStatusArg.Busy. - Calls
DatabaseServices.SetupForRemoteDb(...)with stored credentials. - Validates connection via
SimpleDbTest(). - On failure: publishes
DbStatusEventwithFailedToConnectToRemote, callsSwitchLocal(), logs exception. - On success: publishes
DbStatusEvent.LegacyStatus,AppStatusArg.Available, andLogoutUserEvent(reason:DatabaseSwitch).
- Publishes
-
void SwitchLocal()
Switches to local database:- Checks local DB files exist via
CheckLocalDatabaseFilesExist(...). - Publishes
AppStatusArg.Busy. - Calls
DatabaseServices.SetupLocal(...). - Publishes
DbStatusEvent.LegacyStatus,AppStatusArg.Available, andLogoutUserEvent.
- Checks local DB files exist via
-
void InitializeDbSettings(string defaultDbName, string dbHost, bool ntlmAuthentication, string dbUser, string dbPassword)
Stores connection settings for later use inSwitchRemote(). -
Properties:
DefaultDbName,DbHost,NTLMAuthentication,DbUser,DbPassword(allprivate set). -
bool IsBusy,IsMenuIncluded,IsNavigationIncluded
Same semantics asDatabaseStatusBarViewModel. -
Constructors & Lifecycle methods
Same asDatabaseStatusBarViewModel; constructor subscribes toRaiseNotificationandBusyIndicatorChangeNotification.
DatabaseCopyViewModel
-
bool CopyEnabled { get; }
Returnstrueonly ifDatabaseType == DbType.RemoteLocalHybridandDbOperations._usingCentralizedDB == true. -
void CopyDatabase()
TriggersCopyFunc()on a background task (Task.Run). PublishesAppStatusArg.Busybefore andAppStatusArg.Availableafter. -
void InitializeState(DbType dbType, string dbName)
SetsDatabaseTypeandDbName, publishes initialProgressBarEventfor both progress bars (collapsed), and notifiesCopyEnabled. -
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 duringInitializeAsync(). -
Task InitializeAsync()
Resolves and configures twoIStatusAndProgressBarViewinstances:- One for
OverallTaskBar(named"OverallStatus"). - One for
CurrentTaskBar(named"CurrentTaskStatus").
Each is bound to a sharedIStatusAndProgressBarViewModelinstance.
- One for
-
void OnRaiseNotification(NotificationContentEventArgs)
Wraps event args intoNotificationand raisesNotificationRequest. -
void OnBusyIndicatorNotification(bool)
SetsIsBusy. -
bool IsBusy,IsMenuIncluded,IsNavigationIncluded,IsDirty
Same semantics as above. -
Internal helper methods (private)
CopyFunc(): Main copy logic:- Backs up local DB.
- Disables constraints.
- Copies all tables in
_allDBTablesviaCopyRemoteTable(...). - Fixes
Channels.DASId = 0 → NULL. - Re-enables constraints.
- Restores local DB on failure.
- 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), handlesIDENTITY_INSERTfor tables in_tablesWithIdentities.SetStatus(string bar, double percentage, string text): PublishesProgressBarEvent.
-
Constants & Data
MAX_BATCH_SIZE = 20_allDBTables: List of 72 table names (includes duplicates like"tblDataPRODbVersion"and"DataPRODbVersion")._tablesWithIdentities: HashSet of 58 table names requiringIDENTITY_INSERT ON/OFF.
3. Invariants
RemoteConnectedis derived solely fromDbOperations._usingCentralizedDB— no local state overrides it.ActiveDbNameandBackgroundBrushdepend onDatabaseTypeandRemoteConnected— their values are recalculated only whenDatabaseTypeorServerNamechanges (viaInitializeValuesorOnDbEvent).- Progress bars are always reset to collapsed/zero on completion/failure —
CopyFunc()publishesProgressBarEventwithVisibility.Collapsedinfinally. CopyDatabase()runs asynchronously —Task.Runis used explicitly; noasync/awaitis used internally.DatabaseCopyViewModelrequiresInitializeAsync()to be called beforeCopyDatabase()— otherwiseOverallProgressBarView/CurrentTaskProgressBarViewremainnull.DatabaseSwitchViewModel.SwitchRemote()andSwitchLocal()always triggerLogoutUserEvent— user session is invalidated after any database switch.DatabaseStatusBarViewModel.OnDbEvent(...)only handlesLegacyStatus— otherDbStatusArg.EventTypesare ignored.
4. Dependencies
Internal Dependencies (from source):
DTS.Common.*:DTS.Common.Enums.Database.DbTypeDTS.Common.Events.*(RaiseNotification,BusyIndicatorChangeNotification,DbStatusEvent,AppStatusEvent,PageErrorEvent,LogoutUserEvent)DTS.Common.Storage.DatabaseServices(SetupForRemoteDb,SimpleDbTest,SetupLocal,BackupLocalDatabase,RestoreLocalDatabase,LOCAL_DB_FOLDER)DTS.Common.Storage.DatabaseServices(viaDbOperations,LocalOnlyOperations)DTS.Common.Interface.Database.*(e.g.,IDatabaseStatusBarView,IDatabaseCopyViewModel)DTS.Common.Interface.*(e.g.,IStatusAndProgressBarView)DTS.Common.Utilities.Logging.APILoggerDTS.Common.Interactivity.*(InteractionRequest,Notification,Confirmation)
- Prism Framework:
Prism.Events.IEventAggregator,Prism.Regions.IRegionManagerPrism.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. DatabaseServiceslayer (DbOperations,LocalOnlyOperations) is called directly by these view models.
5. Gotchas
DatabaseStatusBarViewModelhas two constructors — the parameterless one does not subscribe to events, soOnDbEvent,OnBusyIndicatorNotification, andOnRaiseNotificationwill not be triggered if used. This is likely a design flaw or legacy artifact.DatabaseStatusBarViewModel.OnDbEventonly handlesLegacyStatus— other status types (e.g.,FailedToConnectToRemote) are silently ignored.DatabaseCopyViewModel.CopyFunc()loads entire remote tables into memory —CopyRemoteTablefetches all rows viaQueryDataSetbefore copying. This may cause OOM for large tables.DatabaseCopyViewModeluses 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()callsSwitchLocal()on failure — this may cause cascading failures or confusing UI state if local DB is also unavailable.DatabaseStatusBarViewModel.ServerNameis updated only inOnDbEventforLegacyStatus— ifInitializeValuesis not called first,ServerNameremainsnull/empty, leading to incorrectActiveDbName.DatabaseCopyViewModel.InitializeAsync()resolves views/models twice — two separateResolvecalls forIStatusAndProgressBarView/IStatusAndProgressBarViewModelper progress bar, potentially creating duplicate view model instances.- No cancellation support —
CopyDatabase()andSwitchRemote()/SwitchLocal()lack cancellation tokens or progress callbacks for user-initiated aborts. DbOperations._usingCentralizedDBis a static field — shared across the app domain; changes in one view model affect others unexpectedly.DatabaseStatusBarViewModel.ActiveDbNamereturns""for unhandledDbType— no fallback or exception on unknown types.DatabaseCopyViewModelusessp_msforeachtable— undocumented, unsupported SQL Server stored procedure; may break on future SQL Server versions or non-standard DB configurations.