Пример #1
1
 public TestDb(ISQLitePlatform sqlitePlatform, String path)
     : base(sqlitePlatform, path)
 {
     Trace = true;
     CreateTable<TestObj>();
 }
 public TestDb(ISQLitePlatform sqlitePlatform)
     : base(sqlitePlatform, TestPath.CreateTemporaryDatabase())
 {
     CreateTable<Product>();
     CreateTable<OrderLine>();
     TraceListener = DebugTraceListener.Instance;
 }
 public TestDb(ISQLitePlatform sqlitePlatform)
     : base(sqlitePlatform, TestPath.GetTempFileName())
 {
     CreateTable<Product>();
     CreateTable<OrderLine>();
     Trace = true;
 }
Пример #4
0
        public EFDbConnect(ISQLitePlatform platform, string path,bool trace = false) : base(platform, path)
        {

            if (trace)
            {
                TraceListener = new DebugTraceListener_OutputWindow();
            }

            CreateTable<AppSetting>();
            CreateTable<LearningItem>();
            CreateTable<Statistics>();
            CreateTable<WordOfDictionary>();
            CreateTable<LearningWordStrategy>();
            CreateTable<FrequencyDictionary>();
            CreateTable<FrequencyDictionary.Item>();
            CreateTable<ProcessingWordsRules>();
            CreateTable<Dictionary>();
            CreateTable<Language>();
            CreateTable<Subtitles>();
            CreateTable<SubtitleItem>();
            CreateTable<WordOfSubtitleItem>();
            CreateTable<LanguageService>();
            CreateTable<LanguageService.LanguageOfService>();
            CreateTable<AudioTrack>();
            CreateTable<LearnedWord>();
            CreateTable<TranslationOfWord>();
            CreateTable<LearningWordStrategy.StrategyItem>();
            CreateTable<Statistics.StatisticsItem>();

            CreateSchema();

            Udpate();

            RemoveOldColumns();
        }
Пример #5
0
        public Database(ISQLitePlatform platform, string databasePath)
        {
            _connectionParameters = new SQLiteConnectionString(databasePath, false);
            _sqliteConnectionPool = new SQLiteConnectionPool(platform);

            _dbConnection = new SQLiteAsyncConnection(() => _sqliteConnectionPool.GetConnection(_connectionParameters));
        }
Пример #6
0
		public App(string dbPath, ISQLitePlatform sqlitePlatform)
		{
			//set database path first, then retrieve main page
			PersonRepo = new PersonRepository(sqlitePlatform, dbPath);

			this.MainPage = new MainPage();
		}
Пример #7
0
 //TODO : Inject sqlite
 public ConferencesViewModel(ITekConfService tekConfService, ISQLitePlatform sqlite)
 {
     
     _tekConfService = tekConfService;
     _sqliteClient = new SQLiteClient(sqlite);
     this.Conferences = new List<Conference>();
 }
Пример #8
0
        public static Page GetMainPage(ISQLitePlatform sqlitePlatform, string dbPath)
        {
            //set database path first, then retrieve main page
            PersonRepo = new PersonRepository(sqlitePlatform, dbPath);

            return new MainPage();
        }
Пример #9
0
        /// <summary>
        ///     Creates an instance of a DbHelper
        /// </summary>
        public DbHelper(ISQLitePlatform platform, IDatabasePath path)
        {
            this.platform = platform;
            this.path = path;

            CreateDatabase();
        }
        public UserAccountDataSource(ISQLitePlatform platform, string dbPath)
        {
            var connectionFactory = new Func<SQLiteConnectionWithLock>(() => new SQLiteConnectionWithLock(platform, new SQLiteConnectionString(dbPath, storeDateTimeAsTicks: false)));
            Db = new SQLiteAsyncConnection(connectionFactory);

            AccountUserRepository = new Repository<AccountUser>(Db);
        }
        public StickersDataSource(ISQLitePlatform platform, string dbPath)
        {
            var connectionFactory = new Func<SQLiteConnectionWithLock>(() => new SQLiteConnectionWithLock(platform, new SQLiteConnectionString(dbPath, storeDateTimeAsTicks: false)));
            Db = new SQLiteAsyncConnection(connectionFactory);

            StickersRepository = new Repository<StickerResponse>(Db);
        }
Пример #12
0
		public VTSViewModel (IFileSystemService fileSystem, ILocalizer localazer, ISQLitePlatform sqlitePlatform)
		{	
			_vacationList = new VacationInfoMockModel ().Vacations;

			_fileSystem = fileSystem;
			this.Localaizer = localazer;
			_sqlitePlatform = sqlitePlatform;
		}
Пример #13
0
        public App(string dbPath, ISQLitePlatform sqlitePlatform)
        {
            /* initialize data */
            LocalDb.SetDb(dbPath, sqlitePlatform);

            // The root page of your application
            MainPage = new MainPage(new Page0("page 0"));
        }
