KeyFactory

Namespace: SyncSoft.App
We found 10 examples in language CSharp for this search. You will see 33 fragments of code.

        [Fact]
        public async Task Lookup()
        {
            var db = _fixture.CreateDatastoreDb();
            var keyFactory = db.CreateKeyFactory("lookup_test");
            var entity = new Entity { Key = keyFactory.CreateKey("x"), ["description"] = "predefined_key" };
            db.Insert(entity);

            // Test both sync and async lookup
            Assert.Equal(entity, db.Lookup(entity.Key));
            Assert.Equal(entity, await db.LookupAsync(entity.Key));
        }

        [Fact]
        public void Delete()
        {
            var db = _fixture.CreateDatastoreDb();
            var keyFactory = db.CreateKeyFactory("update_test");

            var insertedKey = db.Insert(new Entity { Key = keyFactory.CreateIncompleteKey(), ["description"] = "original" });
            Assert.NotNull(db.Lookup(insertedKey));
            db.Delete(insertedKey);
            Assert.Null(db.Lookup(insertedKey));
        }

        [Fact]
        public async Task DeleteAsync()
        {
            var db = _fixture.CreateDatastoreDb();
            var keyFactory = db.CreateKeyFactory("update_test");

            var insertedKey = await db.InsertAsync(new Entity { Key = keyFactory.CreateIncompleteKey(), ["description"] = "original" });
            Assert.NotNull(await db.LookupAsync(insertedKey));
            await db.DeleteAsync(insertedKey);
            Assert.Null(await db.LookupAsync(insertedKey));
        }


        [Fact]
        public void KeyQuery()
        {
            string projectId = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Sample: KeyQuery
            KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "Task");
            Query query = new Query("Task")
            {
                Filter = Filter.GreaterThan(DatastoreConstants.KeyProperty, keyFactory.CreateKey("someTask"))
            };
            // End sample
        }

        [Fact]
        public void AncestorQuery()
        {
            string projectId = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Sample: AncestorQuery
            KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "Task");
            Query query = new Query("Task")
            {
                Filter = Filter.HasAncestor(keyFactory.CreateKey("someTask"))
            };
            // End sample
        }


        /// <summary>
        /// Creates new instance of a key implementing <see cref="IKey"/> for the <paramref name="targetType"/>.
        /// </summary>
        /// <param name="targetType">The type for which key is generated.</param>
        /// <returns>Newly generated key for the <paramref name="targetType"/>.</returns>
        public static IKey Create(Type targetType)
        {
            return keyFactory(targetType);
        }


        [Fact]
        public async Task AllocateIdAsync()
        {
            string projectId = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: AllocateIdAsync
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory keyFactory = db.CreateKeyFactory("message");
            Key key = await db.AllocateIdAsync(keyFactory.CreateIncompleteKey());
            // End snippet
        }


        /// <summary>
        /// Creates new instance of a key implementing <see cref="IKey"/> for the <paramref name="targetType"/>.
        /// </summary>
        /// <param name="targetType">The type for which key is generated.</param>
        /// <returns>Newly generated key for the <paramref name="targetType"/>.</returns>
        public static IKey Create(Type targetType)
        {
            return keyFactory(targetType);
        }


        #endregion //Constructors

        #region Methods

        public void Encrypt(string parameter)
        {
            try
            {
                switch (parameter)
                {
                    case "string": MessageFactory.CipheredStringMessage = MessageFactory.StringMessage.EncryptString(KeyFactory); break;
                    case "file": MessageFactory.CipheredFileMessage = MessageFactory.FileMessage.EncryptFile(KeyFactory); break;
                    default: break;
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("Brak wszystkich danych");
            }
        }
        public void Decrypt(string parameter)
        {
            try
            {
                switch (parameter)
                {
                    case "string":
                        {
                            MessageFactory.StringMessage = MessageFactory.CipheredStringMessage.DecryptString(KeyFactory);
                            HashComparer.DecryptedHash = MessageFactory.CipheredStringMessage.DecryptString(KeyFactory).Hash;
                            break;
                        }
                    case "file":
                        {
                            MessageFactory.FileMessage = MessageFactory.CipheredFileMessage.DecryptFile(KeyFactory);
                            HashComparer.DecryptedHash = MessageFactory.CipheredFileMessage.DecryptFile(KeyFactory).Hash;
                            break;
                        }
                    default: break;
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("Brak wszystkich danych");
            }
        }

        [SetUp]
        public void Setup()
        {
            Console.WriteLine("Initalizing Setup for Tests");
        }

        [Test]
        public void TestKeyFactory()
        {
            Key testKey1 = KeyFactory.MakeNewKey();
            Key testKey2 = KeyFactory.MakeNewKey();
            Assert.Pass();
        }

        [Test]
        public void TestKeyNotEqual()
        {
            Key testKey1 = KeyFactory.MakeNewKey();
            Key testKey2 = KeyFactory.MakeNewKey();

            Assert.AreNotSame(testKey1, testKey2);
        }

        [Test]
        public void TestKeyEqualToItself()
        {
            Key testKey1 = KeyFactory.MakeNewKey();
            Key testCopyKey1 = testKey1;
            Assert.AreNotSame(testKey1, testCopyKey1);
        }

        [Test]
        public void TestTryToStart()
        {
            string message = "A Black flying space ship car using real Rocket fuel, tops out at 100 AU in the vacumme of space!";
            Key testKey1 = KeyFactory.MakeNewKey();
            SpaceCar mySpaceCar2 = new SpaceCar(testKey1, Color.Black);
            Assert.AreEqual(mySpaceCar2.GetDescription(), message);
        }


        [Fact]
        public void Lookup_FullPartition()
        {
            var db = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var keyFactory = db.CreateKeyFactory("test");
            var entity = new Entity
            {
                Key = keyFactory.CreateIncompleteKey(),
                ["foo"] = "bar"
            };
            var key = db.Insert(entity);

            var result = db.Lookup(key);
            Assert.NotNull(result);
            Assert.Equal("bar", (string)entity["foo"]);
        }

        [Fact]
        public void Lookup_NamespaceOnly()
        {
            var db = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var keyFactory = db.CreateKeyFactory("test");
            var entity = new Entity
            {
                Key = keyFactory.CreateIncompleteKey(),
                ["foo"] = "bar"
            };
            var insertedKey = db.Insert(entity);

            var lookupKey = new Key { PartitionId = new PartitionId { NamespaceId = _fixture.NamespaceId }, Path = { insertedKey.Path } };
            var result = db.Lookup(lookupKey);
            Assert.NotNull(result);
            Assert.Equal("bar", (string)entity["foo"]);
        }

        [Fact]
        public async Task Lookup_NoPartition()
        {
            // Deliberately in the empty namespace, which won't be cleaned up automatically - hence the db.Delete call later.
            var db = DatastoreDb.Create(_fixture.ProjectId);
            var keyFactory = db.CreateKeyFactory("test");
            var entity = new Entity
            {
                Key = keyFactory.CreateIncompleteKey(),
                ["foo"] = "bar"
            };
            var insertedKey = db.Insert(entity);
            try
            {
                var lookupKey = new Key { Path = { insertedKey.Path } };
                var result = db.Lookup(lookupKey);
                Assert.NotNull(result);
                Assert.Equal("bar", (string)entity["foo"]);

                // And the same lookup asynchronously...
                Assert.Equal(result, await db.LookupAsync(lookupKey));
            }
            finally
            {
                db.Delete(insertedKey);
            }
        }

        [Fact]
        public async Task Lookup()
        {
            var db = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var keyFactory = db.CreateKeyFactory("lookup_test");
            var entity = new Entity { Key = keyFactory.CreateKey("x"), ["description"] = "predefined_key" };
            db.Insert(entity);

            // Test both sync and async lookup
            Assert.Equal(entity, db.Lookup(entity.Key));
            Assert.Equal(entity, await db.LookupAsync(entity.Key));
        }

        [Fact]
        public void RunQuery_NoResults()
        {
            var db = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var query = db.RunQueryLazily(new Query("absent"));
            // Each of the checks below will run the query again, as the query is only lazily
            // evaluated.
            Assert.Equal(0, query.Count());
            var singleResponse = query.AsResponses().Single();
            Assert.Equal(MoreResultsType.NoMoreResults, singleResponse.Batch.MoreResults);
        }

        [Fact]
        public void SyncQueries()
        {
            var db = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var keyFactory = db.CreateKeyFactory("syncqueries");
            using (var transaction = db.BeginTransaction())
            {
                var entities = Enumerable.Range(0, 5)
                    .Select(x => new Entity { Key = keyFactory.CreateIncompleteKey(), ["x"] = x })
                    .ToList();
                transaction.Insert(entities);
                transaction.Commit();
            }

            var query = new Query("syncqueries") { Filter = Filter.LessThan("x", 3) };
            var gql = new GqlQuery { QueryString = "SELECT * FROM syncqueries WHERE x < 3", AllowLiterals = true };

            ValidateQueryResults(db.RunQuery(gql).Entities);
            ValidateQueryResults(db.RunQuery(query).Entities);
            ValidateQueryResults(db.RunQueryLazily(query));
            ValidateQueryResults(db.RunQueryLazily(gql));
        }


        [Fact]
        public void Lookup()
        {
            string projectId = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: Lookup(*,*,*,*)
            KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "book");
            Key key1 = keyFactory.CreateKey("pride_and_prejudice");
            Key key2 = keyFactory.CreateKey("not_present");

            DatastoreClient client = DatastoreClient.Create();
            LookupResponse response = client.Lookup(
                projectId,
                new ReadOptions { ReadConsistency = ReadConsistency.Strong },
                new[] { key1, key2 });
            Console.WriteLine($"Found: {response.Found.Count}");
            Console.WriteLine($"Deferred: {response.Deferred.Count}");
            Console.WriteLine($"Missing: {response.Missing.Count}");
            // End snippet

            Entity entity = response.Found[0].Entity;
            Assert.Equal("Jane Austen", (string)entity["author"]);
            Assert.Equal("Pride and Prejudice", (string)entity["title"]);
        }

        [Fact]
        public void RunQuery()
        {
            string projectId = _fixture.ProjectId;
            PartitionId partitionId = _fixture.PartitionId;
            
            // Snippet: RunQuery(RunQueryRequest,*)
            DatastoreClient client = DatastoreClient.Create();

            RunQueryRequest request = new RunQueryRequest
            {
                ProjectId = projectId,
                PartitionId = partitionId,
                ReadOptions = new ReadOptions { ReadConsistency = ReadConsistency.Eventual },
            };
            // Structured query
            request.Query = new Query("book")
            {
                Filter = Filter.Equal("author", "Jane Austen")
            };
            RunQueryResponse response = client.RunQuery(request);
            foreach (EntityResult result in response.Batch.EntityResults)
            {
                Console.WriteLine(result.Entity);
            }

            // Equivalent GQL query
            request.GqlQuery = new GqlQuery
            {
                QueryString = "SELECT * FROM book WHERE author = @author",
                NamedBindings = { { "author", "Jane Austen" } },
            };
            foreach (EntityResult result in response.Batch.EntityResults)
            {
                Console.WriteLine(result.Entity);
            }
            // End snippet

            Assert.Equal(1, response.Batch.EntityResults.Count);
            Entity entity = response.Batch.EntityResults[0].Entity;
            Assert.Equal("Jane Austen", (string)entity["author"]);
            Assert.Equal("Pride and Prejudice", (string)entity["title"]);
        }

        [Fact]
        public void AddEntity()
        {
            string projectId = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Sample: AddEntity
            DatastoreClient client = DatastoreClient.Create();
            KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "book");
            Entity book1 = new Entity
            {
                Key = keyFactory.CreateIncompleteKey(),
                ["author"] = "Harper Lee",
                ["title"] = "To Kill a Mockingbird",
                ["publication_date"] = new DateTime(1960, 7, 11, 0, 0, 0, DateTimeKind.Utc),
                ["genres"] = new[] { "Southern drama", "Courtroom drama", "Bildungsroman" }
            };
            Entity book2 = new Entity
            {
                Key = keyFactory.CreateIncompleteKey(),
                ["author"] = "Charlotte Brontë",
                ["title"] = "Jane Eyre",
                ["publication_date"] = new DateTime(1847, 10, 16, 0, 0, 0, DateTimeKind.Utc),
                ["genres"] = new[] { "Gothic", "Romance", "Bildungsroman" }
            };

            ByteString transactionId = client.BeginTransaction(projectId).Transaction;
            using (DatastoreTransaction transaction = DatastoreTransaction.Create(client, projectId, namespaceId, transactionId))
            {
                transaction.Insert(book1, book2);
                CommitResponse response = transaction.Commit();
                IEnumerable<Key> insertedKeys = response.MutationResults.Select(r => r.Key);
                Console.WriteLine($"Inserted keys: {string.Join(",", insertedKeys)}");
            }
            // End sample
        }

        [Fact]
        public void AllocateIds()
        {
            string projectId = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: AllocateIds(*,*,*)
            DatastoreClient client = DatastoreClient.Create();
            KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "message");
            AllocateIdsResponse response = client.AllocateIds(projectId,
                new[] { keyFactory.CreateIncompleteKey(), keyFactory.CreateIncompleteKey() }
            );
            Entity entity1 = new Entity { Key = response.Keys[0], ["text"] = "Text 1" };
            Entity entity2 = new Entity { Key = response.Keys[1], ["text"] = "Text 2" };
            // End snippet

            Assert.NotEqual(entity1, entity2);
        }

        [Fact]
        public void NamespaceQuery()
        {
            string projectId = _fixture.ProjectId;

            // Sample: NamespaceQuery
            DatastoreClient client = DatastoreClient.Create();
            PartitionId partitionId = new PartitionId(projectId);
            RunQueryRequest request = new RunQueryRequest
            {
                ProjectId = projectId,
                PartitionId = partitionId,
                Query = new Query(DatastoreConstants.NamespaceKind)
            };
            RunQueryResponse response = client.RunQuery(request);
            foreach (EntityResult result in response.Batch.EntityResults)
            {
                Console.WriteLine(result.Entity.Key.Path.Last().Name);
            }
            // End sample
        }

        [Fact]
        public void KindQuery()
        {
            string projectId = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;
            PartitionId partitionId = new PartitionId(projectId, namespaceId);

            // Sample: KindQuery
            DatastoreClient client = DatastoreClient.Create();
            RunQueryRequest request = new RunQueryRequest
            {
                ProjectId = projectId,
                PartitionId = partitionId,
                Query = new Query(DatastoreConstants.KindKind)
            };
            RunQueryResponse response = client.RunQuery(request);
            foreach (EntityResult result in response.Batch.EntityResults)
            {
                Console.WriteLine(result.Entity.Key.Path.Last().Name);
            }
            // End sample
        }


        #endregion Lifespan

        #region Protected Methods

        /// <summary>
        /// Returns the key prefixed with the type of object being cached.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        internal protected static string QualifiedKey( string key )
        {
            return $"{KeyPrefix}:{key}";
        }

        /// <summary>
        /// Gets an item from cache, and if not found, executes the itemFactory to create item and add to cache.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="itemFactory">The item factory.</param>
        /// <param name="keyFactory">The key factory to create a list of keys for the type. This will only be used if a list does not already exist.</param>
        /// <returns></returns>
        internal protected static T GetOrAddExisting( int key, Func<T> itemFactory, Func<List<string>> keyFactory = null )
        {
            return GetOrAddExisting( key.ToString(), itemFactory, keyFactory );
        }

        /// <summary>
        /// Gets an item from cache, and if not found, executes the itemFactory to create item and add to cache with an expiration timespan.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="itemFactory">The item factory.</param>
        /// <param name="expiration">The expiration.</param>
        /// <returns></returns>
        [RockObsolete( "1.11" )]
        [Obsolete( "Use the Lifespan properties instead of the expiration parameter." )]
        internal protected static T GetOrAddExisting( int key, Func<T> itemFactory, TimeSpan expiration )
        {
            return GetOrAddExisting( key, itemFactory );
        }

        /// <summary>
        /// Gets an item from cache, and if not found, executes the itemFactory to create item and add to cache with an expiration timespan.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="itemFactory">The item factory.</param>
        /// <param name="expiration">The expiration.</param>
        /// <returns></returns>
        [RockObsolete( "1.11" )]
        [Obsolete( "Use the Lifespan properties instead of the expiration parameter." )]
        internal protected static T GetOrAddExisting( string key, Func<T> itemFactory, TimeSpan expiration )
        {
            return GetOrAddExisting( key, itemFactory );
        }

        /// <summary>
        /// Gets an item from cache, and if not found, executes the itemFactory to create item and add to cache.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="itemFactory">The item factory.</param>
        /// <param name="keyFactory">The key factory to create a list of keys for the type. This will only be used if a list does not already exist.</param>
        /// <returns></returns>
        internal protected static T GetOrAddExisting( string key, Func<T> itemFactory, Func<List<string>> keyFactory = null )
        {
            string qualifiedKey = QualifiedKey( key );
            var value = RockCacheManager<T>.Instance.Get( qualifiedKey );

            if ( value != null )
            {
                return value;
            }

            if ( itemFactory == null ) return default( T );

            value = itemFactory();
            if ( value != null )
            {
                UpdateCacheItem( key, value, keyFactory );
            }

            return value;
        }

        /// <summary>
        /// Updates the cache item.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="item">The item.</param>
        /// <param name="keyFactory">The key factory to create a list of keys for the type. This will only be used if a list does not already exist.</param>
        internal protected static void UpdateCacheItem( string key, T item, Func<List<string>> keyFactory = null )
        {
            string qualifiedKey = QualifiedKey( key );

            var lifespan = ( ( item as IHasLifespan )?.Lifespan ) ?? DefaultLifespan;

            // Add the item to cache
            RockCacheManager<T>.Instance.AddOrUpdate( qualifiedKey, item, lifespan );

            // Do any postcache processing that this item cache type may need to do
            item.PostCached();

            AddToAllIds( key, keyFactory );
        }

SyncSoft.App.Messaging.KeyFactory : Object

Methods :

public static String CreateLockKey(Guid correlationId = )
public static String CreateResultKey(Guid correlationId = , Boolean isRollback = False)
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods