private void InsertData(IDbConnection db, int count)
 {
     for (var i = 0; i < count; i++)
     {
         var data = new CompositeKey {SubId1 = SubId1Value, SubId2 = SubId2Value, Data = Guid.NewGuid().ToString()};
         db.Insert(data);
     }
 }
                // <summary>
                // Construct a new placeholder with the shape of the given placeholder. Key values are
                // injected into the resulting place holder and default values are substituted with
                // either propagator constants or progagator nulls depending on the mode established
                // by the <paramref name="mode" /> flag.
                // </summary>
                // <remarks>
                // The key is essentially an array of values. The key map indicates that for a particular
                // placeholder an expression (keyMap.Keys) corresponds to some ordinal in the key array.
                // </remarks>
                // <param name="placeholder"> Placeholder to clone </param>
                // <param name="key"> Key to substitute </param>
                // <param name="placeholderKey"> Key elements in the placeholder (ordinally aligned with 'key') </param>
                // <param name="mode"> Mode of operation. </param>
                // <returns> Cloned placeholder with key values </returns>
                internal static PropagatorResult Populate(
                    PropagatorResult placeholder, CompositeKey key,
                    CompositeKey placeholderKey, PopulateMode mode)
                {
                    DebugCheck.NotNull(placeholder);
                    DebugCheck.NotNull(key);
                    DebugCheck.NotNull(placeholderKey);

                    // Figure out which flags to apply to generated elements.
                    var isNull = mode == PopulateMode.NullModified || mode == PopulateMode.NullPreserve;
                    var preserve = mode == PopulateMode.NullPreserve || mode == PopulateMode.Unknown;
                    var flags = PropagatorFlags.NoFlags;
                    if (!isNull)
                    {
                        flags |= PropagatorFlags.Unknown;
                    } // only null values are known
                    if (preserve)
                    {
                        flags |= PropagatorFlags.Preserve;
                    }

                    var result = placeholder.Replace(
                        node =>
                            {
                                // See if this is a key element
                                var keyIndex = -1;
                                for (var i = 0; i < placeholderKey.KeyComponents.Length; i++)
                                {
                                    if (placeholderKey.KeyComponents[i] == node)
                                    {
                                        keyIndex = i;
                                        break;
                                    }
                                }

                                if (keyIndex != -1)
                                {
                                    // Key value.
                                    return key.KeyComponents[keyIndex];
                                }
                                else
                                {
                                    // for simple entries, just return using the markup context for this
                                    // populator
                                    var value = isNull ? null : node.GetSimpleValue();
                                    return PropagatorResult.CreateSimpleValue(flags, value);
                                }
                            });

                    return result;
                }
示例#3
0
        public SerializedEntity ReadObject(Dictionary <string, object> keys, TableSchema schema)
        {
            using (var bucket = GetBucket(schema))
            {
                var compositeKey = new CompositeKey(keys);

                if (!bucket.IndexedObjects.ContainsKey(compositeKey))
                {
                    return(null);
                }

                var storedObject = bucket.IndexedObjects[compositeKey];

                return(new SerializedEntity(storedObject));
            }
        }
        public void Setup()
        {
            var fullDatabasePath = Path.Combine(TestContext.CurrentContext.TestDirectory, Path.Combine(databaseDirectory, databaseFileName));

            Assert.IsTrue(File.Exists(fullDatabasePath));
            var ioConnectionInfo = new IOConnectionInfo()
            {
                Path = fullDatabasePath
            };

            var key = new CompositeKey();

            key.AddUserKey(new KcpPassword(databasePassword));

            this.pwDatabase = new PwDatabase();
            this.pwDatabase.Open(ioConnectionInfo, key, null);
        }
        public void struct_key_checked_only_for_content_not_address()
        {
            int a = 1;
            string b = "dire";
            object c = new object();

            var key1 = new CompositeKey() { Key1 = a, Key2 = b, Key3 = c };
            var key2 = new CompositeKey() { Key1 = a, Key2 = b, Key3 = c };
            var key3 = new CompositeKey() { Key1 = 2, Key2 = b, Key3 = c };

            var dict = new Dictionary<CompositeKey, string>();
            dict.Add(key1, "straits");

            Assert.IsTrue(dict.ContainsKey(key1));
            Assert.IsTrue(dict.ContainsKey(key2));
            Assert.IsFalse(dict.ContainsKey(key3));
        }
        public void CacheKeyForDB(string databasePath, CompositeKey keys)
        {
            Contract.Requires(!string.IsNullOrEmpty(databasePath));
            Contract.Requires(keys != null);
            Contract.Requires(WinHello.IsAvailable());

            var validPeriod = KeePassWinHelloExt.Host.CustomConfig.GetULong(CfgValidPeriod, VALID_DEFAULT);

            lock (_unlockCache)
            {
                _unlockCache[databasePath] = new WinHelloData
                {
                    ValidUntil  = validPeriod == VALID_UNLIMITED ? DateTime.MaxValue : DateTime.Now.AddSeconds(validPeriod),
                    ComposedKey = Encrypt(keys),
                };
            }
        }