Пример #14
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 /// <param name="platform">Platform specific SQLite implementation</param>
 /// <param name="path">Path to database file</param>
 public Database(ISQLitePlatform platform, string path)
     : base(platform, path, true)
 {
     CreateTable<Item>();
     CreateTable<Investment>();
     CreateTable<InvestmentList>();
     CreateTable<Watchlist>();
     BusyTimeout = new TimeSpan(0,0,0,2);
 }
Пример #15
0
        /// <summary>
        /// Construtor da casse para a criação da conexão
        /// </summary>
        /// <param name="sqliteP">Plataforma - ios, android ou winPhone</param>
        /// <param name="dbPath">Caminho onde está o arquivo db3</param>
        public DataBaseRepository(ISQLitePlatform sqliteP, string dbPath)
        {
            if (dbCon == null) {

                dbCon = new SQLiteConnection (sqliteP, dbPath);
                dbCon.CreateTable<Aluno> ();

            }
        }
        public SqliteEventStore(ISQLitePlatform sqLitePlatform, string databasePath, GetUtcNow getUtcNow = null)
        {
            Ensure.That(sqLitePlatform, "sqLitePlatform").IsNotNull();
            Ensure.That(databasePath, "databasePath").IsNotNull();

            _getUtcNow = getUtcNow ?? SystemClock.GetUtcNow;
            _connectionPool = new SQLiteConnectionPool(sqLitePlatform);
            var connectionString = new SQLiteConnectionString(databasePath, false);
            _getConnection = () => _connectionPool.GetConnection(connectionString);
        }
Пример #17
0
 public SqliteContext(ISQLitePlatform platform,DatabaseInitializator init)
 {
     _platform = platform;
     _init = init;
     _dbPath = init.Path;
     var connection = new SQLiteConnectionWithLock(_platform,
         new SQLiteConnectionString(_dbPath, storeDateTimeAsTicks: true));
     _connectionFactory = new Func<SQLiteConnectionWithLock>(() =>connection);
     CreateTables();
 }
        public PersonRepository(ISQLitePlatform sqlitePlatform, string dbPath)
        {
            //initialize a new SQLiteConnection 
            if (dbConn == null)
            {
                dbConn = new SQLiteConnection(sqlitePlatform, dbPath);

                //create the Person table
                dbConn.CreateTable<Person>();
            }
        }
Пример #19
0
 public static Manager GetInstance(ISQLitePlatform plataform, IServiceClient client, string path)
 {
     if (_instance == null)
     {
         lock (_mutex)
         {
             if (_instance == null)
             {
                 _instance = new Manager(plataform, client, path);
             }
         }
     }
     return _instance;
 }
Пример #20
0
        public static DatabaseState Connect(ISQLitePlatform platform, string databasePath)
        {
            try
            {
                Connection = new SQLiteConnection(platform, databasePath, storeDateTimeAsTicks:false);

                return Connection.ExecuteScalar<int>(@"select count(*) from sqlite_master") == 0 ? DatabaseState.Empty : DatabaseState.NotEmpty;
            }
            catch (Exception)
            {
                Connection = null;
                return DatabaseState.Invalid;
            }
        }
Пример #21
0
        public TableMapping(ISQLitePlatform platformImplementation, Type type,
            CreateFlags createFlags = CreateFlags.None)
        {
            _sqlitePlatform = platformImplementation;
            MappedType = type;

            var tableAttr = (TableAttribute) type.GetTypeInfo().GetCustomAttributes(typeof (TableAttribute), true).FirstOrDefault();

            TableName = tableAttr != null ? tableAttr.Name : MappedType.Name;

            IEnumerable<PropertyInfo> props = _sqlitePlatform.ReflectionService.GetPublicInstanceProperties(MappedType);

            var cols = new List<Column>();
            foreach (PropertyInfo p in props)
            {
                bool ignore = p.GetCustomAttributes(typeof (IgnoreAttribute), true).Any();

                if (p.CanWrite && !ignore)
                {
                    cols.Add(new Column(p, createFlags));
                }
            }
            Columns = cols.ToArray();
            foreach (Column c in Columns)
            {
                if (c.IsAutoInc && c.IsPK)
                {
                    _autoPk = c;
                }
                if (c.IsPK)
                {
                    PKs.Add(c);
                }
            }

            HasAutoIncPK = _autoPk != null;

            if (PK != null)
            {
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
                PkWhereSql = PKs.Aggregate(new StringBuilder(), (sb, pk) => sb.AppendFormat(" \"{0}\" = ? and", pk.Name), sb => sb.Remove(sb.Length - 3, 3).ToString());
                GetByPrimaryKeysSql = String.Format("select * from \"{0}\" where {1}", TableName, PkWhereSql);
            }
            else
            {
                // People should not be calling Get/Find without a PK
                GetByPrimaryKeysSql = GetByPrimaryKeySql = string.Format("select * from \"{0}\" limit 1", TableName);
            }
        }
Пример #22
0
		public PersonRepository(ISQLitePlatform sqlitePlatform, string dbPath)
		{
			//initialize a new SQLiteConnection 
			if (dbConn == null)
			{
				var connectionFunc = new Func<SQLiteConnectionWithLock>(() =>
					new SQLiteConnectionWithLock
					(
						sqlitePlatform,
						new SQLiteConnectionString(dbPath, storeDateTimeAsTicks: false)
					));

				dbConn = new SQLiteAsyncConnection(connectionFunc);
				dbConn.CreateTableAsync<Person>();
			}
		}
