--- source_files: - DataPRO/DASFactoryDb/DbWrapper.cs generated_at: "2026-04-16T03:44:18.623811+00:00" model: "Qwen/Qwen3-Coder-Next-FP8" schema_version: 1 sha256: "836c8383a0b90cbc" --- # DASFactoryDb ### **Purpose** The `DbWrapper` class serves as a minimal, internal database access abstraction layer for the `DASFactory` database, specifically targeting SQL Server. It encapsulates connection string construction, singleton-based instance management, and basic command execution for stored procedures. Its primary role is to provide a centralized, reusable mechanism for retrieving device IDs and handling SQL command execution with error propagation, while supporting future flexibility between local and centralized database configurations via static flags (`_usingCentralizedDB`, `_usingNTLMAuthentication`). The class is not intended for general-purpose data access but focuses on a narrow set of operations required by the DASFactory system. --- ### **Public Interface** All members are `public` or `internal`, but the class is `partial` and its constructor is `protected`, suggesting it may be extended elsewhere in the codebase. Only the following are *publicly* accessible from outside the assembly (based on `public` modifiers): - **`public static bool _usingCentralizedDB`** A static flag indicating whether the system should use a centralized database (currently always `false` per comments). Used for future configuration flexibility. - **`public static bool _usingNTLMAuthentication`** A static flag indicating whether to use Windows Authentication (NTLM) for database connections (currently always `true`). Affects connection string generation. - **`public static bool Connected`** A read/write static property that *always returns `false`* (per its `get => false;` implementation). The summary states it is “used to passively indicate connection status, does not perform any connection checking.” **Note:** This property is non-functional as implemented. - **`public static DbWrapper Connection`** A static property implementing a thread-safe singleton pattern. Returns the single instance of `DbWrapper` (lazily initialized on first access). Uses `lock(dbLock)` to ensure thread-safe initialization. - **`public string Server { get; set; }`** Gets or sets the database server name. Required for connection string generation; must be non-empty/whitespace when `GetLocalDASFactoryConnectionString()` is called. - **`public string DBName { get; set; }`** Gets or sets the database name. *Not used in current implementation*—the connection string hardcodes `"Database=DASFactory;"`. - **`public string Username { get; set; }`** Gets or sets the SQL Server username. Used only when `_usingNTLMAuthentication` is `false`. - **`public string Password { get; set; }`** Gets or sets the SQL Server password. Used only when `_usingNTLMAuthentication` is `false`. - **`public void ResetLocalDASFactoryConnection()`** Resets the cached connection string (`_localDASFactoryConnection = null`) and resets `_usingNTLMAuthentication` to `true`. Intended to force re-computation of the connection string on next access. - **`public string GetLocalDASFactoryConnectionString()`** Returns a SQL Server connection string for the `DASFactory` database. Uses cached value if available; otherwise constructs it based on `Server`, `_usingNTLMAuthentication`, `Username`, and `Password`. Throws `Exception("Empty Server")` if `Server` is null/whitespace. - If `_usingNTLMAuthentication == true`: `"Server={Server};Database=DASFactory;Trusted_Connection=TRUE;"` - Else: `"Server={Server};Database=DASFactory;User Id={Username};Password={Password};"` - **`public static int GetDeviceId(string serialNumber)`** Executes the stored procedure `sp_IDASCommunicationTableGetRecordId` with `@SerialNumber` as input. Returns the `RecordId` (as `int`) if found, or `-1` if no matching record exists. Throws `Exception("Not connected")` if `Connected` is `false` (which it always is, per the property implementation—see *Gotchas*). Disposes the underlying connection after use. - **`internal static void ProcessReturn(SqlParameter errorNumber, SqlParameter errorMessage)`** Checks the `Value` of `errorNumber`. If non-null and non-zero, throws an `Exception` concatenating `errorNumber.Value` and `errorMessage.Value`. Used to propagate SQL stored procedure error codes/messages. --- ### **Invariants** - The `Server` property **must** be set to a non-null, non-whitespace string before calling `GetLocalDASFactoryConnectionString()`; otherwise, an exception is thrown. - The `Connected` property is *always* `false`, regardless of actual database state. Any code checking `if (!Connected)` will always throw an exception. - The `DbWrapper.Connection` singleton is lazily initialized and thread-safe via `lock(dbLock)`. - Connection strings are cached in `_localDASFactoryConnection`; subsequent calls return the cached value until `ResetLocalDASFactoryConnection()` is invoked. - `GetDeviceId()` always opens and disposes its own `SqlConnection` internally; it does not use the singleton’s state for persistence. --- ### **Dependencies** - **Direct Dependencies (from imports):** - `System` - `System.Data` - `System.Data.SqlClient` - `DASFactoryDb.Connection` (used in `GetDASFactoryCommand()` via `Connection.GetLocalDASFactoryConnectionString()`) - **Inferred Usage:** - The stored procedure `sp_IDASCommunicationTableGetRecordId` must exist in the `DASFactory` database. - The `Connection` class (referenced in `GetDASFactoryCommand()`) must define `GetLocalDASFactoryConnectionString()`—likely in a separate file or module. - **Dependents (inferred):** - Any code calling `DbWrapper.Connection`, `GetDeviceId()`, or `GetLocalDASFactoryConnectionString()` (e.g., device lookup logic). - The `ProcessReturn()` method suggests integration with stored procedures that output `@ErrorNumber` and `@ErrorMessage` parameters. --- ### **Gotchas** - **`Connected` is non-functional:** Its `get` accessor always returns `false`, so `GetDeviceId()` will *always* throw `"Not connected"`—this is likely a bug or incomplete implementation. - **Hardcoded database name:** `DBName` is unused; the connection string always uses `"DASFactory"`. - **No connection pooling or reuse:** `GetDASFactoryCommand()` creates and opens a *new* `SqlConnection` on every call, then disposes it in `GetDeviceId()`—inefficient for repeated calls. - **Exception message format in `ProcessReturn`:** Concatenates `errorNumber.Value` (likely an `int`) and `errorMessage.Value` (a `string`) without a separator, potentially causing ambiguous error messages (e.g., `"53Operation failed"`). - **Thread-safety gap:** While `Connection` singleton is thread-safe, `ResetLocalDASFactoryConnection()` modifies static state (`_usingNTLMAuthentication`) without locking—could cause race conditions if called concurrently with `GetLocalDASFactoryConnectionString()`. - **No async support:** All database operations are synchronous (`ExecuteReader()`), which may block threads in UI or high-throughput services. - **Missing null/empty checks in `GetDeviceId`:** Does not validate `serialNumber` before passing to the stored procedure. - **`_usingCentralizedDB` is unused:** Despite being declared, no logic in this file branches on its value.