示例#7
0
        public IKeePassService Open()
        {
            //TODO add support for composite database keys
            if (KeePassPasswordProvider.RetrievePassword() == null)
            {
                throw new ArgumentNullException("password", "Password provided by IKeePassPasswordValueProvider is not set. Please register Password before calling Open().");
            }

            var io           = IOConnectionInfo.FromPath(Configuration.Path);
            var masterpass   = new KcpPassword(KeePassPasswordProvider.RetrievePassword().ConvertToUnsecureString());
            var compositeKey = new CompositeKey();

            compositeKey.AddUserKey(masterpass);
            _database = new PwDatabase();
            _database.Open(io, compositeKey, new NullStatusLogger());
            return(this);
        }
        public void GetOne()
        {
            var Cxt = new VendsRepository(connexion);

            var vente = new Vends
            {
                DateVente    = new DateTime(),
                IdPermaFungi = 1,
                IdProduit    = 2
            };

            CompositeKey <int, int> id = new CompositeKey <int, int> {
                PK1 = 2, PK2 = 2
            };

            Assert.IsNotNull(Cxt.GetOne(id));
        }
        /// <summary>
        /// updates the row in the index, if the index values have not
        /// changed then no-op. if values have changed old is removed
        /// and new is added
        /// </summary>
        /// <param name="row"></param>
        /// <param name="removedDetached"></param>
        private void UpdateDataRowInIndex(DataRow row, bool removedDetached, bool isRollback)
        {
            CompositeKey key;

            // This will commit any changes made when the parent row changed.  Note that the mapping element is removed when a
            // deleted row is committed.
            if (isRollback == true ||
                (removedDetached == true &&
                 (row.RowState == DataRowState.Detached ||
                  row.RowState == DataRowState.Deleted)))
            {
                //if the row is detached (probably from commit) and param set
                //just remove the row when it is detached
                this.DeleteDataRowFromIndex(row);
                return;
            }

            //check if key is is the same and in the map
            if (this.dataRowToKeyMap.TryGetValue(row, out key))
            {
                CompositeKey newKey = this.GetDataRowCompositeKey(row);
                if (newKey != null &&
                    newKey.Equals(key))
                {
                    return;
                }

                //created the key so set Key to it so dont need to create another one
                key = newKey;
            }
            else if (key == null)
            {
                //not in the map create a new key
                key = this.GetDataRowCompositeKey(row);
            }

            //get rid of the old
            this.DeleteDataRowFromIndex(row);

            //if there is a valid key add
            if (key != null)
            {
                this.dataRowToKeyMap.Add(row, key);
                this.keyToDataRowMap.Add(key, row);
            }
        }
示例#10
0
        /// <summary>
        /// Unlocks the database using KeyPromptForm
        /// </summary>
        internal static void Unlock(KeyPromptForm keyPromptForm, CompositeKey compositeKey)
        {
            try
            {
                var fieldInfo = keyPromptForm.GetType().GetField("m_pKey", BindingFlags.Instance | BindingFlags.NonPublic);
                if (fieldInfo != null)
                {
                    fieldInfo.SetValue(keyPromptForm, compositeKey);
                }
                //keyPromptForm.Visible = false;
                //keyPromptForm.Opacity = 1;

                keyPromptForm.DialogResult = DialogResult.OK;
                keyPromptForm.Close();
            }
            catch (Exception) { }
        }
        public void Setup()
        {
            var path = Path.Combine(Path.GetFullPath(databaseFilePath), databaseFileName);

            Assert.IsTrue(File.Exists(path));
            var ioConnectionInfo = new IOConnectionInfo()
            {
                Path = path
            };

            var key = new CompositeKey();

            key.AddUserKey(new KcpPassword(databasePassword));

            this.pwDatabase = new PwDatabase();
            this.pwDatabase.Open(ioConnectionInfo, key, null);
        }
示例#12
0
文件: CreateDB.cs 项目: 77rusa/README
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.progress_create);
            Database db = _app.CreateNewDatabase(_makeCurrent);

            db.KpDatabase = new KeePassLib.PwDatabase();

            if (_key == null)
            {
                _key = new CompositeKey();                 //use a temporary key which should be changed after creation
            }

            db.KpDatabase.New(_ioc, _key, _app.GetFileStorage(_ioc).GetFilenameWithoutPathAndExt(_ioc));

            db.KpDatabase.KdfParameters = (new AesKdf()).GetDefaultParameters();
            db.KpDatabase.Name          = "Keepass2Android Password Database";
            //re-set the name of the root group because the PwDatabase uses UrlUtil which is not appropriate for all file storages:
            db.KpDatabase.RootGroup.Name = _app.GetFileStorage(_ioc).GetFilenameWithoutPathAndExt(_ioc);

            // Set Database state
            db.Root         = db.KpDatabase.RootGroup;
            db.SearchHelper = new SearchDbHelper(_app);

            // Add a couple default groups
            AddGroup internet = AddGroup.GetInstance(_ctx, _app, "Internet", 1, null, db.KpDatabase.RootGroup, null, true);

            internet.Run();
            AddGroup email = AddGroup.GetInstance(_ctx, _app, "eMail", 19, null, db.KpDatabase.RootGroup, null, true);

            email.Run();

            List <PwEntry>     addedEntries;
            AddTemplateEntries addTemplates = new AddTemplateEntries(_ctx, _app, null);

            addTemplates.AddTemplates(out addedEntries);

            // Commit changes
            SaveDb save = new SaveDb(_ctx, _app, db, OnFinishToRun, _dontSave);

            save.SetStatusLogger(StatusLogger);
            _onFinishToRun = null;
            save.Run();

            db.UpdateGlobals();
        }
示例#13
0
        /// <summary>
        /// Creates the data for WinHelloUnlock to work.
        /// 1. A Key Credential to sign a cryptographic key.
        /// 2. A Password vault to save the data into
        /// 3. A Password Credential in which to save the encrypted data (using the signed cryptographic key).
        /// </summary>
        /// <param name="dbPath">Database path. This is the identity of the database, if Database is moved or renamed,
        /// WinHelloUnlock will not work and new data needs to be created.
        /// </param>
        /// <returns>True if all the data was saved successfully.</returns>
        internal static async Task <bool> CreateHelloData(string dbPath)
        {
            bool isHelloAvailable = await UWPLibrary.IsHelloAvailable();

            if (isHelloAvailable)
            {
                KeyCredentialCreationOption  optionNew       = KeyCredentialCreationOption.ReplaceExisting;
                KeyCredentialRetrievalResult retrievalResult = await UWPLibrary.CreateCredential(dbPath, optionNew);

                if (retrievalResult.Status == KeyCredentialStatus.Success)
                {
                    KeyList keyList    = Library.GetKeys(WinHelloUnlockExt.database);
                    string  resultSave = await UWPLibrary.SaveKeys(dbPath, keyList, retrievalResult);

                    if (resultSave == "Success")
                    {
                        MessageService.ShowInfo("Database Keys saved successfuly");
                        UWPLibrary.ck = KeePass.Program.MainForm.ActiveDatabase.MasterKey;
                        return(true);
                    }
                    else
                    {
                        if (resultSave.Substring(0, 20) == "Value cannot be null")
                        {
                            MessageService.ShowWarning("Error saving the composite key: MasterKey was null." +
                                                       " Verify that \"Remember master password (in encrypted form) of a database while it is open\" option under Tools/Options/Security" +
                                                       " is enabled, then lock and unlock the database.");
                        }
                        else
                        {
                            MessageService.ShowWarning("Error saving the composite key: " + resultSave);
                        }
                    }
                }
                else
                {
                    WinHelloErrors(retrievalResult.Status, "Error creating the credential: ");
                }
            }
            else
            {
                MessageService.ShowWarning("Windows Hello is NOT Available");
            }
            return(false);
        }
        /// <inheritdoc />
        public TValue GetValue(TId id, TName name)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            var key = new CompositeKey(id, name);

            if (!_internalStore.ContainsKey(key))
            {
                throw new KeyNotFoundException($"Словарь не содержит указанный ключ {key}.");
            }
            return(_internalStore[key]);
        }