Пример #23
0
        public TableMapping(ISQLitePlatform platformImplementation, Type type,
                            CreateFlags createFlags = CreateFlags.None)
        {
            _sqlitePlatform = platformImplementation;
            MappedType = type;

            var tableAttr = type.GetTypeInfo().CustomAttributes.FirstOrDefault(data => data.AttributeType == typeof(TableAttribute));

            TableName = tableAttr != null ? (string)tableAttr.ConstructorArguments.FirstOrDefault().Value : MappedType.Name;

            IEnumerable<PropertyInfo> props = _sqlitePlatform.ReflectionService.GetPublicInstanceProperties(MappedType);

            var cols = new List<Column>();
            foreach (PropertyInfo p in props)
            {
                bool ignore = p.GetCustomAttributes<IgnoreAttribute>(true).Any();

                if (p.CanWrite && !ignore)
                {
                    cols.Add(new Column(p, createFlags));
                }
            }
            Columns = cols.ToArray();
            foreach (Column c in Columns)
            {
                if (c.IsAutoInc && c.IsPK)
                {
                    _autoPk = c;
                }
                if (c.IsPK)
                {
                    PK = c;
                }
            }

            HasAutoIncPK = _autoPk != null;

            if (PK != null)
            {
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
            }
            else
            {
                // People should not be calling Get/Find without a PK
                GetByPrimaryKeySql = string.Format("select * from \"{0}\" limit 1", TableName);
            }
        }
Пример #24
0
        public static SQLiteAsyncConnection GetConnection(string path, ISQLitePlatform sqlitePlatform)
        {
            var connectionFactory = new Func <SQLiteConnectionWithLock>(() => new SQLiteConnectionWithLock(sqlitePlatform, new SQLiteConnectionString(path, storeDateTimeAsTicks: false)));

            return(new SQLiteAsyncConnection(connectionFactory));
        }
Пример #25
0
 /// <summary>Initializes a new instance of the <see cref="TableQueryBridge{T}" /> class.</summary>
 /// <param name="platformImplementation">The platform implementation.</param>
 /// <param name="conn">The connection.</param>
 public TableQueryBridge(ISQLitePlatform platformImplementation, SQLiteConnection conn)
     : base(platformImplementation, conn)
 {
 }
Пример #26
0
 public SQLiteService(ISQLitePlatform platform, SQLiteConnectionString connectionString)
 {
     connection = new SQLiteConnectionWithLock(platform, connectionString);
     context    = new SQLiteAsyncConnection(() => connection);
     isDisposed = false;
 }
Пример #27
0
        /// <summary>
        /// Get or create a pooled connection
        /// </summary>
        private LockableSQLiteConnection GetOrCreatePooledConnection(ConnectionString dataSource, bool isReadonly)
        {
            // First is there a connection already?
            var connections = this.GetOrRegisterConnections(dataSource);
            WriteableSQLiteConnection writeConnection = null;

            lock (s_lockObject)
            {
                if (this.m_writeConnections.TryGetValue(dataSource.Name, out writeConnection))
                {
                    if (Monitor.IsEntered(writeConnection))
                    {
                        return(writeConnection);
                    }
                }
                var conn = connections.FirstOrDefault(o => Monitor.IsEntered(o));
                if (conn != null)
                {
                    return(conn);
                }
            }


            ISQLitePlatform platform = ApplicationContext.Current.GetService <ISQLitePlatform>();

            lock (s_lockObject)
            {
                LockableSQLiteConnection retVal = null;
                if (isReadonly)
                {
                    retVal = this.m_connectionPool.OfType <ReadonlySQLiteConnection>().FirstOrDefault(o => o.ConnectionString.Name == dataSource.Name);
                }
                else
                {
                    if (!this.m_writeConnections.TryGetValue(dataSource.Name, out writeConnection)) // Writeable connection can only have one in the pool so if it isn't there make sure it isn't in the current
                    {
                        writeConnection = new WriteableSQLiteConnection(platform, dataSource, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.Create)
                        {
                            Persistent = true
                        };
                        writeConnection.Execute("PRAGMA synchronous = 1");
                        //writeConnection.Execute("PRAGMA automatic_index = true");
                        //writeConnection.Execute("PRAGMA journal_mode = WAL");
                        this.m_writeConnections.Add(dataSource.Name, writeConnection);
                    }
                    retVal = writeConnection;
                }

                // Remove return value
                if (retVal != null)
                {
                    this.m_connectionPool.Remove(retVal);
                }
                else if (isReadonly)
                {
                    retVal = new ReadonlySQLiteConnection(platform, dataSource, SQLiteOpenFlags.ReadOnly | SQLiteOpenFlags.FullMutex)
                    {
                        Persistent = true
                    };
                    //retVal.Execute("PRAGMA threads = 2");
                }
                else
                {
                    throw new InvalidOperationException("Should not be here");
                }
                return(retVal);
            }
        }
