# The C# Connection Class

Connection provides the interface for all threads interacting with a Database object.

### For an overview see page C# Classes

## Class Definition

        public class Connection : IDisposable
        {
            /* Constructors */
            public Connection(Database db)
            public Connection(Connection con)
            public Connection(Database db, byte[] context)

            /* Methods */
            public void StartTransaction(Database.TransactionType type)
            public virtual void StartTransaction(Database.TransactionType type, Database.TransactionPriority pri, Database.IsolationLevel level)
            public virtual bool CommitTransaction()
            public bool CommitTransaction(int phase)
            public virtual bool CheckpointTransaction()
            public void SetCommitPolicy(Database.CommitPolicy policy)
            public void DiskFlush()
            public virtual void RollbackTransaction()
            public long Insert(Object obj)
            public T Create<T>() where T : class
            public T Create<T>(out long autoid) where T : class
            public long Count(Type cls)
            public void RemoveAll(Type cls)
            public virtual void Disconnect()
            public virtual void Dispose()
            public bool SaveSnapshot(String databaseSnapshotFilePath)
            public void SaveMetadata(String metadataFile, bool saveDefaults)
            public void SaveDictionary(String dictionaryFile)
            public bool SaveClass(String filePath, Type cls)
            public bool LoadClass(String filePath, Type cls, bool doMerge)
            public bool LoadClass(String filePath)
            public void SetCipherKeySnapshotTL(String cipherKey)
            public void IgnoreTtl(bool ignore)
            public bool IsTtlIgnored()
            public ClassStat GetClassStat(int ClassCode)
            public IndexStat GetIndexStat(Int16 index)
            public DiskInfo GetDiskInfo()
            public void WaitEvent(string name)
            public void StartEventListeners(string[] eventNames)
            public void ReleaseEvent(string name)
            public void ReleaseAllEvents()
            public virtual void CreateBackup(String fileName, String label, Database.BackupType type)
            public virtual void CreateBackup(String fileName, String label, Database.BackupType type, int compressionLevel, String cipher)
            public virtual void RestoreBackup(String fileName, String label)
            public void RestoreBackup(String fileName, String label, String cipher)
            public virtual Database.BackupInfo[] ListBackup(String fileName)
            public Table<T> GetTable<T>() where T : class
            public IEnumerable<T> Select<T>(Expression<Func<T,bool>> predicate) where T : class

            /* Properties */
            public ICursor CurrentCursor { get; }
            public Int32 FreePages { get; }
            public Int32 TotalPages { get; }
            public Int16 DbPageSize { get; }
            public Int32 DiskPageSize { get; }
            public Int16 IndexStatCount { get; }
            public int NumberOfSequentialSearches { get; }

            /* Events */
            public event AsyncEventHandler AsyncEvent
            public event AsyncEventErrorHandler AsyncEventError
        }

## Public Interface

### Constructors

Connection(Database db)
Database connection constructor.
Connection(Connection con)
Copy constructor for connection.
Connection(Database db, byte[] context)
Connection constructor with custom context.

### Transaction Methods

StartTransaction(TransactionType type)
Start a transaction with default priority and isolation level (nested transactions supported).
StartTransaction(TransactionType type, TransactionPriority pri, IsolationLevel level)
Start a transaction with specified priority and isolation level.
CommitTransaction()
Commit transaction. Returns `false` on MVCC conflict.
CommitTransaction(int phase)
Perform one of two phases of transaction commit (phase = 1 or 2).
CheckpointTransaction()
Checkpoint current transaction: insert all updated objects into indexes.
SetCommitPolicy(CommitPolicy policy)
Set transaction commit policy for this connection.
DiskFlush()
Flush all committed transaction changes to disk (used with MCO_COMMIT_BUFFERED policy).
RollbackTransaction()
Rollback transaction. All nested transactions are also cancelled.

### Object Methods

Insert(Object obj)
Insert a new object into the DB. Returns AUTOID if set, else 0.
Create<T>()
Create a new implementation of the specified interface or abstract class.
Create<T>(out long autoid)
Create implementation of interface/abstract class with AUTOID return.
Count(Type cls)
Return the number of instances of the specified class in the DB.
RemoveAll(Type cls)
Delete all instances of the specified class (inheritance not considered).

### Connection Management

Disconnect()
Close database connection.
Dispose()
Close connection (synonym for Disconnect, implements IDisposable).

### Snapshots and Export/Import

SaveSnapshot(String path)
Save DB snapshot to specified file for later loading via Database.Open.
SaveMetadata(String file, bool saveDefaults)
Save DB metadata in JSON format (compatible with xsql utility).
SaveDictionary(String file)
Save database dictionary to file.
SaveClass(String filePath, Type cls)
Save table (class) content to file.
LoadClass(String filePath, Type cls, bool doMerge)
Load table content from file. If doMerge=false, table is cleared before loading.
LoadClass(String filePath)
Load table content from file (simplified version, doMerge=false).
SetCipherKeySnapshotTL(String cipherKey)
Set encryption key for DB snapshots and transaction logs.

### TTL and Statistics

IgnoreTtl(bool ignore)
Configure TTL ignore mode.
IsTtlIgnored()
Return current TTL ignore mode.
GetClassStat(int ClassCode)
Get runtime statistics for the class.
GetIndexStat(Int16 index)
Get index statistics by number (total indexes — IndexStatCount).
GetDiskInfo()
Return DB state info: log size, DB file size, used space.

### Statistics Properties

FreePages
Total number of free pages in DB.
TotalPages
Total number of allocated pages in DB.
DbPageSize
Current DB page size for this connection.
DiskPageSize
Current disk page size for this connection.

### Async Events

WaitEvent(string name)
Wait for async event signal (blocking call, must run in separate thread).
StartEventListeners(string[] eventNames)
Start async event handlers for specified names.
ReleaseEvent(string name)
Signal async event.
ReleaseAllEvents()
Signal all async events.

### Backup

CreateBackup(...)
Create DB backup (overloads with compression and encryption parameters).
RestoreBackup(...)
Restore DB from backup.
ListBackup(String fileName)
Get list of backup metadata in file.

### LINQ

GetTable<T>()
[LINQ] Get table associated with class T.
Select<T>(Expression<Func<T,bool>> predicate)
[LINQ] Select records using LINQ predicate.
NumberOfSequentialSearches
[LINQ] Number of sequential searches performed by LINQ adapter since connection opened.

### Access Properties

CurrentCursor
Return current active cursor (most recently used if multiple).

### Events

AsyncEvent
Event: triggered on async event signal.
AsyncEventError
Event: triggered on async event processing error.