示例#15
0
        /// <summary>
        /// Opens a create new password dialog
        /// </summary>
        /// <returns></returns>
        public CompositeKey GetNewDualPassword()
        {
            CompositeKey newPwd = null;
            PasswordFrm  f      = new PasswordFrm(true);

            f.AlgoLabel = GetAlgoLabel();
            DialogResult dr = f.ShowDialog();

            if (dr == DialogResult.OK)
            {
                newPwd         = f.Password;
                m_DualPassword = newPwd;
            }

            UIUtil.DestroyForm(f);

            return(newPwd);
        }
        /// <inheritdoc />
        public bool TryGetValue(TId id, TName name, out TValue value)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            var key = new CompositeKey(id, name);

            if (_internalStore.TryGetValue(key, out value))
            {
                return(true);
            }
            return(false);
        }
        /// <summary>Adds a database-key mapping.</summary>
        /// <param name="databasePath">Full path of the database file.</param>
        /// <param name="pin">The pin to unlock the database.</param>
        /// <param name="keys">The keys used to encrypt the database.</param>
        public void AddCachedKey(string databasePath, ProtectedString pin, CompositeKey keys)
        {
            Contract.Requires(!string.IsNullOrEmpty(databasePath));
            Contract.Requires(pin != null);
            Contract.Requires(keys != null);

            var validPeriod = KeePassQuickUnlockExt.Host.CustomConfig.GetULong(CfgValidPeriod, VALID_DEFAULT);

            lock (unlockCache)
            {
                unlockCache[databasePath] = new QuickUnlockData
                {
                    ValidUntil  = validPeriod == VALID_UNLIMITED ? DateTime.MaxValue : DateTime.Now.AddSeconds(validPeriod),
                    UnlockKey   = pin.WithProtection(true),
                    ComposedKey = keys.CombineKeys()
                };
            }
        }
        public virtual TData this[TKey1 key1, TKey2 key2]
        {
            get
            {
                if (key1 == null && key2 == null)
                {
                    throw new ArgumentNullException("key1 and key2", "Key should not be nullable");
                }

                return(_compositeKeyCollection[key1, key2]);
            }
            set
            {
                CheckKeyParameters(key1, key2);
                var key = new CompositeKey <TKey1, TKey2>(key1, key2);
                SetValue(key, value);
            }
        }
示例#19
0
        public ProtectedKey(CompositeKey compositeKey, KeyCipher keyCipher)
        {
            var password = keyCipher.GeneratePassword();

            _protectedPassword = keyCipher.Protect(password);
            _keys = new List <KcpData>();

            foreach (var key in compositeKey.UserKeys)
            {
                KcpData data;

                var p  = key as KcpPassword;
                var kf = key as KcpKeyFile;
                var ck = key as KcpCustomKey;

                if (p != null)
                {
                    if (p.Password != null)
                    {
                        data = new KcpData(KcpType.kcpPassword, keyCipher.Encrypt(p.Password, password));
                    }
                    else
                    {
                        data = new KcpData(KcpType.kcpCustomKey, keyCipher.Encrypt(p.KeyData, password), p.ToString());
                    }
                }
                else if (kf != null)
                {
                    data = new KcpData(KcpType.kcpKeyFile, keyCipher.Encrypt(new ProtectedString(false, kf.Path), password));
                }
                else if (key is KcpUserAccount)
                {
                    data = new KcpData(KcpType.kcpUserAccount);
                }
                else
                {
                    Debug.Assert(ck != null, "Unknown key type");
                    var name = ck != null ? ck.Name : key.ToString();
                    data = new KcpData(KcpType.kcpCustomKey, keyCipher.Encrypt(key.KeyData, password), name);
                }

                _keys.Add(data);
            }
        }
示例#20
0
        private static KdbErrorCode SetDatabaseKey(KdbManager mgr, CompositeKey pwKey)
        {
            string strPassword = null;

            if (pwKey.ContainsType(typeof(KcpPassword)))
            {
                KcpPassword     p  = (pwKey.GetUserKey(typeof(KcpPassword)) as KcpPassword);
                ProtectedString ps = ((p != null) ? p.Password : null);
                if (ps == null)
                {
                    throw new Exception(KPRes.OptionReqOn + @" '" +
                                        KPRes.MasterPasswordRmbWhileOpen + @"'.");
                }
                strPassword = ps.ReadString();
            }

            string strKeyFile = null;

            if (pwKey.ContainsType(typeof(KcpKeyFile)))
            {
                strKeyFile = (pwKey.GetUserKey(typeof(KcpKeyFile)) as KcpKeyFile).Path;
            }

            KdbErrorCode e;

            if (!string.IsNullOrEmpty(strKeyFile))
            {
                e = mgr.SetMasterKey(strKeyFile, true, strPassword, IntPtr.Zero, false);
            }
            else if (strPassword != null)
            {
                e = mgr.SetMasterKey(strPassword, false, null, IntPtr.Zero, false);
            }
            else if (pwKey.ContainsType(typeof(KcpUserAccount)))
            {
                throw new Exception(KPRes.KdbWUA);
            }
            else
            {
                throw new Exception(KLRes.InvalidCompositeKey);
            }

            return(e);
        }
示例#21
0
        private bool ExtractCompositeKey(string dbPath, out CompositeKey compositeKey)
        {
            compositeKey = null;

            if (String.IsNullOrEmpty(dbPath))
            {
                return(false);
            }

            ProtectedKey encryptedData;

            if (!_keyStorage.TryGetValue(dbPath, out encryptedData))
            {
                return(false);
            }

            try
            {
                using (AuthProviderUIContext.With(Settings.DecryptConfirmationMessage, _keePassMainWindowHandle))
                {
                    compositeKey = encryptedData.GetCompositeKey(_keyCipher);
                    return(true);
                }
            }
            catch (AuthProviderInvalidKeyException)
            {
                // The key might be compromised so we revoke all stored passwords
                ClaimCurrentCacheType(AuthCacheType.Local);
                throw;
            }
            catch (AuthProviderUserCancelledException)
            {
                if (Settings.Instance.RevokeOnCancel)
                {
                    _keyStorage.Remove(dbPath);
                }
                throw;
            }
            catch (Exception)
            {
                _keyStorage.Remove(dbPath);
                throw;
            }
        }
示例#22
0
        /// <summary>
        /// Open a database. The URL may point to any supported data source.
        /// </summary>
        /// <param name="ioSource">IO connection to load the database from.</param>
        /// <param name="pwKey">Key used to open the specified database.</param>
        /// <param name="slLogger">Logger, which gets all status messages.</param>
        public void Open(IOConnectionInfo ioSource, CompositeKey pwKey,
                         IStatusLogger slLogger)
        {
            Debug.Assert(ioSource != null);
            if (ioSource == null)
            {
                throw new ArgumentNullException("ioSource");
            }
            Debug.Assert(pwKey != null);
            if (pwKey == null)
            {
                throw new ArgumentNullException("pwKey");
            }

            this.Close();

            try
            {
                m_pgRootGroup = new PwGroup(true, true, UrlUtil.StripExtension(
                                                UrlUtil.GetFileName(ioSource.Path)), PwIcon.FolderOpen);
                m_pgRootGroup.IsExpanded = true;

                m_pwUserKey = pwKey;

                m_bModified = false;

                Kdb4File kdb4 = new Kdb4File(this);
                Stream   s    = IOConnection.OpenRead(ioSource);
                kdb4.Load(s, Kdb4Format.Default, slLogger);
                s.Close();

                m_pbHashOfLastIO     = kdb4.HashOfFileOnDisk;
                m_pbHashOfFileOnDisk = kdb4.HashOfFileOnDisk;
                Debug.Assert(m_pbHashOfFileOnDisk != null);

                m_bDatabaseOpened = true;
                m_ioSource        = ioSource;
            }
            catch (Exception)
            {
                this.Clear();
                throw;
            }
        }
示例#23
0
        public void Open_With_KeyFile_Test()
        {
            IFolder folder   = SpecialFolder.Current.Local;
            IFolder testData = folder.CreateFolderAsync("TestData",
                                                        CreationCollisionOption.OpenIfExists).Result;
            IFile keyFile = testData.CreateFileAsync("1.key",
                                                     CreationCollisionOption.ReplaceExisting).Result;
            var fileStream = keyFile.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result;
            var assembly   = typeof(PwDatabaseTests).GetTypeInfo().Assembly;
            var stream     = assembly.GetManifestResourceStream(
                "KeePass2PCL.Test.UWP.TestData.1.key");

            using (var reader = new BinaryReader(stream))
                using (var fileWriter = new BinaryWriter(fileStream))
                {
                    fileWriter.Write(reader.ReadBytes((int)stream.Length));
                }

            IFile file = testData.CreateFileAsync("1key.kdbx",
                                                  CreationCollisionOption.ReplaceExisting).Result;

            fileStream = file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result;
            assembly   = typeof(PwDatabaseTests).GetTypeInfo().Assembly;
            stream     = assembly.GetManifestResourceStream(
                "KeePass2PCL.Test.UWP.TestData.1key.kdbx");
            using (var reader = new BinaryReader(stream))
                using (var fileWriter = new BinaryWriter(fileStream))
                {
                    fileWriter.Write(reader.ReadBytes((int)stream.Length));
                }

            var ci = new IOConnectionInfo();

            ci.Path = file.Path;
            var key = new CompositeKey();

            key.AddUserKey(new KcpKeyFile(keyFile.Path));
            var db = new PwDatabase();

            db.Open(ci, key, null);
            keyFile.DeleteAsync().Wait();
            file.DeleteAsync().Wait();
            testData.DeleteAsync().Wait();
        }