Пример #28
0
 public SampleDbConnection(ISQLitePlatform sqlitePlatform, string path)
     : base(sqlitePlatform, new SQLiteConnectionString(Path.Combine(path, "Samples.db"), true))
 {
     this.CreateTable <GeofenceEvent>();
 }
Пример #29
0
 public RefereeRepository(ISQLitePlatform platform, string databasePath) : base(platform, databasePath)
 {
 }
Пример #30
0
 /// <summary>
 /// Creates a locked SQLite connection
 /// </summary>
 public LockedSQLiteConnection(
     ISQLitePlatform sqlitePlatform, string databasePath, bool storeDateTimeAsTicks = true, IBlobSerializer serializer = null, IDictionary <string, TableMapping> tableMappings = null, IDictionary <Type, string> extraTypeMappings = null, IContractResolver resolver = null
     ) : base(sqlitePlatform, databasePath, storeDateTimeAsTicks, serializer, tableMappings, extraTypeMappings, resolver)
 {
 }
 public Entry(ISQLitePlatform sqlitePlatform, SQLiteConnectionString connectionString)
 {
     ConnectionString = connectionString;
     Connection       = new SQLiteConnectionWithLock(sqlitePlatform, connectionString);
 }
Пример #32
0
		public MyDatabase(ISQLitePlatform platform, string dbfile, ICryptoService cryptoService) : base(platform, dbfile, cryptoService)
		{
		}
Пример #33
0
 public InitializeSettings(string dbPath, ISQLitePlatform platform)
 {
     DBPath   = dbPath;
     Platform = platform;
 }
Пример #34
0
 public DbAcs(ISQLitePlatform sqlitePlatform, String path)
     : base(sqlitePlatform, path)
 {
     TraceListener = DebugTraceListener.Instance;
 }
Пример #35
0
 public GoalService(bool connectedService, string dbPath, ISQLitePlatform platform)
 {
     _connectedService = connectedService;
     _platform         = platform;
     _dbPath           = dbPath;
 }
 public SqliteConnectionProvider(ISystemInfoProvider systemInfoProvider)
 {
     _systemInfoProvider = systemInfoProvider;
     _sqLitePlatform     = _systemInfoProvider.SqLitePlatform;
 }
Пример #37
0
 /// <summary>Initializes a new instance of the <see cref="TableQueryBridge{T}" /> class.</summary>
 /// <param name="platformImplementation">The platform implementation.</param>
 /// <param name="conn">The connection.</param>
 /// <param name="table">The table.</param>
 protected TableQueryBridge(
     ISQLitePlatform platformImplementation, SQLiteConnection conn, TableMapping table)
     : base(platformImplementation, conn, table)
 {
 }
Пример #38
0
 /// <summary>
 /// Construct a new instance of SecureDatabase.
 /// This ctor allows you pass an instance of the CryptoService. You could use the one provided by SQLite.Net.Cipher or build and pass your own.
 /// </summary>
 /// <param name="platform">The platform specific engine of SQLite (ISQLitePlatform)</param>
 /// <param name="dbfile">The sqlite db file path</param>
 /// <param name="cryptoService">An instance of the Crypto Service</param>
 protected SecureDatabase(ISQLitePlatform platform, string dbfile, ICryptoService cryptoService) : base(platform, dbfile)
 {
     _cryptoService = cryptoService;
     CreateTables();
 }
Пример #39
0
 public ReadonlySQLiteConnection(ISQLitePlatform sqlitePlatform, String databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true, IBlobSerializer serializer = null, IDictionary <String, TableMapping> tableMappings = null, IDictionary <Type, String> extraTypeMappings = null, IContractResolver resolver = null) :
     base(sqlitePlatform, databasePath, openFlags, storeDateTimeAsTicks, serializer, tableMappings, extraTypeMappings, resolver)
 {
 }
Пример #40
0
 public PokemonService(IStorageService storageService, ISQLitePlatform sqlitePlatform)
     : base(storageService, sqlitePlatform)
 {
 }
 public SQLiteConnectionPool(ISQLitePlatform sqlitePlatform)
 {
     _sqlitePlatform = sqlitePlatform;
 }
 internal PreparedSqlLiteInsertCommand(ISQLitePlatform platformImplementation, SQLiteConnection conn)
 {
     _sqlitePlatform = platformImplementation;
     Connection      = conn;
 }
Пример #43
0
 public MyDatabase(ISQLitePlatform platform, string dbfile) : base(platform, dbfile)
 {
 }
