using System; using System.Data; using System.Data.Entity; using System.IO; using Application.Ringtoets.Storage.Converters; using Application.Ringtoets.Storage.DbContext; using Application.Ringtoets.Storage.Properties; using Core.Common.Base.Data; using Core.Common.Utils; using Core.Common.Utils.Builders; using UtilsResources = Core.Common.Utils.Properties.Resources; namespace Application.Ringtoets.Storage { /// /// This class interacts with an SQLite database file using the Entity Framework. /// public class StorageSqLite : StorageToFile { /// /// Creates a new instance of . /// /// Path to database file. /// is invalid. public StorageSqLite(string databaseFilePath) : base(databaseFilePath) { FileUtils.ValidateFilePath(databaseFilePath); if (!File.Exists(databaseFilePath)) { var message = new FileReaderErrorMessageBuilder(databaseFilePath).Build(UtilsResources.Error_File_does_not_exist); throw new FileNotFoundException(message); } ConnectionString = SqLiteStorageConnection.BuildSqLiteEntityConnectionString(databaseFilePath); } /// /// Tests if a connection can be made to a Ringtoets project file by verifying if the table 'Version' exists. /// /// Returns true if a valid connection can be made, false otherwise. public bool TestConnection() { using (var dbContext = new RingtoetsEntities(ConnectionString)) { try { dbContext.Database.Initialize(true); dbContext.Versions.Load(); return true; } catch { return false; } } } /// /// Converts to a new in the database. /// /// to save. /// Returns the number of changes that were saved in . public int SaveProjectAs(Project project) { using (var dbContext = new RingtoetsEntities(ConnectionString)) { try { var projectEntity = new ProjectEntity(); ProjectEntityConverter.ProjectToProjectEntity(project, projectEntity); dbContext.ProjectEntities.Add(projectEntity); return dbContext.SaveChanges(); } catch (DataException exception) { throw CreateUpdateDatabaseException(Resources.Error_Update_Database, exception); } catch (SystemException exception) { throw CreateUpdateDatabaseException(Resources.Error_During_Connection, exception); } } } /// /// Attempts to load the from the SQLite database. /// /// Returns a new instance of with the data from the database or null when not found. /// Thrown when ProjectEntities is null. public Project LoadProject() { using (var dbContext = new RingtoetsEntities(ConnectionString)) { return ProjectEntityConverter.GetProject(dbContext.ProjectEntities); } } } }