示例#24
0
		public void SetKeySources(IOConnectionInfo iocDb, CompositeKey cmpKey)
		{
			string strID = GetKeyAssocID(iocDb);
			int idx = GetKeyAssocIndex(strID);

			if((cmpKey == null) || !m_bRememberKeySources)
			{
				if(idx >= 0) m_vKeySources.RemoveAt(idx);
				return;
			}

			AceKeyAssoc a = new AceKeyAssoc();
			a.DatabasePath = strID;

			IUserKey kcpFile = cmpKey.GetUserKey(typeof(KcpKeyFile));
			if(kcpFile != null)
			{
				string strKeyFile = ((KcpKeyFile)kcpFile).Path;
				if(!string.IsNullOrEmpty(strKeyFile) && !StrUtil.IsDataUri(strKeyFile))
				{
					if(!UrlUtil.IsAbsolutePath(strKeyFile))
						strKeyFile = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(),
							strKeyFile);

					a.KeyFilePath = strKeyFile;
				}
			}

			IUserKey kcpCustom = cmpKey.GetUserKey(typeof(KcpCustomKey));
			if(kcpCustom != null)
				a.KeyProvider = ((KcpCustomKey)kcpCustom).Name;

			IUserKey kcpUser = cmpKey.GetUserKey(typeof(KcpUserAccount));
			a.UserAccount = (kcpUser != null);

			bool bAtLeastOne = ((a.KeyFilePath.Length > 0) ||
				(a.KeyProvider.Length > 0) || a.UserAccount);
			if(bAtLeastOne)
			{
				if(idx >= 0) m_vKeySources[idx] = a;
				else m_vKeySources.Add(a);
			}
			else if(idx >= 0) m_vKeySources.RemoveAt(idx);
		}
                /// <summary>
                /// Construct a new placeholder with the shape of the given placeholder. Key values are
                /// injected into the resulting place holder and default values are substituted with
                /// either propagator constants or progagator nulls depending on the mode established
                /// by the <paramref name="mode"/> flag.
                /// </summary>
                /// <remarks>
                /// The key is essentially an array of values. The key map indicates that for a particular
                /// placeholder an expression (keyMap.Keys) corresponds to some ordinal in the key array.
                /// </remarks>
                /// <param name="placeholder">Placeholder to clone</param>
                /// <param name="key">Key to substitute</param>
                /// <param name="placeholderKey">Key elements in the placeholder (ordinally aligned with 'key')</param>
                /// <param name="mode">Mode of operation.</param>
                /// <param name="translator">Translator context.</param>
                /// <returns>Cloned placeholder with key values</returns>
                internal static PropagatorResult Populate(PropagatorResult placeholder, CompositeKey key, 
                    CompositeKey placeholderKey, PopulateMode mode, UpdateTranslator translator)
                {
                    EntityUtil.CheckArgumentNull(placeholder, "placeholder");
                    EntityUtil.CheckArgumentNull(key, "key");
                    EntityUtil.CheckArgumentNull(placeholderKey, "placeholderKey");
                    EntityUtil.CheckArgumentNull(translator, "translator");

                    // Figure out which flags to apply to generated elements.
                    bool isNull = mode == PopulateMode.NullModified || mode == PopulateMode.NullPreserve;
                    bool preserve = mode == PopulateMode.NullPreserve || mode == PopulateMode.Unknown;
                    PropagatorFlags flags = PropagatorFlags.NoFlags;
                    if (!isNull) { flags |= PropagatorFlags.Unknown; } // only null values are known
                    if (preserve) { flags |= PropagatorFlags.Preserve; }

                    PropagatorResult result = placeholder.Replace(node =>
                        {
                            // See if this is a key element
                            int keyIndex = -1;
                            for (int i = 0; i < placeholderKey.KeyComponents.Length; i++)
                            {
                                if (placeholderKey.KeyComponents[i] == node)
                                {
                                    keyIndex = i;
                                    break;
                                }
                            }

                            if (keyIndex != -1)
                            {
                                // Key value.
                                return key.KeyComponents[keyIndex];
                            }
                            else
                            {
                                // for simple entries, just return using the markup context for this
                                // populator
                                object value = isNull ? null : node.GetSimpleValue();
                                return PropagatorResult.CreateSimpleValue(flags, value);
                            }
                        });
                    
                    return result;
                }
            /// <summary>
            /// Determines whether two specified CompositeKey objects have the same values
            /// </summary>
            /// <param name="obj">other object to compare to this</param>
            /// <returns>true if values equal</returns>
            public override bool Equals(object obj)
            {
                if (!(obj is CompositeKey))
                {
                    return(false);
                }

                //ref check is quick so try that first
                if (object.ReferenceEquals(this, obj))
                {
                    return(true);
                }

                CompositeKey other = (CompositeKey)obj;

                if (other.hashCode != this.hashCode ||
                    other.valueAr.Length != this.valueAr.Length)
                {
                    return(false);
                }

                for (int i = 0; i < this.valueAr.Length; i++)
                {
                    object curVal      = this.valueAr[i];
                    object curOtherVal = other.valueAr[i];

                    if (curVal == null)
                    {
                        if (curOtherVal != null)
                        {
                            return(false);
                        }

                        continue;
                    }
                    if (curVal.Equals(curOtherVal) == false)
                    {
                        return(false);
                    }
                }

                return(true);
            }
示例#27
0
        public void DifferentObjectEqualTest()
        {
            var firstObject = new CompositeKey <UserTypeA, UserTypeB>(new UserTypeA {
                UserId = 1, UserName = "******"
            }, new UserTypeB {
                Level = "123456", FriendlyUserTypeA = new UserTypeA {
                    UserId = 3, UserName = "******"
                }
            });
            var secondObject = new CompositeKey <UserTypeA, UserTypeB>(new UserTypeA {
                UserId = 2, UserName = "******"
            }, new UserTypeB {
                Level = "12345", FriendlyUserTypeA = new UserTypeA {
                    UserId = 4, UserName = "******"
                }
            });

            Assert.That(firstObject.Equals(secondObject), Is.False);
        }
        public IAsyncQueryResultsEnumerable <IKeyValue> GetStateByRangeWithPaginationAsync(string startKey, string endKey, int pageSize, string bookmark)
        {
            if (string.IsNullOrEmpty(startKey))
            {
                startKey = UNSPECIFIED_KEY;
            }
            if (string.IsNullOrEmpty(endKey))
            {
                endKey = UNSPECIFIED_KEY;
            }

            CompositeKey.ValidateSimpleKeys(startKey, endKey);

            QueryMetadata queryMetadata = new QueryMetadata {
                Bookmark = bookmark, PageSize = pageSize
            };

            return(ExecuteGetStateByRangeWithMetadata("", startKey, endKey, queryMetadata.ToByteString()));
        }