Пример #44
0
        /// <summary>
        /// Rekey databases
        /// </summary>
        public void RekeyDatabases()
        {
            if (ApplicationContext.Current.GetCurrentContextSecurityKey() == null)
            {
                return;         // no need to rekey
            }
            lock (s_lockObject) // prevent others from obtaining connections
                try
                {
                    ISQLitePlatform platform          = ApplicationContext.Current.GetService <ISQLitePlatform>();
                    var             connectionStrings = (ApplicationContext.Current.GetService <IConfigurationManager>()).GetSection <DcDataConfigurationSection>().ConnectionString;
                    for (var i = 0; i < connectionStrings.Count; i++)
                    {
                        ApplicationContext.Current.SetProgress(Strings.locale_backup_restore, (float)i / connectionStrings.Count);
                        var cstr = connectionStrings[i];

                        // Obtain and lock the connection pool
                        this.m_tracer.TraceVerbose("Rekey {0} - Closing existing connections", cstr.Name);
                        var pool = this.GetConnectionPool(cstr.Name);
                        pool.CloseAll();

                        using (pool.Lock()) // Prevent new pool connections from being created
                        {
                            var dbFile = cstr.GetComponent("dbfile");
                            try
                            {
                                if (!File.Exists(dbFile))
                                {
                                    continue;                       // could not find file
                                }
                                File.Move(dbFile, Path.ChangeExtension(dbFile, "old"));

                                // Create new encrypted database
                                Mono.Data.Sqlite.SqliteConnection.CreateFile(dbFile);
                                using (var prodConn = new Mono.Data.Sqlite.SqliteConnection($"Data Source={dbFile}"))
                                {
                                    prodConn.Open();
                                    using (var cmd = prodConn.CreateCommand())
                                    {
                                        cmd.CommandType = System.Data.CommandType.Text;
                                        cmd.CommandText = $"PRAGMA key = '{Encoding.UTF8.GetString(ApplicationContext.Current.GetCurrentContextSecurityKey())}'";
                                        cmd.ExecuteNonQuery();
                                    }
                                }

                                // Commands to be run
                                string[] sqlScript =
                                {
                                    $"ATTACH DATABASE '{dbFile}' AS prod_db KEY '{Encoding.UTF8.GetString(ApplicationContext.Current.GetCurrentContextSecurityKey())}'",
                                    "SELECT sqlcipher_export('prod_db')",
                                    "DETACH DATABASE prod_db"
                                };

                                // Attempt to use the existing security key
                                using (var bakConn = new Mono.Data.Sqlite.SqliteConnection($"Data Source={Path.ChangeExtension(dbFile, "old")}"))
                                {
                                    bakConn.Open();
                                    foreach (var sql in sqlScript)
                                    {
                                        using (var cmd = bakConn.CreateCommand())
                                        {
                                            cmd.CommandType = System.Data.CommandType.Text;
                                            cmd.CommandText = sql;
                                            cmd.ExecuteNonQuery();
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                File.Delete(Path.ChangeExtension(dbFile, "old"));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    this.m_tracer.TraceError("Error rekeying database: {0}", e);
                    throw new Exception("Error re-keying databases", e);
                }
        }
Пример #45
0
 public TestDb(ISQLitePlatform sqlitePlatform, String path)
     : base(sqlitePlatform, path)
 {
     TraceListener = DebugTraceListener.Instance;
     CreateTable <TestObj>();
 }
Пример #46
0
        /// <summary>
        /// Backup the database
        /// </summary>
        public string Backup(string passkey)
        {
            // Take the main connection lock
            lock (s_lockObject)
            {
                try
                {
                    var backupDir = Path.Combine(Path.GetTempPath(), "db-copy");
                    if (!Directory.Exists(backupDir))
                    {
                        Directory.CreateDirectory(backupDir);
                    }

                    ISQLitePlatform platform          = ApplicationContext.Current.GetService <ISQLitePlatform>();
                    var             connectionStrings = (ApplicationContext.Current.GetService <IConfigurationManager>()).GetSection <DcDataConfigurationSection>().ConnectionString;

                    for (var i = 0; i < connectionStrings.Count; i++)
                    {
                        var pool = this.GetConnectionPool(connectionStrings[i].Name);
                        //pool.CloseAll();
                        using (pool.Lock()) // Lock the pool
                        {
                            this.m_tracer.TraceInfo("Will backup {0} with passkey {1}", connectionStrings[i].GetComponent("dbfile"), !String.IsNullOrEmpty(passkey));
                            if (!File.Exists(connectionStrings[i].GetComponent("dbfile")))
                            {
                                continue;
                            }

                            var dataFile = connectionStrings[i].GetComponent("dbfile");

                            ApplicationContext.Current.SetProgress(Strings.locale_backup, (float)i / connectionStrings.Count);

                            var backupFile = Path.Combine(backupDir, Path.GetFileName(dataFile));
                            if (File.Exists(backupFile))
                            {
                                File.Delete(backupFile);
                            }
                            // Create empty database
                            this.m_tracer.TraceVerbose("Creating temporary copy of database at {0}...", backupFile);

                            // Create new encrypted database
                            Mono.Data.Sqlite.SqliteConnection.CreateFile(backupFile);
                            using (var prodConn = new Mono.Data.Sqlite.SqliteConnection($"Data Source={backupFile}"))
                            {
                                prodConn.Open();
                                using (var cmd = prodConn.CreateCommand())
                                {
                                    cmd.CommandType = System.Data.CommandType.Text;
                                    cmd.CommandText = $"PRAGMA key = '{passkey}'";
                                    cmd.ExecuteNonQuery();
                                }
                            }

                            // Commands to be run
                            string[] sqlScript =
                            {
                                $"ATTACH DATABASE '{backupFile}' AS bak_db KEY '{passkey}'",
                                "SELECT sqlcipher_export('bak_db')",
                                "DETACH DATABASE bak_db"
                            };

                            // Attempt to use the existing security key
                            using (var bakConn = new Mono.Data.Sqlite.SqliteConnection($"Data Source={dataFile}"))
                            {
                                if (connectionStrings[i].GetComponent("encrypt") == "true")
                                {
                                    bakConn.SetPassword(ApplicationContext.Current.GetCurrentContextSecurityKey());
                                }
                                bakConn.Open();
                                foreach (var sql in sqlScript)
                                {
                                    using (var cmd = bakConn.CreateCommand())
                                    {
                                        cmd.CommandType = System.Data.CommandType.Text;
                                        cmd.CommandText = sql;
                                        cmd.ExecuteNonQuery();
                                    }
                                }
                            }
                        }
                    }

                    return(backupDir);
                }
                catch (Exception e)
                {
                    throw new DataPersistenceException("Error backing up database", e);
                }
            }
        }
Пример #47
0
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Falling rock style!

            #region Setup
            // Setup services and globals for iOS
            // Create iOSCore globals
            this._iOSGlobals = new AspyRoad.iOSCore.AspyGlobals();
            // Create our appwide user setup settings
            //this._numeracyUIManager = new NumeracyUIManager(this.iOSGlobals);
            // Create shared globals
            this._sharedGlobals = new NathansWay.Numeracy.Shared.SharedGlobal();
            // Create our application settings. These are settings that are global to Numbers Application only.
            this._numberAppSettings = new NathansWay.Numeracy.Shared.NWNumberAppSettings();
            // Load our storyboard and setup our UIWindow and first view controller
            _storyBoard = UIStoryboard.FromName("NathansWay.Numeracy", null);
            iOSCoreServiceContainer.Register <UIStoryboard> (_storyBoard);
            // Number factory relies on Storyboard so load it first
            this._NumletFactory = new Lazy <UINumberFactory>(() => new UINumberFactory());

            // Set SharedGlobals for the Shared lib
            // This must be done for each device being built
            this._sharedGlobals.GS__RootAppPath = Environment.CurrentDirectory;
            // Db Name
            this._sharedGlobals.GS__DatabaseName = "Nathansway.db3";
            // Documents folder
            this._sharedGlobals.GS__DocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            // Library folder
            this._sharedGlobals.GS__FolderNameLibrary = Path.Combine(this._sharedGlobals.GS__DocumentsPath, "../Library/");
            // Full db path
            this._sharedGlobals.GS__FullDbPath = Path.Combine(this._sharedGlobals.GS__DocumentsPath, this._sharedGlobals.GS__DatabaseName);
            // Copy the database if needed
            // For building we ALWAYS copy the db as we need to capture build changes.
            //this.CopyDb();
            this.ExplcitCopyDb();

            // Apply user based app settings
            // Depending on student, teahcer etc some of these will change at log in, but we will set defaults here.
            // TODO : These will need to be loaded from a database as they will be different for each student
            // But not all need to be saved?
            this._numberAppSettings.GA__NumberEditMode = G__NumberEditMode.EditNumPad;
            //this._numberAppSettings.GA__NumberEditMode = G__NumberEditMode.EditScroll;
            //this._numberAppSettings.GA__NumberEditMode = G__NumberEditMode.EditUpDown;
            this._numberAppSettings.GA__NumberDisplaySize             = G__DisplaySizeLevels.Level5;
            this._numberAppSettings.GA__NumberLabelDisplaySize        = G__DisplaySizeLevels.Level3;
            this._numberAppSettings.GA__MoveToNextNumber              = true;
            this._numberAppSettings.GA__ShowAnswerNumlet              = true;
            this._numberAppSettings.GA__SingleDigitErrorUIDisplay     = false;
            this._numberAppSettings.GA__PersistUICorrectStateOnMove   = true;
            this._numberAppSettings.GA__PersistUIInCorrectStateOnMove = true;
            this._numberAppSettings.GA__ToStringReturnsCurrentValue   = false;
            this._numberAppSettings.GA__FreeFromModeActive            = false;
            this._numberAppSettings.GA__DecimalPrecission             = 2;

            // Set AspyiOSCore global         variables here....
            this._iOSGlobals.G__ViewAutoResize = UIViewAutoresizing.None;
            this._iOSGlobals.G__InitializeAllViewOrientation = true;
            this._iOSGlobals.G__ViewOrientation           = G__Orientation.Landscape;
            this._iOSGlobals.G__ShouldAutorotate          = false;
            this._iOSGlobals.G__SegueingAnimationDuration = 0.8;
            this._iOSGlobals.G__PrefersStatusBarHidden    = true;

            // Orientation handlers two types depending on iOS version
            // iOS 6 and above >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            this._iOSGlobals.G__6_SupportedOrientationMasks = UIInterfaceOrientationMask.Landscape;
            // You can use bitwise operators on these
            // NOTE : I couldnt get the bitwise versions to compare, not sure why, so I assume that Lanscapeleft and right are the same
            // Doesnt really matter as its only for iOS5.
            // in the autorotate function for iOS5
            // Eg  = UIInterfaceOrientation.LandscapeRight | UIInterfaceOrientation.LandscapeLeft
            // iOS 5 and below >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            this._iOSGlobals.G__5_SupportedOrientation = UIInterfaceOrientation.LandscapeLeft;

            // Register any Shared services needed
            SharedServiceContainer.Register <ISharedGlobal>(this._sharedGlobals);
            // Set Sqlite db Platform
            this._iOSSQLitePLatform = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS();
            // Set up a database context
            this._DbContext = new NumeracyDB(this._iOSSQLitePLatform, this._sharedGlobals.GS__FullDbPath);

            // Platform lib needed by the constructor for SQLite Shared
            SharedServiceContainer.Register <ISQLitePlatform>(this._iOSSQLitePLatform);
            // Register the database connection
            SharedServiceContainer.Register <INWDatabaseContext>(this._DbContext);
            // Register any iOS services needed
            iOSCoreServiceContainer.Register <IAspyGlobals> (this._iOSGlobals);
            // Register our Numberappwide setings
            SharedServiceContainer.Register <IAppSettings> (this._numberAppSettings);

            // Application Services, Factories
            // Dimensions Class
            this._numberDimensions = new iOSNumberDimensions(G__DisplaySizeLevels.Level5, this._iOSGlobals);
            iOSCoreServiceContainer.Register <iOSNumberDimensions> (this._numberDimensions);

            // Build a ToolBoxFactory
            this._toolBuilder = new Lazy <ToolFactory> (() => new ToolFactory());
            iOSCoreServiceContainer.Register <ToolFactory> (this._toolBuilder.Value);

            // Build a NumletFactory
            // Numlets are the most basic workspace, the contain any expression
            // A workspace is made up of one to [n] numlets
            iOSCoreServiceContainer.Register <UINumberFactory> (this._NumletFactory.Value);

            #endregion

            #region Setup UI

            // TODO : Remove and insert this into .ctor code for lesson UI startup
//						// Start a toolfactory
//						ITool hammer;
//						hammer = ToolBuilder.CreateNewTool(E__ToolBoxToolz.Hammerz);
//
//						AspyViewController _vcHammer = hammer.MainGame.Services.GetService<AspyViewController>();
//
//						// Temp workspace setup code. Mormally this will be behind a menu button.
//						vcWorkSpace _workspace = new vcWorkSpace();
//						//vcMainGame _maingame = new vcMainGame();
//						vcMainWorkSpace _mainworkspace = new vcMainWorkSpace();
//
//						ViewContainerController = new AspyViewController();
//						ViewContainerController.AddAndDisplayController(_vcHammer);
//						ViewContainerController.AddAndDisplayController(_mainworkspace);
//						//ViewContainerController.View.AddSubview(_mainworkspace.ChildViewControllers[0].View);
//
//						window.RootViewController = ViewContainerController;
//						//window.RootViewController = _mainworkspace;
            //Setup UIManager
            this.SetUpUI();
            // Setup the window
            _window = new AspyWindow(UIScreen.MainScreen.Bounds);
            // _window = new iOSGameWindow(UIScreen.MainScreen.Bounds);
            // Register our window
            iOSCoreServiceContainer.Register <AspyWindow> (_window);

            // Setup view controllers
            //_mainNavigator = storyboard.InstantiateInitialViewController() as UINavigationController;
            //_mainController = storyboard.InstantiateViewController("vcMainContainer") as vcMainContainer;
            _mainContainer = new vcMainContainer();

            // Use storyboard ids to create VCs
            //_menuStart = new vcMenuStart();
            //_menuStart = storyboard.InstantiateViewController("vcMenuStart") as vcMenuStart;
            //_menuStart = storyboard.InstantiateViewController("vcLessonMenu") as vcLessonMenu;

            //Add our navigation object to the service library
            iOSCoreServiceContainer.Register <vcMainContainer> (_mainContainer);
            // The drawing factory needs to know of MainController hence its position here...after maincontainers creation
            this._drawingFunctions = new DrawingFactory();
            iOSCoreServiceContainer.Register <DrawingFactory>(_drawingFunctions);

            //window.MakeKeyAndVisible();
            _window.RootViewController = _mainContainer;
            //window.RootViewController = _menuStart;
            _window.MakeKeyAndVisible();
            //_mainController.AddAndDisplayController(_menuStart);

            //window.MakeKeyAndVisible();

            #endregion

            return(true);
        }
Пример #48
0
        public static string BackupDatabase(this SQLiteConnection conn, ISQLitePlatform platform, string folderName = null)
        {
            ISQLiteApiExt sqliteApi = platform.SQLiteApi as ISQLiteApiExt;

            if (sqliteApi == null)
            {
                return(null);
            }

            string additionalPath = string.Empty;

            if (!string.IsNullOrEmpty(folderName))
            {
                ApplicationData.Current?.LocalFolder.CreateFolderAsync(folderName, CreationCollisionOption.FailIfExists);
                //  if (asyncOperation != null)
                //      await asyncOperation;
                additionalPath = "\\" + folderName;
            }

            string destDbPath = ApplicationData.Current?.LocalFolder.Path + additionalPath + "\\db." + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss");

            IDbHandle destDb;

            byte[] databasePathAsBytes = GetNullTerminatedUtf8(destDbPath);
            Result r = sqliteApi.Open(databasePathAsBytes, out destDb,
                                      (int)(SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite), IntPtr.Zero);

            if (r != Result.OK)
            {
                throw SQLiteException.New(r, String.Format("Could not open backup database file: {0} ({1})", destDbPath, r));
            }

            /* Open the backup object used to accomplish the transfer */
            IDbBackupHandle bHandle = sqliteApi.BackupInit(destDb, "main", conn.Handle, "main");


            if (bHandle == null)
            {
                // Close the database connection
                sqliteApi.Close(destDb);

                throw SQLiteException.New(r, String.Format("Could not initiate backup process: {0}", destDbPath));
            }

            /* Each iteration of this loop copies 5 database pages from database
            ** pDb to the backup database. If the return value of backup_step()
            ** indicates that there are still further pages to copy, sleep for
            ** 250 ms before repeating. */
            do
            {
                r = sqliteApi.BackupStep(bHandle, 5);

                if (r == Result.OK || r == Result.Busy || r == Result.Locked)
                {
                    sqliteApi.Sleep(250);
                }
            } while (r == Result.OK || r == Result.Busy || r == Result.Locked);

            /* Release resources allocated by backup_init(). */
            r = sqliteApi.BackupFinish(bHandle);

            if (r != Result.OK)
            {
                // Close the database connection
                sqliteApi.Close(destDb);

                throw SQLiteException.New(r, String.Format("Could not finish backup process: {0} ({1})", destDbPath, r));
            }

            // Close the database connection
            sqliteApi.Close(destDb);

            return(destDbPath);
        }
Пример #49
0
 public SQLiteConnectionWithLock(ISQLitePlatform sqlitePlatform, SQLiteConnectionString connectionString)
     : base(sqlitePlatform, connectionString.DatabasePath, connectionString.StoreDateTimeAsTicks, connectionString.Serializer)
 {
 }
Пример #50
0
 /// <summary>
 /// Constructor for locable sqlite connection
 /// </summary>
 public LockableSQLiteConnection(ISQLitePlatform sqlitePlatform, String databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true, IBlobSerializer serializer = null, IDictionary <String, TableMapping> tableMappings = null, IDictionary <Type, String> extraTypeMappings = null, IContractResolver resolver = null) :
     base(sqlitePlatform, databasePath, openFlags, storeDateTimeAsTicks, serializer, tableMappings, extraTypeMappings, resolver, ApplicationContext.Current.GetCurrentContextSecurityKey())
 {
 }
 internal PreparedSqlLiteInsertCommand(ISQLitePlatform platformImplementation, SQLiteConnection conn)
 {
     _sqlitePlatform = platformImplementation;
     Connection = conn;
 }
        public PersonRepository(ISQLitePlatform sqlitePlatform, string dbPath)
        {
            //add code to initialize a new SQLiteConnection

            //add code to create the Person table
        }
 public UserAccountDatabase(ISQLitePlatform platform, string dblocation)
 {
     Platform = platform;
     DbLocation = dblocation;
 }
Пример #54
0
 public SQLiteSetup(ISQLitePlatform platform)
 {
     DatabasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "filestorage.db3");;
     Platform     = platform;
 }
Пример #55
0
 public ConferenceViewModel(ISQLitePlatform sqlite)
 {
     _sqliteClient = new SQLiteClient(sqlite);
 }
Пример #56
0
 private TableQuery(ISQLitePlatform platformImplementation, SQLiteConnection conn, TableMapping table)
 {
     _sqlitePlatform = platformImplementation;
     Connection      = conn;
     Table           = table;
 }
Пример #57
0
 public SampleDbConnection(ISQLitePlatform sqlitePlatform, string path)
     : base(sqlitePlatform, new SQLiteConnectionString(Path.Combine(path, "Samples.db"), true))
 {
     this.CreateTable<GeofenceEvent>();
 }
Пример #58
0
 public TableQuery(ISQLitePlatform platformImplementation, SQLiteConnection conn)
 {
     _sqlitePlatform = platformImplementation;
     Connection      = conn;
     Table           = Connection.GetMapping(typeof(T));
 }
		public MyDatabase(ISQLitePlatform platform, string dbfile, string saltText) : base(platform, dbfile, saltText)
		{
		}
Пример #60
0
 /// <summary>
 /// Construct a new instance of SecureDatabase.
 /// </summary>
 /// <param name="platform">The platform specific engine of SQLite (ISQLitePlatform)</param>
 /// <param name="dbfile">The sqlite db file path</param>
 protected SecureDatabase(ISQLitePlatform platform, string dbfile) : this(platform, dbfile, new CryptoService())
 {
 }