示例#1
0
        /// <summary>
        /// Load the database from disk
        /// </summary>
        /// <param name="requireLock">True if a lock needs to be acquired before saving</param>
        /// <returns></returns>
        private async Task LoadDatabaseAsync(bool requireLock = true)
        {
            if (File.Exists(_config.Filename))
            {
                if (requireLock)
                {
                    await _dataLock.WaitAsync();
                }
                try
                {
                    using (var stream = File.OpenRead(_config.Filename))
                    {
                        var dbVersion = ReadDbVersion(stream);

                        // copy the rest of the bytes
                        var bytes = new byte[stream.Length - stream.Position];
                        stream.Read(bytes, 0, bytes.Length);

                        _db   = LoadDatabaseByVersion(dbVersion, bytes);
                        bytes = null;

                        // could make this non-fatal
                        if (!ValidateChecksum(_db))
                        {
                            throw new Exception("The database did not pass validation! It is either corrupt or has been modified outside of the application.");
                        }
                        _primaryKeyTracker = new PrimaryKeyTracker(new Dictionary <string, long>
                        {
                            // there is no guaranteed order so we must sort first
                            { typeof(Part).Name, _db.Parts.OrderByDescending(x => x.PartId).Select(x => x.PartId).FirstOrDefault() },
                            { typeof(PartType).Name, _db.PartTypes.OrderByDescending(x => x.PartTypeId).Select(x => x.PartTypeId).FirstOrDefault() },
                        });
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to load database!", ex);
                }
                finally
                {
                    if (requireLock)
                    {
                        _dataLock.Release();
                    }
                }
            }
            else
            {
                if (requireLock)
                {
                    await _dataLock.WaitAsync();
                }
                try
                {
                    _db = NewDatabase();
                }
                finally
                {
                    if (requireLock)
                    {
                        _dataLock.Release();
                    }
                }
            }
        }