示例#29
0
        public void DifferentObjectGetHashCodeTest()
        {
            var firstObject = new CompositeKey <UserTypeA, UserTypeB>(new UserTypeA {
                UserId = 1, UserName = "******"
            }, new UserTypeB {
                Level = "123456", FriendlyUserTypeA = new UserTypeA {
                    UserId = 3, UserName = "******"
                }
            });
            var secondObject = new CompositeKey <UserTypeA, UserTypeB>(new UserTypeA {
                UserId = 2, UserName = "******"
            }, new UserTypeB {
                Level = "12345", FriendlyUserTypeA = new UserTypeA {
                    UserId = 4, UserName = "******"
                }
            });

            Assert.That(firstObject.GetHashCode() != secondObject.GetHashCode());
        }
示例#30
0
        public void TestGenerateKey32()
        {
            var originalKey = new byte[32];
            var expectedKey = new byte[32] {
                0xF0, 0xED, 0x57, 0xD5, 0xF0, 0xDA, 0xF3, 0x47,
                0x90, 0xD0, 0xDB, 0x43, 0x25, 0xC6, 0x81, 0x2C,
                0x81, 0x6A, 0x0D, 0x94, 0x96, 0xA9, 0x03, 0xE1,
                0x20, 0xD4, 0x3A, 0x3E, 0x45, 0xAD, 0x02, 0x65
            };
            const ulong rounds = 1;

            var composite = new CompositeKey();
            var key       = composite.GenerateKey32(originalKey, rounds);

            Assert.That(key, Is.Not.Null);
            var keyData = key.ReadData();

            Assert.That(keyData, Is.EqualTo(expectedKey));
        }
示例#31
0
		internal void Clear()
		{
			m_pgRootGroup = null;
			m_vDeletedObjects = new PwObjectList<PwDeletedObject>();

			m_uuidDataCipher = StandardAesEngine.AesUuid;
			m_caCompression = PwCompressionAlgorithm.GZip;
			m_uKeyEncryptionRounds = PwDefs.DefaultKeyEncryptionRounds;

			m_pwUserKey = null;
			m_memProtConfig = new MemoryProtectionConfig();

			m_vCustomIcons = new List<PwCustomIcon>();
			m_bUINeedsIconUpdate = true;

			m_strName = string.Empty;
			m_dtNameChanged = PwDefs.DtDefaultNow;
			m_strDesc = string.Empty;
			m_dtDescChanged = PwDefs.DtDefaultNow;
			m_strDefaultUserName = string.Empty;
			m_dtDefaultUserChanged = PwDefs.DtDefaultNow;
			m_uMntncHistoryDays = 365;

			m_ioSource = new IOConnectionInfo();
			m_bDatabaseOpened = false;
			m_bModified = false;

			m_pwLastSelectedGroup = PwUuid.Zero;
			m_pwLastTopVisibleGroup = PwUuid.Zero;

			m_bUseRecycleBin = true;
			m_pwRecycleBin = PwUuid.Zero;
			m_dtRecycleBinChanged = PwDefs.DtDefaultNow;
			m_pwEntryTemplatesGroup = PwUuid.Zero;
			m_dtEntryTemplatesChanged = PwDefs.DtDefaultNow;

			m_vCustomData = new StringDictionaryEx();

			m_pbHashOfFileOnDisk = null;
			m_pbHashOfLastIO = null;

			m_bUseFileTransactions = false;
		}
示例#32
0
        private static CompositeKey CreateCompositeKey(ProtectedString password, string keyFilePath)
        {
            CompositeKey key = new CompositeKey();

            if (!password.IsEmpty)
            {
                IUserKey mKeyPass = new KcpPassword(password.ReadUtf8());
                key.AddUserKey(mKeyPass);
            }

            // Load a keyfile for the target database if requested (and add it to the key)
            if (!string.IsNullOrEmpty(keyFilePath))
            {
                IUserKey mKeyFile = new KcpKeyFile(keyFilePath);
                key.AddUserKey(mKeyFile);
            }

            return(key);
        }
        public async Task UpdateComposityKey()
        {
            var compositeKey = new CompositeKey()
            {
                FirstID   = 1,
                SecondID  = 1,
                SomeValue = Guid.NewGuid().ToString()
            };
            var connector = new Connector <CompositeKey>();
            await connector.UpdateAsync(compositeKey);

            var filter = connector.CreateQuery();

            filter.Add(x => x.FirstID, 1);
            filter.Add(x => x.SecondID, 1);
            var result = await connector.FetchSingleAsync(filter);

            Assert.AreEqual(compositeKey.SomeValue, result.SomeValue);
        }
示例#34
0
        public StudentType(QueryFactoryHelper queryFactoryHelper, IDataLoaderContextAccessor dataLoaderContextAccessor)
        {
            Name = "Student";

            Field(h => h.Id).Description("Id");

            Field(h => h.Surname, true).Description("Surname");

            Field(h => h.Forename, true).Description("Forename");

            Field(h => h.CourseId).Description("CourseId");

            Field <CourseType, Course>()
            .Name("course")
            .Description("Related course")
            .ResolveAsync(context =>
            {
                Func <IEnumerable <CompositeKey>, CancellationToken, Task <IDictionary <CompositeKey, Course> > > batchLoaderLogic = async(ids, cancelToken) =>
                {
                    var aggregatedResults = await ChildQueryHelper.Get <Course>("Course", queryFactoryHelper, ids);
                    var dict = new Dictionary <CompositeKey, Course>(new CompositeKey.MyEqualityComparer());
                    foreach (var r in aggregatedResults)
                    {
                        var fkFields = new Dictionary <string, object>()
                        {
                            { "CourseId", r.CourseId }
                        };
                        var key = new CompositeKey(fkFields);
                        dict.TryAdd(key, r);
                    }

                    return(dict);
                };

                var dataLoader   = dataLoaderContextAccessor.Context.GetOrAddBatchLoader("Student_Course", batchLoaderLogic);
                var parentFields = new Dictionary <string, object>()
                {
                    { "CourseId", context.Source.CourseId }
                };
                return(dataLoader.LoadAsync(new CompositeKey(parentFields)));
            });
        }
 /// <summary>
 ///     See <see cref="LeftPlaceholder"></see>
 /// </summary>
 /// <param name="key"> </param>
 /// <param name="mode"> </param>
 /// <returns> </returns>
 private PropagatorResult RightPlaceholder(CompositeKey key, PopulateMode mode)
 {
     return PlaceholderPopulator.Populate(m_right.Placeholder, key, m_rightPlaceholderKey, mode);
 }
            /// <summary>
            ///     Propagate all changes associated with a particular join key.
            /// </summary>
            /// <param name="key"> Key. </param>
            /// <param name="result"> Resulting changes are added to this result. </param>
            private void Propagate(
                CompositeKey key, ChangeNode result, JoinDictionary leftDeletes, JoinDictionary leftInserts,
                JoinDictionary rightDeletes, JoinDictionary rightInserts)
            {
                // Retrieve changes associates with this join key
                Tuple<CompositeKey, PropagatorResult> leftInsert = null;
                Tuple<CompositeKey, PropagatorResult> leftDelete = null;
                Tuple<CompositeKey, PropagatorResult> rightInsert = null;
                Tuple<CompositeKey, PropagatorResult> rightDelete = null;

                var input = Ops.Nothing;

                if (leftInserts.TryGetValue(key, out leftInsert))
                {
                    input |= Ops.LeftInsert;
                }
                if (leftDeletes.TryGetValue(key, out leftDelete))
                {
                    input |= Ops.LeftDelete;
                }
                if (rightInserts.TryGetValue(key, out rightInsert))
                {
                    input |= Ops.RightInsert;
                }
                if (rightDeletes.TryGetValue(key, out rightDelete))
                {
                    input |= Ops.RightDelete;
                }

                // Get propagation rules for the changes
                var insertRule = m_insertRules[input];
                var deleteRule = m_deleteRules[input];

                if (Ops.Unsupported == insertRule
                    || Ops.Unsupported == deleteRule)
                {
                    // If no propagation rules are defined, it suggests an invalid workload (e.g.
                    // a required entity or relationship is missing). In general, such exceptions
                    // should be caught by the RelationshipConstraintValidator, but we defensively
                    // check for problems here regardless. For instance, a 0..1:1..1 self-assocation
                    // implied a stronger constraint that cannot be checked by RelationshipConstraintValidator.

                    // First gather state entries contributing to the problem
                    var stateEntries = new List<IEntityStateEntry>();
                    Action<Tuple<CompositeKey, PropagatorResult>> addStateEntries = (r) =>
                        {
                            if (r != null)
                            {
                                stateEntries.AddRange(
                                    SourceInterpreter.GetAllStateEntries(
                                        r.Item2, m_parent.m_updateTranslator,
                                        m_parent.m_table));
                            }
                        };
                    addStateEntries(leftInsert);
                    addStateEntries(leftDelete);
                    addStateEntries(rightInsert);
                    addStateEntries(rightDelete);

                    throw new UpdateException(Strings.Update_InvalidChanges, null, stateEntries.Cast<ObjectStateEntry>().Distinct());
                }

                // Where needed, substitute null/unknown placeholders. In some of the join propagation
                // rules, we handle the case where a side of the join is 'unknown', or where one side
                // of a join is comprised of an record containing only nulls. For instance, we may update
                // only one extent appearing in a row of a table (unknown), or; we may insert only
                // the left hand side of a left outer join, in which case the right hand side is 'null'.
                if (0 != (Ops.LeftUnknown & insertRule))
                {
                    leftInsert = Tuple.Create(key, LeftPlaceholder(key, PopulateMode.Unknown));
                }
                if (0 != (Ops.LeftUnknown & deleteRule))
                {
                    leftDelete = Tuple.Create(key, LeftPlaceholder(key, PopulateMode.Unknown));
                }
                if (0 != (Ops.RightNullModified & insertRule))
                {
                    rightInsert = Tuple.Create(key, RightPlaceholder(key, PopulateMode.NullModified));
                }
                else if (0 != (Ops.RightNullPreserve & insertRule))
                {
                    rightInsert = Tuple.Create(key, RightPlaceholder(key, PopulateMode.NullPreserve));
                }
                else if (0 != (Ops.RightUnknown & insertRule))
                {
                    rightInsert = Tuple.Create(key, RightPlaceholder(key, PopulateMode.Unknown));
                }

                if (0 != (Ops.RightNullModified & deleteRule))
                {
                    rightDelete = Tuple.Create(key, RightPlaceholder(key, PopulateMode.NullModified));
                }
                else if (0 != (Ops.RightNullPreserve & deleteRule))
                {
                    rightDelete = Tuple.Create(key, RightPlaceholder(key, PopulateMode.NullPreserve));
                }
                else if (0 != (Ops.RightUnknown & deleteRule))
                {
                    rightDelete = Tuple.Create(key, RightPlaceholder(key, PopulateMode.Unknown));
                }

                // Populate elements in join output
                if (null != leftInsert
                    && null != rightInsert)
                {
                    result.Inserted.Add(CreateResultTuple(leftInsert, rightInsert, result));
                }
                if (null != leftDelete
                    && null != rightDelete)
                {
                    result.Deleted.Add(CreateResultTuple(leftDelete, rightDelete, result));
                }
            }
示例#37
0
        public SerializedEntity ReadObject(Dictionary<string,object> keys, OrmSchema schema)
        {
            using (var bucket = GetBucket(schema))
            {
                var compositeKey = new CompositeKey(keys);

                if (!bucket.IndexedObjects.ContainsKey(compositeKey))
                    return null;

                var storedObject = bucket.IndexedObjects[compositeKey];

                return new SerializedEntity(storedObject);
            }
        }
        private void DiagnoseKeyCollision(UpdateCompiler compiler, PropagatorResult change, CompositeKey key, PropagatorResult other)
        {
            KeyManager keyManager = compiler.m_translator.KeyManager;
            CompositeKey otherKey = new CompositeKey(GetKeyConstants(other));

            // determine if the conflict is due to shared principal key values
            bool sharedPrincipal = true;
            for (int i = 0; sharedPrincipal && i < key.KeyComponents.Length; i++)
            {
                int identifier1 = key.KeyComponents[i].Identifier;
                int identifier2 = otherKey.KeyComponents[i].Identifier;

                if (!keyManager.GetPrincipals(identifier1).Intersect(keyManager.GetPrincipals(identifier2)).Any())
                {
                    sharedPrincipal = false;
                }
            }

            if (sharedPrincipal)
            {
                // if the duplication is due to shared principals, there is a duplicate key exception
                var stateEntries = SourceInterpreter.GetAllStateEntries(change, compiler.m_translator, m_table)
                    .Concat(SourceInterpreter.GetAllStateEntries(other, compiler.m_translator, m_table));
                throw EntityUtil.Update(Strings.Update_DuplicateKeys, null, stateEntries);
            }
            else
            {
                // if there are no shared principals, it implies that common dependents are the problem
                HashSet<IEntityStateEntry> commonDependents = null;
                foreach (PropagatorResult keyValue in key.KeyComponents.Concat(otherKey.KeyComponents))
                {
                    var dependents = new HashSet<IEntityStateEntry>();
                    foreach (int dependentId in keyManager.GetDependents(keyValue.Identifier))
                    {
                        PropagatorResult dependentResult;
                        if (keyManager.TryGetIdentifierOwner(dependentId, out dependentResult) &&
                            null != dependentResult.StateEntry)
                        {
                            dependents.Add(dependentResult.StateEntry);
                        }
                    }
                    if (null == commonDependents)
                    {
                        commonDependents = new HashSet<IEntityStateEntry>(dependents);
                    }
                    else
                    {
                        commonDependents.IntersectWith(dependents);
                    }
                }

                // to ensure the exception shape is consistent with constraint violations discovered while processing
                // commands (a more conventional scenario in which different tables are contributing principal values)
                // wrap a DataConstraintException in an UpdateException
                throw EntityUtil.Update(Strings.Update_GeneralExecutionException,
                    EntityUtil.Constraint(Strings.Update_ReferentialConstraintIntegrityViolation), commonDependents);
            }
        }
        // Determines key values for a list of changes. Side effect: populates <see cref="keys" /> which
        // includes an entry for every key involved in a change.
        private Dictionary<CompositeKey, PropagatorResult> ProcessKeys(UpdateCompiler compiler, List<PropagatorResult> changes, Set<CompositeKey> keys)
        {
            Dictionary<CompositeKey, PropagatorResult> map = new Dictionary<CompositeKey, PropagatorResult>(
                compiler.m_translator.KeyComparer);

            foreach (PropagatorResult change in changes)
            {
                // Reassign change to row since we cannot modify iteration variable
                PropagatorResult row = change;

                CompositeKey key = new CompositeKey(GetKeyConstants(row));

                // Make sure we aren't inserting another row with the same key
                PropagatorResult other;
                if (map.TryGetValue(key, out other))
                {
                    DiagnoseKeyCollision(compiler, change, key, other);
                }

                map.Add(key, row);
                keys.Add(key);
            }

            return map;
        }
 /// <summary>
 /// Constructs a new placeholder record for the left hand side of the join. Values taken
 /// from the join key are injected into the record.
 /// </summary>
 /// <param name="key">Key producing the left hand side.</param>
 /// <param name="mode">Mode used to populate the placeholder</param>
 /// <returns>Record corresponding to the type of the left input to the join. Each value in
 /// the record is flagged as <see cref="PropagatorFlags.Unknown" /> except when it is
 /// a component of the key.</returns>
 private PropagatorResult LeftPlaceholder(CompositeKey key, PopulateMode mode)
 {
     return PlaceholderPopulator.Populate(m_left.Placeholder, key, m_leftPlaceholderKey, mode, m_parent.UpdateTranslator);
 }
示例#41
0
        private CompositeKey BuildAggregateKey(Object theObject, Boolean useSource)
        {
            //not a great implementation...we will start with this though
            if (theObject == null)
                throw new DataMapperException("unable to build aggregatekey for object");

            CompositeKey key = new CompositeKey();

            //the order matters but it should be preserved, right?
            foreach (var item in this.PropertyMapList.Where(a => a.IsKey))
            {
                var propertyInfoToUse = useSource ? item.SourcePropertyInfo : item.TargetPropertyInfo;

                var value = propertyInfoToUse.GetValue(theObject, null);

                key.AddKey(propertyInfoToUse.PropertyType, value);
            }

            return key;
        }
示例#42
0
        public ObjectWriteResult WriteObject(SerializedEntity o, bool createNew, OrmSchema schema)
        {
            var result = new ObjectWriteResult();

            using (var bucket = GetBucket(schema))
            {
                if (createNew)
                {
                    foreach (var incrementKey in schema.IncrementKeys.Where(incrementKey => o[incrementKey.MappedName].Convert<long>() == 0))
                    {
                        o[incrementKey.MappedName] = bucket.NextIncrementCounter(incrementKey.FieldName).Convert(incrementKey.FieldType);

                        result.OriginalUpdated = true;
                    }

                    var storedObject = o.AsDictionary();

                    bucket.Objects.Add(storedObject);
                    bucket.IndexedObjects[new CompositeKey(schema,o)] = storedObject;

                    result.Added = true;
                    result.Success = true;
                }
                else
                {
                    if (schema.PrimaryKeys.Length > 0)
                    {
                        for (int i = 0; i < bucket.Objects.Count; i++)
                        {
                            if (schema.PrimaryKeys.All(primaryKey => Equals(bucket.Objects[i][primaryKey.MappedName], o[primaryKey.MappedName])))
                            {
                                var compositeKey = new CompositeKey(schema, o);

                                var storedObject = o.AsDictionary();

                                bucket.Objects[i] = storedObject;
                                bucket.IndexedObjects[compositeKey] = storedObject;
                                result.Success = true;
                                break;
                            }
                        }
                    }
                    else
                    {
                        result.Success = false;
                    }
                }
            }

            return result;
        }