KeyFactory

Namespace: zipkin4net
We found 10 examples in language CSharp for this search. You will see 49 fragments of code.

Other methods


        /// <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);
        }


        /// <summary>
        /// Sets <paramref name="keyFactory"/> to be used for generating new keys and <paramref name="emptyFactory"/> for generating empty keys.
        /// </summary>
        /// <param name="keyFactory">The key generator function.</param>
        /// <param name="emptyFactory">The empty key generator function.</param>
        public static void Set(Func<Type, IKey> keyFactory, Func<Type, IKey> emptyFactory)
        {
            Ensure.NotNull(keyFactory, "keyFactory");
            Ensure.NotNull(emptyFactory, "emptyFactory");
            KeyFactory.keyFactory = keyFactory;
            KeyFactory.emptyFactory = emptyFactory;
        }

        /// <summary>
        /// Sets key factory to use <see cref="GuidKey"/> and type fullname with assembly name (without version and public key).
        /// </summary>
        public static void SetGuidKeyWithTypeFullNameAndAssembly()
        {
            keyFactory = targetType => GuidKey.Create(Guid.NewGuid(), targetType.FullName + ", " + targetType.GetTypeInfo().Assembly.GetName().Name);
            emptyFactory = targetType => GuidKey.Empty(targetType.FullName + ", " + targetType.GetTypeInfo().Assembly.GetName().Name);
        }

        /// <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);
        }

        /// <summary>
        /// Creates new empty key isntance.
        /// </summary>
        /// <param name="targetType">The type for which key is generated.</param>
        /// <returns>New empty key isntance.</returns>
        public static IKey Empty(Type targetType)
        {
            return emptyFactory(targetType);
        }


        [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 );
        }


        public Task<SignOperationResult> Sign(ICollection<KeySignRequest> requests, CancellationToken cancellationToken = new CancellationToken(),
            bool invididualAttestation = false)
        {
            var signer = new MultiKeyOperation<SignOperationResult>(
                keyFactory,
                (keyId, ct) => new SignOperation(keyId, requests).SignAsync(ct),
                r => r.IsSuccess
                );
            return signer.RunOperationAsync(cancellationToken);
        }

        public Task<RegisterOperationResult> Register(ICollection<KeyRegisterRequest> registerRequests, ICollection<KeySignRequest> signRequests,
            CancellationToken cancellationToken = new CancellationToken())
        {
            var signer = new MultiKeyOperation<RegisterOperationResult>(
                keyFactory,
                (keyId, ct) => new RegisterOperation(keyId, registerRequests).AuthenticateAsync(ct),
                r => r.IsSuccess
                );
            return signer.RunOperationAsync(cancellationToken);
        }


        /// <summary>Per test initialization.</summary>
        [TestInitialize]
        public void InitializeTest()
        {
            // Create index store stub and factory stub
            this.indexStore = MockRepository.GenerateStub<IIndexStore>();
            this.indexStoreFactory = MockRepository.GenerateStub<IIndexStoreFactory>();
            this.indexStoreFactory.Stub(f => f.GetIndexStore()).Return(this.indexStore);

            // Create key rule stub to return partition
            this.keyRule = MockRepository.GenerateStub<IKeyRule>();
            this.keyRule.Stub(f => f.GenerateKeyField(Arg<IEntity>.Is.Anything)).Return(this.partitionValue);

            // Create key rule factory stub to return key rule
            this.keyRuleFactory = MockRepository.GenerateStub<IKeyRuleFactory>();
            this.keyRuleFactory.Stub(
                f => f.GetKeyRule(Arg<IEntity>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything))
                .Return(this.keyRule);

            this.azureStorageKey = new AzureStorageKey(this.expectedStorageAccountName, this.tableName, this.partition, this.rowId);
        }

        /// <summary>Test Xml key factory injection construction</summary>
        [TestMethod]
        public void XmlInjectionConstructor()
        {
            // Call key factory constructor with data store
            var keyFactory = new XmlStorageKeyFactory(this.indexStoreFactory, this.keyRuleFactory);

            // Assert that it is using the correct data store
            Assert.IsNotNull(keyFactory);
            Assert.AreSame(this.indexStoreFactory, keyFactory.IndexStoreFactory);
            Assert.AreSame(this.keyRuleFactory, keyFactory.KeyRuleFactory);
        }

        /// <summary>Test Azure key factory injection construction</summary>
        [TestMethod]
        public void AzureInjectionConstructor()
        {
            // Call key factory constructor with data store
            var keyFactory = new AzureStorageKeyFactory(this.indexStoreFactory, this.keyRuleFactory);

            // Assert that it is using the correct data store
            Assert.IsNotNull(keyFactory);
            Assert.AreSame(this.indexStoreFactory, keyFactory.IndexStoreFactory);
            Assert.AreSame(this.keyRuleFactory, keyFactory.KeyRuleFactory);
        }

        /// <summary>Test S3 key factory injection construction</summary>
        [TestMethod]
        public void S3InjectionConstructor()
        {
            // Call key factory constructor with data store
            var keyFactory = new S3StorageKeyFactory(this.indexStoreFactory, this.keyRuleFactory);

            // Assert that it is using the correct data store
            Assert.IsNotNull(keyFactory);
            Assert.AreSame(this.indexStoreFactory, keyFactory.IndexStoreFactory);
            Assert.AreSame(this.keyRuleFactory, keyFactory.KeyRuleFactory);
        }

        /// <summary>Test to build a new Xml storage key for a company.</summary>
        [TestMethod]
        public void XmlBuildNewCompanyStorageKey()
        {
            // Create entity
            var entity = this.BuildNewEntity<XmlRawEntity>();

            // Create concrete IStorageKeyFactory using the stubbed key rule stack
            var keyFactory = new XmlStorageKeyFactory(this.indexStoreFactory, this.keyRuleFactory);

            // Create entity key - these will be a little different because we partially populate the entity key
            // with table name. It would not be available in the index yet at this point.
            var partialKey = new XmlStorageKey(this.expectedStorageAccountName, this.tableName, string.Empty, Guid.Empty);
            entity.Key = partialKey;
            var key = (XmlStorageKey)keyFactory.BuildNewStorageKey(this.expectedStorageAccountName, this.companyExternalId, entity);

            Assert.AreEqual(this.expectedStorageAccountName, key.StorageAccountName);
            Assert.AreEqual(partialKey.TableName, key.TableName);
            Assert.AreEqual(this.partitionValue, key.Partition);
            Assert.AreNotEqual(Guid.Empty, (Guid)key.RowId);
        }

        /// <summary>Test to build a new Azure storage key for a company.</summary>
        [TestMethod]
        public void AzureBuildNewCompanyStorageKey()
        {
            // Create entity
            var entity = this.BuildNewEntity<Entity>();

            // Create concrete IStorageKeyFactory using the stubbed key rule stack
            var keyFactory = new AzureStorageKeyFactory(this.indexStoreFactory, this.keyRuleFactory);

            // Create entity key - these will be a little different because we partially populate the entity key
            // with table name. It would not be available in the index yet at this point.
            var partialKey = new AzureStorageKey(this.expectedStorageAccountName, this.tableName, string.Empty, Guid.Empty);
            entity.Key = partialKey;
            var key = (AzureStorageKey)keyFactory.BuildNewStorageKey(this.expectedStorageAccountName, this.companyExternalId, entity);

            Assert.AreEqual(this.expectedStorageAccountName, key.StorageAccountName);
            Assert.AreEqual(partialKey.TableName, key.TableName);
            Assert.AreEqual(this.partitionValue, key.Partition);
            Assert.AreNotEqual(Guid.Empty, (Guid)key.RowId);
        }

		
		public static KeyFactory GetInstance (string id)
		{
			switch (id.ToUpper ()) {
			case "DSA": return new DSAKeyFactory ();
			case "DH": return new DHKeyFactory ();
			case "RSA": return new RSAKeyFactory ();
			}
			throw new NotSupportedException ();
		}
		
		public abstract PublicKey GeneratePublic (KeySpec key);
		
		public abstract PrivateKey GeneratePrivate (KeySpec key);
		public override PublicKey GeneratePublic (KeySpec key)
		{
			DSAPublicKeySpec spec = (DSAPublicKeySpec) key;
			DSAParameters dsp = new DSAParameters ();
			dsp.G = spec.GetG ().GetBytes ();
			dsp.P = spec.GetP ().GetBytes ();
			dsp.Q = spec.GetQ ().GetBytes ();
			dsp.Y = spec.GetY ().GetBytes ();
			return new DSAPublicKey (dsp);
		}
		
		public override PrivateKey GeneratePrivate (KeySpec key)
		{
			DSAPrivateKeySpec spec = (DSAPrivateKeySpec) key;
			DSAParameters dsp = new DSAParameters ();
			dsp.G = spec.GetG ().GetBytes ();
			dsp.P = spec.GetP ().GetBytes ();
			dsp.Q = spec.GetQ ().GetBytes ();
			dsp.X = spec.GetX ().GetBytes ();
			return new DSAPrivateKey (dsp);
		}
		public override PublicKey GeneratePublic (KeySpec key)
		{
			DHPublicKeySpec spec = (DHPublicKeySpec) key;
			return new DHPublicKey (spec.Y);
		}


        #region IFixedLengthKey Members

        public void Write(BinaryWriter writer)
        {
            writer.Write( _key );
        }

        public void Read(BinaryReader reader)
        {
            _key = reader.ReadInt32();
        }

        public int CompareTo(object obj)
        {
            int result = _key.CompareTo( ((TestKey)obj)._key );
            return result;
        }

        public IFixedLengthKey FactoryMethod( BinaryReader reader )
        {
            TestKey testKey = new TestKey();
            testKey.Read( reader );
            return testKey;
        }
        public IFixedLengthKey FactoryMethod( )
        {
            return new TestKey( _key );
        }

        public void SetIntKey( int key )
        {
            _key = key;
        }


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

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

            IReadOnlyList<Entity> entities = db.Lookup(key1, key2);
            Console.WriteLine(entities[0]); // Pride and Prejudice entity
            Console.WriteLine(entities[1]); // Nothing (value is null reference)
            // End snippet

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

        // See-also: Lookup(*)
        // Member: Lookup(IEnumerable<Key>, *, *)
        // Member: Lookup(Key, *, *)
        // See [Lookup](ref) for an example using an alternative overload.
        // End see-also

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

            // Snippet: LookupAsync(*)
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory keyFactory = db.CreateKeyFactory("book");
            Key key1 = keyFactory.CreateKey("pride_and_prejudice");
            Key key2 = keyFactory.CreateKey("not_present");

            IReadOnlyList<Entity> entities = await db.LookupAsync(key1, key2);
            Console.WriteLine(entities[0]); // Pride and Prejudice entity
            Console.WriteLine(entities[1]); // Nothing (value is null reference)
            // End snippet

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

        // See-also: LookupAsync(*)
        // Member: LookupAsync(IEnumerable<Key>, *, *)
        // Member: LookupAsync(Key, *, *)
        // See [LookupAsync](ref) for an example using an alternative overload.
        // End see-also

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

            // Snippet: RunQueryLazily(Query,*,*)
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);
            Query query = new Query("book")
            {
                Filter = Filter.Equal("author", "Jane Austen")
            };
            LazyDatastoreQuery results = db.RunQueryLazily(query);
            // LazyDatastoreQuery implements IEnumerable<Entity>, but you can
            // call AsResponses() to see the raw RPC responses, or
            // GetAllResults() to get all the results into memory, complete with
            // the end cursor and the reason for the query finishing.
            foreach (Entity entity in results)
            {
                Console.WriteLine(entity);
            }
            // End snippet

            // This will run the query again, admittedly...
            List<Entity> entities = results.ToList();
            Assert.Equal(1, entities.Count);
            Entity book = entities[0];
            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }

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

            // Snippet: RunQueryLazilyAsync(Query,*,*)
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);
            Query query = new Query("book")
            {
                Filter = Filter.Equal("author", "Jane Austen")
            };
            AsyncLazyDatastoreQuery results = db.RunQueryLazilyAsync(query);
            // AsyncLazyDatastoreQuery implements IAsyncEnumerable<Entity>, but you can
            // call AsResponses() to see the raw RPC responses, or
            // GetAllResultsAsync() to get all the results into memory, complete with
            // the end cursor and the reason for the query finishing.
            await results.ForEachAsync(entity =>
            {
                Console.WriteLine(entity);
            });
            // End snippet

            // This will run the query again, admittedly...
            List<Entity> entities = await results.ToList();
            Assert.Equal(1, entities.Count);
            Entity book = entities[0];
            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }

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

            // Snippet: RunQueryLazily(GqlQuery,*,*)
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);
            GqlQuery gqlQuery = new GqlQuery
            {
                QueryString = "SELECT * FROM book WHERE author = @author",
                NamedBindings = { { "author", "Jane Austen" } },
            };
            LazyDatastoreQuery results = db.RunQueryLazily(gqlQuery);
            // LazyDatastoreQuery implements IEnumerable<Entity>, but you can
            // call AsResponses() to see the raw RPC responses, or
            // GetAllResults() to get all the results into memory, complete with
            // the end cursor and the reason for the query finishing.
            foreach (Entity entity in results)
            {
                Console.WriteLine(entity);
            }
            // End snippet

            // This will run the query again, admittedly...
            List<Entity> entities = results.ToList();
            Assert.Equal(1, entities.Count);
            Entity book = entities[0];
            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }

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

            // Snippet: RunQueryLazilyAsync(GqlQuery,*,*)
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);
            GqlQuery gqlQuery = new GqlQuery
            {
                QueryString = "SELECT * FROM book WHERE author = @author",
                NamedBindings = { { "author", "Jane Austen" } },
            };
            AsyncLazyDatastoreQuery results = db.RunQueryLazilyAsync(gqlQuery);
            // AsyncLazyDatastoreQuery implements IAsyncEnumerable<Entity>, but you can
            // call AsResponses() to see the raw RPC responses, or
            // GetAllResultsAsync() to get all the results into memory, complete with
            // the end cursor and the reason for the query finishing.
            await results.ForEachAsync(entity =>
            {
                Console.WriteLine(entity);
            });
            // End snippet

            // This will run the query again, admittedly...
            List<Entity> entities = await results.ToList();
            Assert.Equal(1, entities.Count);
            Entity book = entities[0];
            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }

zipkin4net.Propagation.KeyFactory<K> : ICloneable, ISerializable

Constructors :

public KeyFactory(Object object = , IntPtr method = )

Methods :

public K Invoke(String key = )
public IAsyncResult BeginInvoke(String key = , AsyncCallback callback = , Object object = )
public K EndInvoke(IAsyncResult result = )
public Void GetObjectData(SerializationInfo info = , StreamingContext context = )
public Boolean Equals(Object obj = )
public Delegate[] GetInvocationList()
public Int32 GetHashCode()
public Object get_Target()
public Object Clone()
public Object DynamicInvoke(Object[] args = )
public MethodInfo get_Method()
public Type GetType()
public String ToString()